You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Appmaker中实现Stripe支付?请求支付收费代码模板解析

Stripe Checkout Payment Charge Flow for AppMaker Enterprise Store (Stripe-Go Implementation)

Hey Dennis, I’ve worked through similar Stripe + AppMaker integrations before, so let’s walk through exactly how to implement the payment charge completion step (Stripe-Go Checkout Guide Step 2) with code templates and explanations tailored to your use case.

First, Quick Recap of the Flow

Stripe Checkout’s end-to-end flow for your store will look like this:

  1. Your AppMaker frontend triggers a server-side function to create a Stripe Checkout Session.
  2. The user completes payment on Stripe’s hosted page.
  3. Stripe sends a checkout.session.completed webhook to your server to confirm success—this is the "charge completion" step you’re stuck on.
  4. Your server updates the order status in AppMaker and finalizes the transaction.

Step 1: Install & Configure Stripe-Go

First, make sure you’ve got the Stripe-Go SDK set up in your server-side environment (AppMaker allows you to run Go code in server scripts, right?):

go get github.com/stripe/stripe-go/v78

Then, set your Stripe Secret Key as an environment variable (never hardcode it!):

import (
  "os"
  stripe "github.com/stripe/stripe-go/v78"
)

// Initialize Stripe client once at startup
var stripeClient = stripe.NewClient(os.Getenv("STRIPE_SECRET_KEY"))

Step 2: Create the Checkout Session (Frontend Trigger)

This is the function you’ll bind to your "Pay Now" button click in AppMaker. It generates a Stripe Checkout URL and redirects the user:

// CreateCheckoutSession creates a Stripe Checkout Session for a store order
func CreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
  // 1. Fetch order details from AppMaker's database (adjust this to your AppMaker data model)
  orderID := r.FormValue("order_id")
  orderTotal := 999 // Example: $9.99 (Stripe uses cents as the smallest unit)
  customerEmail := "customer@example.com" // Pull from your AppMaker user data

  // 2. Configure Checkout Session parameters
  params := &stripe.CheckoutSessionParams{
    PaymentMethodTypes: stripe.StringSlice([]string{"card"}),
    LineItems: []*stripe.CheckoutSessionLineItemParams{
      {
        PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
          Currency: stripe.String("usd"),
          ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
            Name: stripe.String("AppMaker Enterprise Store Order #" + orderID),
          },
          UnitAmount: stripe.Int64(int64(orderTotal)),
        },
        Quantity: stripe.Int64(1),
      },
    },
    Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
    SuccessURL: stripe.String("https://your-appmaker-store.com/success?order_id=" + orderID),
    CancelURL: stripe.String("https://your-appmaker-store.com/cancel?order_id=" + orderID),
    CustomerEmail: stripe.String(customerEmail),
    // Add metadata to link Stripe session to your AppMaker order (critical for Step 3)
    Metadata: map[string]string{"order_id": orderID},
  }

  // 3. Create the session via Stripe-Go
  session, err := stripeClient.CheckoutSessions.New(params)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  // 4. Redirect user to Stripe's Checkout page (return URL to AppMaker frontend)
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(map[string]string{"url": session.URL})
}

How to bind this in AppMaker:

  • Create a server-side script in AppMaker that runs this function.
  • On your payment button’s click event, call this script, then use the returned url to redirect the user to Stripe’s checkout page.

Step 3: Handle the checkout.session.completed Webhook (Charge Completion)

This is the critical step you’re asking about—confirming the payment was successful and finalizing the order in AppMaker. Stripe sends this webhook when the user completes payment:

// StripeWebhookHandler processes Stripe webhook events
func StripeWebhookHandler(w http.ResponseWriter, r *http.Request) {
  // 1. Validate the webhook signature (critical for security!)
  const webhookSecret = "your_stripe_webhook_secret" // Get this from Stripe Dashboard
  payload, err := io.ReadAll(r.Body)
  if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
  }

  event, err := stripeClient.Webhooks.ConstructEvent(
    payload,
    r.Header.Get("Stripe-Signature"),
    webhookSecret,
  )
  if err != nil {
    http.Error(w, err.Error(), http.StatusUnauthorized)
    return
  }

  // 2. Handle the checkout.session.completed event
  if event.Type == "checkout.session.completed" {
    var session stripe.CheckoutSession
    err := json.Unmarshal(event.Data.Raw, &session)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
      return
    }

    // 3. Extract your AppMaker order ID from the session metadata
    orderID := session.Metadata["order_id"]
    if orderID == "" {
      http.Error(w, "Missing order ID in session metadata", http.StatusBadRequest)
      return
    }

    // 4. Verify the payment was successful
    if session.PaymentStatus == string(stripe.CheckoutSessionPaymentStatusPaid) {
      // 5. Update your AppMaker order status to "Paid" (adjust this to your AppMaker data API)
      err := updateAppMakerOrderStatus(orderID, "Paid")
      if err != nil {
        // Handle error (e.g., retry logic, log to AppMaker's error system)
        log.Printf("Failed to update order %s: %v", orderID, err)
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
      }

      // 6. Optional: Send confirmation email to customer via AppMaker's email service
      sendAppMakerOrderConfirmation(orderID, session.CustomerEmail)
    }
  }

  // 7. Return success to Stripe
  w.WriteHeader(http.StatusOK)
}

// Helper function to update AppMaker order status (replace with your actual AppMaker data logic)
func updateAppMakerOrderStatus(orderID string, status string) error {
  // Example: Use AppMaker's server-side API to update the order record
  // appmakerDB := appmaker.NewClient(os.Getenv("APPMAKER_API_KEY"))
  // return appmakerDB.Orders.Update(orderID, map[string]interface{}{"status": status})
  return nil
}

Key Notes for AppMaker Integration:

  • Webhook Endpoint: In AppMaker, create a public server endpoint that maps to this StripeWebhookHandler function. Then, add this endpoint URL to your Stripe Dashboard’s Webhooks settings (under Developers > Webhooks).
  • Metadata: We added the order ID to the Checkout Session metadata in Step 2—this is the safest way to link Stripe’s payment data to your AppMaker orders.
  • Security: Always validate the Stripe webhook signature—this prevents fake requests from pretending to be Stripe.

Troubleshooting Common Issues

  • Webhook Not Triggering: Make sure your AppMaker endpoint is public (not behind a firewall) and that you’ve added the correct webhook secret in both Stripe Dashboard and your code.
  • Payment Status Not Updating: Double-check that the session.PaymentStatus is indeed paid before updating the order. Stripe might send other events like checkout.session.async_payment_succeeded for delayed payments, so you may want to handle those too.
  • AppMaker Data Access: Ensure your server-side script has permission to update order records in AppMaker’s database.

内容的提问来源于stack exchange,提问作者Dennis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:17:03