2
0

customer.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package billing
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/handlers"
  6. "github.com/porter-dev/porter/api/server/shared"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/server/shared/config"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/models"
  11. "github.com/porter-dev/porter/internal/telemetry"
  12. )
  13. // CreateBillingCustomerHandler will create a new handler
  14. // for creating customers in the billing provider
  15. type CreateBillingCustomerHandler struct {
  16. handlers.PorterHandlerReadWriter
  17. }
  18. // NewCreateBillingCustomerIfNotExists will create a new CreateBillingCustomerIfNotExists
  19. func NewCreateBillingCustomerIfNotExists(
  20. config *config.Config,
  21. decoderValidator shared.RequestDecoderValidator,
  22. writer shared.ResultWriter,
  23. ) *CreateBillingCustomerHandler {
  24. return &CreateBillingCustomerHandler{
  25. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  26. }
  27. }
  28. func (c *CreateBillingCustomerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. ctx, span := telemetry.NewSpan(r.Context(), "create-billing-customer-endpoint")
  30. defer span.End()
  31. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  32. request := &types.CreateBillingCustomerRequest{}
  33. if ok := c.DecodeAndValidate(w, r, request); !ok {
  34. return
  35. }
  36. // There is no easy way to pass environment variables to the frontend,
  37. // so for now pass via the backend. This is acceptable because the key is
  38. // meant to be public
  39. publishableKey := c.Config().BillingManager.GetPublishableKey()
  40. if proj.BillingID != "" {
  41. c.WriteResult(w, r, publishableKey)
  42. return
  43. }
  44. // Create customer in Stripe
  45. customerID, err := c.Config().BillingManager.CreateCustomer(request.UserEmail, proj)
  46. if err != nil {
  47. err := telemetry.Error(ctx, span, err, "error creating billing customer")
  48. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error creating billing customer: %w", err)))
  49. return
  50. }
  51. // Update the project record with the customer ID
  52. proj.BillingID = customerID
  53. _, err = c.Repo().Project().UpdateProject(proj)
  54. if err != nil {
  55. err := telemetry.Error(ctx, span, err, "error updating project")
  56. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error updating project: %w", err)))
  57. return
  58. }
  59. c.WriteResult(w, r, publishableKey)
  60. }