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

如何通过Cloud Functions向Stripe传递信息并修复数据库查询问题

修复Firebase Cloud Functions查询数据库并创建Stripe结账会话的问题

原代码的核心问题

  • uid变量未定义:没有正确获取用户UID,导致数据库路径错误
  • 数据库快照取值逻辑错误:未从查询结果中提取numberInput和serviceType,直接写的变量赋值语法无效
  • Stripe模块重复加载:每次函数调用都重新require模块,影响性能
  • 字符串转数字缺失:numberInput是数据库中存储的字符串,直接相乘可能出现意外行为

修正后的代码

const functions = require("firebase-functions");
const admin = require("firebase-admin");
// 将Stripe模块移到函数外部,避免重复加载
const stripe = require("stripe")(functions.config().stripe.secret_key);

admin.initializeApp();

exports.createStripeCheckout = functions.https.onCall(async (data, context) => {
  // 验证用户是否已认证并获取UID
  if (!context.auth) {
    throw new functions.https.HttpsError(
      "unauthenticated",
      "用户未登录,无法创建结账会话"
    );
  }
  const uid = context.auth.uid;

  try {
    // 正确查询数据库并提取数据
    const snapshot = await admin
      .database()
      .ref(`studiopick/studio/users/${uid}/prices/roomA/serviceOne`)
      .once("value");
    
    const serviceData = snapshot.val();
    if (!serviceData) {
      throw new functions.https.HttpsError(
        "not-found",
        "未找到该用户的服务定价数据"
      );
    }

    // 解构变量并转换数据类型
    const { numberInput, serviceType } = serviceData;
    const unitAmount = parseInt(numberInput, 10) * 100;
    if (isNaN(unitAmount)) {
      throw new functions.https.HttpsError(
        "invalid-argument",
        "服务价格格式错误"
      );
    }

    // 创建Stripe结账会话
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      mode: "payment",
      success_url: "http://localhost:5500/success",
      cancel_url: "http://localhost:5500/cancel",
      shipping_address_collection: {
        allowed_countries: ["US"],
      },
      line_items: [
        {
          quantity: 1,
          price_data: {
            currency: "usd",
            unit_amount: unitAmount,
            product_data: {
              name: serviceType || "默认服务",
            },
          },
        },
      ],
    });

    return { id: session.id };
  } catch (error) {
    // 错误处理,返回标准化的HTTPS错误
    if (error instanceof functions.https.HttpsError) {
      throw error;
    }
    throw new functions.https.HttpsError(
      "internal",
      "创建结账会话时发生错误",
      error.message
    );
  }
});

关键修改说明

  1. UID获取:通过context.auth.uid获取已认证用户的UID,同时增加未认证的错误抛出,确保接口安全性。
  2. 数据库查询优化:使用模板字符串拼接路径更清晰,调用snapshot.val()获取节点数据,增加数据存在性校验,避免空值导致后续错误。
  3. 数据类型处理:将numberInput字符串转为整数,再乘以100转换为Stripe要求的最小货币单位(分),同时增加格式校验。
  4. 模块加载优化:将Stripe模块移到函数外部,只在部署时加载一次,提升函数执行效率。
  5. 错误处理:添加完整的try-catch块,抛出标准化的HttpsError,方便客户端捕获和处理不同类型的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:46:08