Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Create 3cx integration

Acho Arnold5c216816aa91
diff --git a/api/pkg/di/container.go b/api/pkg/di/container.go
index 40d6e210..6e563926 100644
--- a/api/pkg/di/container.go
+++ b/api/pkg/di/container.go
@@ -129,6 +129,7 @@ func NewContainer(projectID string, version string) (container *Container) {
container.RegisterWebhookListeners()
container.RegisterLemonsqueezyRoutes()
+ container.RegisterIntegration3CXRoutes()
container.RegisterDiscordRoutes()
container.RegisterDiscordListeners()
@@ -165,6 +166,12 @@ func (container *Container) App() (app *fiber.App) {
return app
}
+// BearerAPIKeyMiddleware creates a new instance of middlewares.BearerAPIKeyAuth
+func (container *Container) BearerAPIKeyMiddleware() fiber.Handler {
+ container.logger.Debug("creating middlewares.BearerAPIKeyAuth")
+ return middlewares.BearerAPIKeyAuth(container.Logger(), container.Tracer(), container.UserRepository())
+}
+
// AuthenticatedMiddleware creates a new instance of middlewares.Authenticated
func (container *Container) AuthenticatedMiddleware() fiber.Handler {
container.logger.Debug("creating middlewares.Authenticated")
@@ -268,6 +275,10 @@ func (container *Container) DB() (db *gorm.DB) {
container.logger.Fatal(stacktrace.Propagate(err, fmt.Sprintf("cannot migrate %T", &entities.Discord{})))
}
+ if err = db.AutoMigrate(&entities.Integration3CX{}); err != nil {
+ container.logger.Fatal(stacktrace.Propagate(err, fmt.Sprintf("cannot migrate %T", &entities.Integration3CX{})))
+ }
+
return container.db
}
@@ -883,6 +894,18 @@ func (container *Container) LemonsqueezyHandler() (handler *handlers.Lemonsqueez
)
}
+// Integration3CXHandler creates a new instance of handlers.Integration3CXHandler
+func (container *Container) Integration3CXHandler() (handler *handlers.Integration3CXHandler) {
+ container.logger.Debug(fmt.Sprintf("creating %T", handler))
+
+ return handlers.NewIntegration3CxHandler(
+ container.Logger(),
+ container.Tracer(),
+ container.MessageService(),
+ container.BillingService(),
+ )
+}
+
// DiscordHandler creates a new instance of handlers.DiscordHandler
func (container *Container) DiscordHandler() (handler *handlers.DiscordHandler) {
container.logger.Debug(fmt.Sprintf("creating %T", handler))
@@ -934,6 +957,12 @@ func (container *Container) RegisterLemonsqueezyRoutes() {
container.LemonsqueezyHandler().RegisterRoutes(container.App())
}
+// RegisterIntegration3CXRoutes registers routes for the /integration/3cx prefix
+func (container *Container) RegisterIntegration3CXRoutes() {
+ container.logger.Debug(fmt.Sprintf("registering [%T] routes", &handlers.Integration3CXHandler{}))
+ container.Integration3CXHandler().RegisterRoutes(container.App(), container.BearerAPIKeyMiddleware(), container.AuthenticatedMiddleware())
+}
+
// RegisterDiscordRoutes registers routes for the /discord prefix
func (container *Container) RegisterDiscordRoutes() {
container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.DiscordHandler{}))
diff --git a/api/pkg/entities/integration_3cx.go b/api/pkg/entities/integration_3cx.go
new file mode 100644
index 00000000..7cfb3796
--- /dev/null
+++ b/api/pkg/entities/integration_3cx.go
@@ -0,0 +1,16 @@
+package entities
+
+import (
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// Integration3CX stores the discord integration of a user
+type Integration3CX struct {
+ ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`
+ UserID UserID `json:"user_id" gorm:"index" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`
+ WebhookURL string `json:"webhook_url" example:"https://org.3cx.com.au/sms/generic/123"`
+ CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`
+ UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`
+}
diff --git a/api/pkg/handlers/integration_3cx_handler.go b/api/pkg/handlers/integration_3cx_handler.go
new file mode 100644
index 00000000..c651924e
--- /dev/null
+++ b/api/pkg/handlers/integration_3cx_handler.go
@@ -0,0 +1,83 @@
+package handlers
+
+import (
+ "fmt"
+
+ "github.com/NdoleStudio/httpsms/pkg/requests"
+ "github.com/davecgh/go-spew/spew"
+
+ "github.com/NdoleStudio/httpsms/pkg/services"
+ "github.com/NdoleStudio/httpsms/pkg/telemetry"
+ "github.com/gofiber/fiber/v2"
+ "github.com/palantir/stacktrace"
+)
+
+// Integration3CXHandler handles 3CX events
+type Integration3CXHandler struct {
+ handler
+ logger telemetry.Logger
+ tracer telemetry.Tracer
+ messageService *services.MessageService
+ billingService *services.BillingService
+}
+
+// NewIntegration3CxHandler creates a new Integration3CXHandler
+func NewIntegration3CxHandler(
+ logger telemetry.Logger,
+ tracer telemetry.Tracer,
+ messageService *services.MessageService,
+ billingService *services.BillingService,
+) (h *Integration3CXHandler) {
+ return &Integration3CXHandler{
+ logger: logger.WithService(fmt.Sprintf("%T", h)),
+ tracer: tracer,
+ messageService: messageService,
+ billingService: billingService,
+ }
+}
+
+// RegisterRoutes registers the routes for the MessageHandler
+func (h *Integration3CXHandler) RegisterRoutes(app *fiber.App, middlewares ...fiber.Handler) {
+ router := app.Group("integration/3cx/")
+ router.Post("/messages", h.computeRoute(middlewares, h.Messages)...)
+}
+
+// Messages consumes a 3cx event
+// @Summary Sends a 3CX SMS message
+// @Description Sends an SMS message from the 3CX platform
+// @Tags 3CXIntegration
+// @Accept json
+// @Produce json
+// @Success 204 {object} responses.NoContent
+// @Failure 400 {object} responses.BadRequest
+// @Failure 401 {object} responses.Unauthorized
+// @Failure 422 {object} responses.UnprocessableEntity
+// @Failure 500 {object} responses.InternalServerError
+// @Router /integration/3cx/messages [post]
+func (h *Integration3CXHandler) Messages(c *fiber.Ctx) error {
+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
+ defer span.End()
+
+ spew.Dump(string(c.Body()))
+
+ var request requests.Integration3CXMessage
+ if err := c.BodyParser(&request); err != nil {
+ msg := fmt.Sprintf("cannot marshall [%s] into %T", c.Body(), request)
+ ctxLogger.Warn(stacktrace.Propagate(err, msg))
+ return h.responseBadRequest(c, err)
+ }
+
+ if msg := h.billingService.IsEntitled(ctx, h.userIDFomContext(c)); msg != nil {
+ ctxLogger.Warn(stacktrace.NewError(fmt.Sprintf("user with ID [%s] can't send a [3cx] message", h.userIDFomContext(c))))
+ return h.responsePaymentRequired(c, *msg)
+ }
+
+ message, err := h.messageService.SendMessage(ctx, request.ToMessageSendParams(h.userIDFomContext(c), c.OriginalURL()))
+ if err != nil {
+ msg := fmt.Sprintf("cannot send [3cx] message with paylod [%s]", c.Body())
+ ctxLogger.Error(stacktrace.Propagate(err, msg))
+ return h.responseInternalServerError(c)
+ }
+
+ return h.responseOK(c, "message added to queue", message)
+}
diff --git a/api/pkg/middlewares/bearer_api_key_auth_middleware.go b/api/pkg/middlewares/bearer_api_key_auth_middleware.go
new file mode 100644
index 00000000..e12face7
--- /dev/null
+++ b/api/pkg/middlewares/bearer_api_key_auth_middleware.go
@@ -0,0 +1,41 @@
+package middlewares
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/NdoleStudio/httpsms/pkg/repositories"
+ "github.com/NdoleStudio/httpsms/pkg/telemetry"
+ "github.com/gofiber/fiber/v2"
+ "github.com/palantir/stacktrace"
+)
+
+// BearerAPIKeyAuth authenticates an API key using the Bearer header
+func BearerAPIKeyAuth(logger telemetry.Logger, tracer telemetry.Tracer, userRepository repositories.UserRepository) fiber.Handler {
+ logger = logger.WithService("middlewares.APIKeyAuth")
+
+ return func(c *fiber.Ctx) error {
+ ctx, span := tracer.StartFromFiberCtx(c, "middlewares.APIKeyAuth")
+ defer span.End()
+
+ ctxLogger := tracer.CtxLogger(logger, span)
+
+ apiKey := strings.TrimSpace(strings.Replace(c.Get(authHeaderBearer), bearerScheme, "", 1))
+ if len(apiKey) == 0 {
+ span.AddEvent(fmt.Sprintf("the request header has no [%s] api key", authHeaderAPIKey))
+ return c.Next()
+ }
+
+ authUser, err := userRepository.LoadAuthUser(ctx, apiKey)
+ if err != nil {
+ ctxLogger.Error(stacktrace.Propagate(err, fmt.Sprintf("cannot load user with api key [%s] using header [%s]", apiKey, c.Get(authHeaderBearer))))
+ return c.Next()
+ }
+
+ c.Locals(ContextKeyAuthUserID, authUser)
+
+ ctxLogger.Info(fmt.Sprintf("[%T] set successfully for user with ID [%s]", authUser, authUser.ID))
+
+ return c.Next()
+ }
+}
diff --git a/api/pkg/repositories/gorm_integration_3cx_repository.go b/api/pkg/repositories/gorm_integration_3cx_repository.go
new file mode 100644
index 00000000..8103ef4d
--- /dev/null
+++ b/api/pkg/repositories/gorm_integration_3cx_repository.go
@@ -0,0 +1,44 @@
+package repositories
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+ "github.com/NdoleStudio/httpsms/pkg/telemetry"
+ "github.com/palantir/stacktrace"
+ "gorm.io/gorm"
+)
+
+// gormIntegration3CxRepository is responsible for persisting entities.Integration3CX
+type gormIntegration3CxRepository struct {
+ logger telemetry.Logger
+ tracer telemetry.Tracer
+ db *gorm.DB
+}
+
+// NewGormIntegration3CXRepository creates the GORM version of the Integration3CxRepository
+func NewGormIntegration3CXRepository(
+ logger telemetry.Logger,
+ tracer telemetry.Tracer,
+ db *gorm.DB,
+) Integration3CxRepository {
+ return &gormIntegration3CxRepository{
+ logger: logger.WithService(fmt.Sprintf("%T", &gormIntegration3CxRepository{})),
+ tracer: tracer,
+ db: db,
+ }
+}
+
+// Save an entities.Integration3CX
+func (repository *gormIntegration3CxRepository) Save(ctx context.Context, integration *entities.Integration3CX) error {
+ ctx, span := repository.tracer.Start(ctx)
+ defer span.End()
+
+ if err := repository.db.WithContext(ctx).Save(integration).Error; err != nil {
+ msg := fmt.Sprintf("cannot save [%T] with ID [%s]", integration, integration.ID)
+ return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ return nil
+}
diff --git a/api/pkg/repositories/integration_3cx_repository.go b/api/pkg/repositories/integration_3cx_repository.go
new file mode 100644
index 00000000..9a7e3557
--- /dev/null
+++ b/api/pkg/repositories/integration_3cx_repository.go
@@ -0,0 +1,13 @@
+package repositories
+
+import (
+ "context"
+
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+)
+
+// Integration3CxRepository loads and persists an entities.Integration3CX
+type Integration3CxRepository interface {
+ // Save an entities.Integration3CX
+ Save(ctx context.Context, heartbeat *entities.Integration3CX) error
+}
diff --git a/api/pkg/requests/integration_3cx_message_request.go b/api/pkg/requests/integration_3cx_message_request.go
new file mode 100644
index 00000000..664e2fed
--- /dev/null
+++ b/api/pkg/requests/integration_3cx_message_request.go
@@ -0,0 +1,40 @@
+package requests
+
+import (
+ "time"
+
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+
+ "github.com/nyaruka/phonenumbers"
+
+ "github.com/NdoleStudio/httpsms/pkg/services"
+)
+
+// Integration3CXMessage is the payload for sending and SMS message via 3CX
+type Integration3CXMessage struct {
+ request
+ From string `json:"from" example:"+18005550199"`
+ To string `json:"to" example:"+18005550100"`
+ Text string `json:"text" example:"This is a sample text message"`
+}
+
+// Sanitize sets defaults to MessageReceive
+func (input *Integration3CXMessage) Sanitize() Integration3CXMessage {
+ input.To = input.sanitizeAddress(input.To)
+ input.From = input.sanitizeAddress(input.From)
+ return *input
+}
+
+// ToMessageSendParams converts Integration3CXMessage to services.MessageSendParams
+func (input *Integration3CXMessage) ToMessageSendParams(userID entities.UserID, source string) services.MessageSendParams {
+ from, _ := phonenumbers.Parse(input.From, phonenumbers.UNKNOWN_REGION)
+ return services.MessageSendParams{
+ Source: source,
+ Owner: *from,
+ RequestID: input.sanitizeStringPointer("integration-3cx"),
+ UserID: userID,
+ RequestReceivedAt: time.Now().UTC(),
+ Contact: input.sanitizeAddress(input.To),
+ Content: input.Text,
+ }
+}