Bladeren bron

pass stripe key via backend routes

Mauricio Araujo 2 jaren geleden
bovenliggende
commit
db68bd7edc

+ 6 - 2
api/server/handlers/billing/customer.go

@@ -41,8 +41,12 @@ func (c *CreateBillingCustomerHandler) ServeHTTP(w http.ResponseWriter, r *http.
 		return
 	}
 
+	// There is no easy way to pass environment variables to the frontend,
+	// so for now pass via the backend. This is acceptable because the key is
+	// meant to be public
+	publishableKey := c.Config().BillingManager.GetPublishableKey()
 	if proj.BillingID != "" {
-		c.WriteResult(w, r, "")
+		c.WriteResult(w, r, publishableKey)
 		return
 	}
 
@@ -63,5 +67,5 @@ func (c *CreateBillingCustomerHandler) ServeHTTP(w http.ResponseWriter, r *http.
 		return
 	}
 
-	c.WriteResult(w, r, "")
+	c.WriteResult(w, r, publishableKey)
 }

+ 4 - 3
api/server/shared/config/env/envconfs.go

@@ -69,9 +69,10 @@ type ServerConf struct {
 	SendgridDeleteProjectTemplateID    string `env:"SENDGRID_DELETE_PROJECT_TEMPLATE_ID"`
 	SendgridSenderEmail                string `env:"SENDGRID_SENDER_EMAIL"`
 
-	StripeSecretKey   string `env:"STRIPE_SECRET_KEY"`
-	SlackClientID     string `env:"SLACK_CLIENT_ID"`
-	SlackClientSecret string `env:"SLACK_CLIENT_SECRET"`
+	StripeSecretKey      string `env:"STRIPE_SECRET_KEY"`
+	StripePublishableKey string `env:"STRIPE_PUBLISHABLE_KEY"`
+	SlackClientID        string `env:"SLACK_CLIENT_ID"`
+	SlackClientSecret    string `env:"SLACK_CLIENT_SECRET"`
 
 	BillingPrivateKey       string `env:"BILLING_PRIVATE_KEY"`
 	BillingPrivateServerURL string `env:"BILLING_PRIVATE_URL"`

+ 2 - 3
api/server/shared/config/loader/loader.go

@@ -58,13 +58,13 @@ func sharedInit() {
 	InstanceEnvConf, _ = envloader.FromEnv()
 
 	InstanceDB, err = adapter.New(InstanceEnvConf.DBConf)
-
 	if err != nil {
 		panic(err)
 	}
 
 	InstanceBillingManager = &billing.StripeBillingManager{
-		StripeSecretKey: InstanceEnvConf.ServerConf.StripeSecretKey,
+		StripeSecretKey:      InstanceEnvConf.ServerConf.StripeSecretKey,
+		StripePublishableKey: InstanceEnvConf.ServerConf.StripePublishableKey,
 	}
 }
 
@@ -123,7 +123,6 @@ func (e *EnvConfigLoader) LoadConfig() (res *config.Config, err error) {
 			Insecure:          envConf.ServerConf.CookieInsecure,
 		},
 	)
-
 	if err != nil {
 		return nil, err
 	}

+ 25 - 0
dashboard/src/lib/hooks/useStripe.tsx

@@ -27,6 +27,10 @@ type TCheckHasPaymentEnabled = {
   refetchPaymentEnabled: any;
 };
 
+type TGetPublishableKey = {
+  publishableKey: string;
+};
+
 export const usePaymentMethods = (): TUsePaymentMethod => {
   const { user, currentProject } = useContext(Context);
 
@@ -144,3 +148,24 @@ export const checkIfProjectHasPayment = (): TCheckHasPaymentEnabled => {
     refetchPaymentEnabled: paymentEnabledReq.refetch,
   };
 };
+
+export const usePublishableKey = (): TGetPublishableKey => {
+  const { user, currentProject } = useContext(Context);
+
+  // Fetch list of payment methods
+  const keyReq = useQuery(["getKey", currentProject?.id], async () => {
+    if (!currentProject?.id || currentProject.id === -1) {
+      return;
+    }
+    const res = await api.checkBillingCustomerExists(
+      "<token>",
+      { user_email: user?.email },
+      { project_id: currentProject?.id }
+    );
+    return res.data;
+  });
+
+  return {
+    publishableKey: keyReq.data,
+  };
+};

+ 4 - 2
dashboard/src/main/home/modals/BillingModal.tsx

@@ -8,14 +8,16 @@ import Link from "components/porter/Link";
 import Modal from "components/porter/Modal";
 import Spacer from "components/porter/Spacer";
 import Text from "components/porter/Text";
+import { usePublishableKey } from "lib/hooks/useStripe";
 
 import backArrow from "assets/back_arrow.png";
 
 import PaymentSetupForm from "./PaymentSetupForm";
 
-const stripePromise = loadStripe(process.env.STRIPE_PUBLISHABLE_KEY || "");
-
 const BillingModal = ({ back, onCreate }) => {
+  const { publishableKey } = usePublishableKey();
+  const stripePromise = loadStripe(publishableKey);
+
   const appearance = {
     variables: {
       colorPrimary: "#aaaabb",

+ 0 - 1
dashboard/src/main/home/modals/PaymentSetupForm.tsx

@@ -36,7 +36,6 @@ const PaymentSetupForm = ({ onCreate }: { onCreate: () => void }) => {
 
     // Create the setup intent in the server
     const clientSecret = await createPaymentMethod();
-    console.log(clientSecret);
 
     // Finally, confirm with Stripe so the payment method is saved
     const { error } = await stripe.confirmSetup({

+ 6 - 6
dashboard/src/main/home/project-settings/ProjectSettings.tsx

@@ -85,12 +85,12 @@ function ProjectSettings(props: any) {
         });
       }
 
-      if (currentProject?.billing_enabled) {
-        tabOpts.push({
-          value: "billing",
-          label: "Billing",
-        });
-      }
+      // if (currentProject?.billing_enabled) {
+      tabOpts.push({
+        value: "billing",
+        label: "Billing",
+      });
+      // }
 
       tabOpts.push({
         value: "additional-settings",

+ 8 - 0
internal/billing/billing.go

@@ -25,6 +25,9 @@ type BillingManager interface {
 
 	// DeletePaymentMethod will remove a payment method for the project in Stripe
 	DeletePaymentMethod(paymentMethodID string) (err error)
+
+	// GetPublishableKey returns the key used to render frontend components for the billing manager
+	GetPublishableKey() (key string)
 }
 
 // NoopBillingManager performs no billing operations
@@ -59,3 +62,8 @@ func (s *NoopBillingManager) CreatePaymentMethod(proj *models.Project) (clientSe
 func (s *NoopBillingManager) DeletePaymentMethod(paymentMethodID string) (err error) {
 	return nil
 }
+
+// GetPublishableKey is a no-op
+func (s *NoopBillingManager) GetPublishableKey() (key string) {
+	return ""
+}

+ 7 - 1
internal/billing/stripe.go

@@ -14,7 +14,8 @@ import (
 // StripeBillingManager interacts with the Stripe API to manage payment methods
 // and customers
 type StripeBillingManager struct {
-	StripeSecretKey string
+	StripeSecretKey      string
+	StripePublishableKey string
 }
 
 // CreateCustomer will create a customer in Stripe only if the project doesn't have a BillingID
@@ -125,3 +126,8 @@ func (s *StripeBillingManager) DeletePaymentMethod(paymentMethodID string) (err
 
 	return nil
 }
+
+// GetPublishableKey is a no-op
+func (s *StripeBillingManager) GetPublishableKey() (key string) {
+	return s.StripePublishableKey
+}

+ 0 - 3
zarf/helm/.dashboardenv

@@ -19,6 +19,3 @@ API_SERVER=http://localhost:8080
 # TRUST_ARN is used with the cloudformation pack, to allow supporting multiple AWS accounts as management accounts. Change MY_AWS_DEV_ACCOUNT_ID to your AWS developer account ID
 
 TRUST_ARN=arn:aws:iam::MY_AWS_DEV_ACCOUNT_ID:role/CAPIManagement
-
-# STRIPE_PUBLISHABLE_KEY is used to create Stripe Web Elements
-STRIPE_PUBLISHABLE_KEY=