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

如何用Cloud Functions创建带Header的HTTP请求,保护Flutter应用API密钥?

用Cloud Functions保护Stripe API密钥的实现方案

一、创建并配置Cloud Functions

1. 初始化Cloud Functions项目

确保本地已安装Firebase CLI,执行以下命令初始化项目:

firebase init functions

选择Node.js作为运行环境,进入生成的functions目录。

2. 安装Stripe依赖

在functions目录下执行:

npm install stripe

3. 配置Stripe密钥到环境变量

在Firebase控制台的Cloud Functions页面,添加环境变量STRIPE_SECRET_KEY,值为你的Stripe私钥;也可以通过本地命令配置:

firebase functions:config:set stripe.secret_key="你的Stripe私钥"

二、编写云函数代码

替换functions/index.js中的默认内容:

const functions = require("firebase-functions");
const stripe = require("stripe")(functions.config().stripe.secret_key);

exports.createStripeCustomer = functions.https.onCall(async (data, context) => {
  // 可选但推荐:验证用户身份,仅允许登录用户调用
  if (!context.auth) {
    throw new functions.https.HttpsError(
      "unauthenticated",
      "需要登录才能创建客户"
    );
  }

  const { userId, name } = data;
  try {
    const customer = await stripe.customers.create({
      name: name || "test",
      metadata: { userId: userId }
    });
    return customer;
  } catch (error) {
    throw new functions.https.HttpsError(
      "internal",
      "创建Stripe客户失败",
      error.message
    );
  }
});

使用onCall类型的触发器,能自动处理JSON序列化和身份验证,更适合Flutter客户端集成。

三、部署云函数

执行命令部署指定函数:

firebase deploy --only functions:createStripeCustomer

四、修改Flutter代码调用云函数

首先在pubspec.yaml中添加cloud_functions依赖:

dependencies:
  flutter:
    sdk: flutter
  cloud_functions: ^4.6.0

然后替换原有的createCustomer方法:

import 'package:cloud_functions/cloud_functions.dart';
import 'dart:developer' as log;

Future<Customer?> createCustomer(String userId) async {
  try {
    final HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(
      'createStripeCustomer',
    );
    final response = await callable.call({
      'userId': userId,
      'name': 'test',
    });

    final customer = Customer.fromMap(response.data);
    currentCustomer = customer;
    return customer;
  } catch (e) {
    log.error(e.toString());
    return null;
  }
}

关键说明

  • 安全防护:通过context.auth验证用户身份,避免未授权的恶意调用。
  • 密钥隔离:Stripe私钥仅存储在Cloud Functions环境变量中,完全不暴露给客户端代码。
  • 错误统一:云函数返回标准化错误,Flutter端可统一捕获处理异常场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:37:13