You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何确认Stripe支付扣款成功?附相关实现代码咨询

Stripe Charge Function Validation & Fixes

Hey there, let's break down your code and fix the gaps to ensure your Stripe charge works reliably with Firebase Cloud Functions.

Key Issues in Your Current Code

  • Invalid Database Update Path: Your updates object has a typo—/Orders/' + orderid + "status" will resolve to something like Orders/abc123status (missing a slash before status). This means the status won't be saved to the correct location in your Realtime Database.
  • Incomplete Stripe Charge Params: The stripe.charges.create call is missing the required source parameter (your token variable) and lacks error handling for failed charges.
  • Unused Variable: orderstatus is defined but never used—you can remove it to clean up the code.
  • Missing Promise Handling: Cloud Functions require you to return a Promise to ensure the runtime waits for async operations (like the Stripe charge and database update) to complete.

Corrected & Robust Implementation

exports.chargecustomer = functions.database.ref('/Orders/{pushId}').onCreate(async (event) => { 
  const original = event.data.val(); 
  const orderid = event.params.pushId; 
  const token = original.paytoken;
  // Ensure you've initialized Stripe with your secret key elsewhere:
  // const stripe = require('stripe')('your-stripe-secret-key');

  try {
    // Execute the Stripe charge
    const charge = await stripe.charges.create({
      amount: 999, // Amount in cents (e.g., $9.99)
      currency: "usd",
      source: token, // Required: the payment token from your frontend
      description: `Order #${orderid} - Customer Charge` // Useful for Stripe dashboard tracking
    });

    // Update order status to 'charged' on success
    const updates = {};
    updates[`/Orders/${orderid}/status`] = "charged";
    updates[`/Orders/${orderid}/stripeChargeId`] = charge.id; // Optional: save charge ID for future reference
    return event.data.ref.parent.update(updates);
  } catch (error) {
    // Handle failed charges (e.g., insufficient funds, invalid card)
    console.error(`Charge failed for order ${orderid}:`, error.message);
    const updates = {};
    updates[`/Orders/${orderid}/status`] = "failed";
    updates[`/Orders/${orderid}/errorMessage`] = error.message; // Optional: save error details for debugging
    return event.data.ref.parent.update(updates);
  }
});

Additional Best Practices

  • Async/Await: I used async/await for cleaner, more readable async code (you can also use .then()/.catch() if you prefer, but async/await reduces callback clutter).
  • Error Resilience: The try/catch block ensures that if the Stripe charge fails for any reason, your order gets updated with a failed status instead of silently failing.
  • Secure Stripe Setup: Never expose your Stripe secret key in frontend code—initialize the SDK only in your Cloud Function or backend server.
  • Amount Accuracy: Stripe expects amounts in the smallest currency unit (e.g., cents for USD), so double-check that 999 matches your order's actual intended amount.

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

火山引擎 最新活动