在 React Native 流程中接受 Stripe 支付

您可以在 Flow & Paywall Builder 中创建流程,并通过该流程销售 Stripe 订阅。流程展示您的 Stripe 价格,其按钮会在流程上方弹出 Stripe 的 PaymentSheet。支付完成后,Stripe 会通知 Adapty。Adapty 随即向用户授予访问等级,并将收入归因到对应的流程、版位及 A/B 测试实验变体。这套方案适用于销售用户在应用外消费的订阅服务,例如线下活动会员资格、课程通票或定期配送服务。如果您已将某项真实世界服务的方案作为 App Store 产品出售,也可以将 Stripe 加入同一个流程,作为另一种付款方式。

Important

App Store 要求数字内容和功能必须使用应用内购买(指南 3.1.1),Google Play 也要求对此类内容使用其自有结算系统(付款政策)。通过 Stripe 进行的应用内支付适用于实体商品,以及用户在应用外消费的服务(指南 3.1.3(e))。对于此类购买(如健身房会员资格和线下活动门票),Google Play 不允许使用其结算系统。

工作原理

  1. 您的应用从后端获取 Stripe 价格,通过自定义标签将其传递给流程,然后展示该流程。
  2. 用户点击流程中的按钮,该按钮触发自定义操作,您的应用接收到操作 ID。
  3. 您的应用请求后端创建 Stripe 订阅,后端将用户 ID 和流程的实验变体 ID 添加到订阅的元数据中。
  4. 您的应用在流程上方打开 PaymentSheet,用户支付订阅的首张账单。
  5. Stripe 向 Adapty 发送 webhook,Adapty 将访问等级授予该用户 ID 对应的用户画像,并将此次购买归因到对应的流程实验变体。
  6. 您的应用关闭流程,等待用户画像获得相应访问等级。

开始之前

确保您已完成以下准备工作:

  1. Stripe 已连接到您的 Adapty 应用:分别为测试模式和正式模式按照将 Stripe 连接到 Adapty 的步骤操作。将 Profile creation behavior 保持设置为 Use customer_user_id from metadata (default)。

  2. 每个套餐对应一个 Stripe 产品和价格:在 Stripe 上创建产品,并设置定期收费价格,例如按月或按年。

  3. 每个 Stripe 价格对应一个 Adapty 产品:将 Stripe 产品 ID 和价格 ID 添加到 Adapty 产品中,并分配该套餐解锁的访问等级。访问等级代表服务的使用权(例如有效会员资格),而非应用内的数字功能。若没有配置 Adapty 产品,Adapty 将不会记录该购买行为。

  4. Adapty React Native SDK 4.0.0 或更高版本:使用已连接到 Stripe 的 Adapty 应用密钥激活 SDK。Adapty 仅接收该应用对应的 Stripe Webhook。通过 customer user ID 识别用户,并仅向已登录且已完成身份识别的用户显示此流程。Adapty 使用此 ID 来找到获得访问等级的用户画像。

    从 SDK 4.4 开始,流程需要 iOS 16 或更高版本。在 iOS 15 上,createFlowView 和 AdaptyFlowView 会报告带有 platformNotSupported 代码的错误。当应用收到此错误时,请显示自己的内容,而不是流程,例如自定义付费墙。

  5. Stripe React Native SDK(@stripe/stripe-react-native)已集成到你的应用中。请参阅 Stripe 文档中的接受付款。

  6. 能够调用 Stripe API 的后端,使用你的 Stripe 密钥,或者使用你自己创建的、拥有 Customers 和 Subscriptions 写权限的受限密钥。不要复用你为 Adapty 生成的受限密钥:那是 Adapty 的密钥,不具备你的后端所需的写权限。请将密钥保存在服务器上。

在流程中显示 Stripe 价格

流程通过自定义标签显示 Stripe 价格。自定义标签是应用在加载流程时传递给流程的文本值。Adapty 不会对自定义标签的值进行任何格式化处理,因此请按照用户看到的形式传递每个价格,例如”$29.00”。

  1. 在 Flow & Paywall Builder 中,为每个价格创建一个 String 变量,例如 stripe_monthly_price 和 stripe_annual_price,并选择 Value comes from outside the app。将每个变量的 Initial value 设置为当前价格。如果应用无法加载价格,用户将看到初始值,因此请确保初始值与您的 Stripe 价格保持一致。
  2. 将每个标签插入到文本元素中,例如套餐按钮的标签。
  3. 在应用中,在加载流程之前先从后端获取价格。
  4. 在视图参数的 customTags 字段中传入价格。

以下函数用于加载流程并使用您的 Stripe 价格构建其视图参数。它同时返回流程对象,因为您的后端会将流程的 variationId 写入 Stripe 订阅。您可以在从流程打开 PaymentSheet 中展示该流程。


export type StripeFlow = {
  flow: AdaptyFlow;
  params: CreateFlowViewParamsInput;
};

export async function loadStripeFlow(): Promise<StripeFlow> {
  // If the prices fail to load, the flow shows the tags' initial values
  const prices = await Backend.fetchPrices().catch((): Record<string, string> => ({}));

  const flow = await adapty.getFlow('YOUR_PLACEMENT_ID');
  const customTags: Record<string, string> = {};
  if (prices.monthly) customTags.stripe_monthly_price = prices.monthly;
  if (prices.annual) customTags.stripe_annual_price = prices.annual;

  return { flow, params: { customTags } };
}

Backend 是您后端接口的客户端,来自在您的后端创建订阅。

添加打开 PaymentSheet 的按钮

每个销售 Stripe 方案的按钮都会触发一个自定义动作。你的应用接收到动作 ID 后,会为该方案打开 PaymentSheet。

  1. 在 Flow & Paywall Builder 中,为每个 Stripe 方案添加一个按钮。
  2. 为每个按钮分配 Custom Action 动作,并输入动作 ID,例如 buy_stripe_monthly 和 buy_stripe_annual。
  3. 发布流程,并将其添加到版位。

您的应用将每个操作 ID 映射到对应的方案。流程不会随操作发送任何数据,因此操作 ID 必须能够标识对应的方案。

将 Stripe 添加为 App Store 产品的另一种支付方式

此设置仅适用于用户在应用外消费的实体商品或服务计划(指南 3.1.3(e)),例如线下活动会员资格。对于数字内容或功能,请通过 Web 付费墙 提供其他支付方式。

此设置仅适用于 iOS。Google Play 不允许其结算系统用于实体商品和服务(付款政策),因此在 Android 上,请仅通过 Stripe 销售这些方案。

该流程会像往常一样展示你的 App Store 产品,而”以其他方式付款”等链接则会打开 PaymentSheet。App Store 的购买按钮无需任何改动即可继续正常使用。

  1. 将 Custom Action 操作分配给链接,并设置一个操作 ID,例如 pay_with_stripe。
  2. 为流程中的每个 App Store 产品,在 Stripe 中创建对应方案的价格。
  3. 在应用中,将每个 App Store 产品 ID 映射到其对应的 Stripe 方案。
  4. 保存用户选择的产品。流程会将每次选择上报给 onProductSelected 处理器。在付费墙编辑工具中构建的流程默认不会上报用户选择的产品,因此请以在编辑工具中设置为已选中的产品作为初始值。如果 A/B 测试的各实验变体选择了不同的产品,则分别保存每个变体的默认产品。
  5. 当应用收到 pay_with_stripe 时,使用已保存产品对应的 Stripe 方案,调用从流程打开 PaymentSheet 中 StripeCheckout 的 pay 方法。

流程中显示的是这些产品在 App Store 中的价格,该价格因销售地区而异。PaymentSheet 收取的则是 Stripe 价格。若要在用户点击前显示 Stripe 价格,请将其作为自定义标签传入,并在每个方案卡片中显示,例如”或 $29.00/月(银行卡支付)“。自定义标签的值在流程打开后不会改变,因此单个链接无法显示所选方案的价格。

在您的后端创建订阅

PaymentSheet 用于支付您后端创建的 Stripe 对象。在本指南中,您的后端会创建一个 Stripe 订阅,PaymentSheet 负责支付该订阅的首张发票。您的后端需要在订阅的元数据中设置两个键:

  • customer_user_id:用户在 Adapty 中的 customer user ID。Adapty 将访问等级授予具有此 ID 的用户画像。
  • variation_id:流程的实验变体 ID,由你的应用发送到后端。Adapty 将收入归因于该流程实验变体、其版位及其 A/B 测试。
Warning

如果你单独创建 PaymentIntent(不关联订阅或发票),Adapty 不会记录该笔付款。用户完成支付,但不会获得访问等级。

创建两个接口。第一个接口返回自定义标签的格式化价格。第二个接口创建订阅并返回 PaymentSheet 所需的值。在创建订阅之前,第二个接口会验证用户是否已有有效订阅,防止同一套餐被重复付款。

本示例使用 Node.js ES 模块(package.json 中设置 "type": "module")、Express 以及 18 或更高版本的 stripe 库。请将 db 替换为你自己的数据库:


const app = express();
app.use(express.json());

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const prices = {
  monthly: 'price_...', // your Stripe price IDs
  annual: 'price_...',
};

// Prices for the custom tags, such as { "monthly": "$29.00", "annual": "$249.00" }.
// You can cache the response.
app.get('/prices', async (req, res) => {
  try {
    const result = {};
    for (const [plan, priceId] of Object.entries(prices)) {
      const price = await stripe.prices.retrieve(priceId);
      // Assumes a currency with two decimal places. Format for your users' locale.
      result[plan] = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: price.currency.toUpperCase(),
      }).format(price.unit_amount / 100);
    }
    res.json(result);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not load prices' });
  }
});

app.post('/subscriptions', async (req, res) => {
  // req.user comes from your authentication middleware. Its ID is the same
  // customer user ID that your app passes to adapty.identify().
  const customerUserId = req.user.id;
  // variationId affects only attribution, so the backend doesn't need to trust it
  const { plan, variationId } = req.body;
  if (!prices[plan]) {
    return res.status(400).json({ error: 'Unknown plan' });
  }

  try {
    // One Stripe customer per user, stored in your database
    let customerId = await db.getStripeCustomerId(customerUserId);
    if (!customerId) {
      const customer = await stripe.customers.create({ metadata: { customer_user_id: customerUserId } });
      customerId = customer.id;
      await db.saveStripeCustomerId(customerUserId, customerId);
    }

    // Don't sell a second subscription to a user who already has one
    for (const status of ['active', 'trialing', 'past_due']) {
      const existing = await stripe.subscriptions.list({ customer: customerId, status, limit: 1 });
      if (existing.data.length > 0) {
        return res.status(409).json({ error: 'You already have a subscription' });
      }
    }

    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: prices[plan] }],
      payment_behavior: 'default_incomplete',
      payment_settings: { save_default_payment_method: 'on_subscription' },
      metadata: {
        customer_user_id: customerUserId,
        variation_id: variationId,
      },
      expand: ['latest_invoice.confirmation_secret'],
    });

    res.json({
      subscriptionId: subscription.id,
      clientSecret: subscription.latest_invoice.confirmation_secret.client_secret,
      publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not create the subscription' });
  }
});

app.listen(process.env.PORT ?? 3000);

使用 payment_behavior: 'default_incomplete' 时,订阅会等待首次付款。用户在 PaymentSheet 中完成支付后,Stripe 才会激活订阅。如果用户关闭 PaymentSheet 而未付款,Stripe 将在约 23 小时后使该订阅失效,Adapty 也不会记录该订阅。有关完整的 Stripe 配置说明,请参阅 Stripe 文档中的 Build a subscriptions integration。

代码从 latest_invoice.confirmation_secret 读取客户端密钥,这需要 Stripe API 版本 2025-03-31.basil 或更高版本。stripe 库从版本 18 开始使用此版本。如果直接调用 Stripe API 而不使用该库,请设置 Stripe-Version 请求头。在更早的 API 版本中,请展开 latest_invoice.payment_intent 并改为读取 payment_intent.client_secret。

在你的应用中,调用这两个接口。根据后端要求,每次请求时都需要携带用户的身份验证信息:

const BASE_URL = 'https://YOUR_BACKEND';

export type Subscription = {
  subscriptionId: string;
  clientSecret: string;
  publishableKey: string;
};

async function send<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(`${BASE_URL}/${path}`, init);
  if (response.status !== 200) {
    // Use the backend's message when the response has one
    const body = await response.json().catch(() => null);
    throw new Error(body?.error ?? `The server returned HTTP ${response.status}.`);
  }
  return response.json();
}

export const Backend = {
  fetchPrices: () => send<Record<string, string>>('prices'),

  createSubscription: (plan: string, variationId: string) =>
    send<Subscription>('subscriptions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // add your authentication header
      },
      body: JSON.stringify({ plan, variationId }),
    }),
};

在流程中打开 PaymentSheet

当流程中的按钮触发自定义操作时,应用会打开 PaymentSheet,并在支付成功后关闭流程:

  1. 将自定义操作 ID 映射到套餐。在应用等待后端响应或显示 PaymentSheet 期间,忽略点击、链接以及流程的关闭按钮。这样一次点击只会创建一个订阅。
  2. 向后端请求订阅,并传入套餐和流程的 variationId。
  3. 在流程上方展示 PaymentSheet,并处理其结果:
    • Completed:关闭流程。关闭后,等待访问等级生效。
    • Canceled:不做任何操作。用户留在流程中,可以选择其他套餐。
    • Failed:显示错误信息。用户留在流程中,可以重试。
  4. 处理流程的关闭按钮、链接和错误。您设置的处理程序会替换 SDK 对该事件的默认处理程序。默认处理程序会打开链接,在模态展示模式下还会在点击关闭按钮或发生错误时关闭流程。
  5. 不要在自定义操作处理程序中等待支付完成,并从中返回 false。在模态展示模式下,返回 true 的处理程序会关闭流程,async 处理程序也会关闭流程,因为它返回的是一个 Promise。

步骤 2 和 3 对于 React 组件和模态展示方式来说是相同的,因此本指南将它们合并在同一章节中:

  initPaymentSheet,
  initStripe,
  PaymentSheetError,
  presentPaymentSheet,
} from '@stripe/stripe-react-native';

/** What the checkout needs from the screen that shows the flow */
export type CheckoutHost = {
  isFlowOpen: () => boolean;
  showError: (message: string) => void;
};

export class StripeCheckout {
  // Custom action IDs from the flow, mapped to your backend's plan keys
  static readonly plans: Record<string, string> = {
    buy_stripe_monthly: 'monthly',
    buy_stripe_annual: 'annual',
  };

  private paying = false;

  get isPaying(): boolean {
    return this.paying;
  }

  /** Opens PaymentSheet for a plan over the flow. Resolves to `true` when the user paid. */
  async pay(plan: string, variationId: string, host: CheckoutHost): Promise<boolean> {
    if (this.paying) return false;
    this.paying = true;

    try {
      const subscription = await Backend.createSubscription(plan, variationId);
      // The flow may have closed while the backend responded
      if (!host.isFlowOpen()) return false;

      await initStripe({ publishableKey: subscription.publishableKey });
      const { error: initError } = await initPaymentSheet({
        paymentIntentClientSecret: subscription.clientSecret,
        merchantDisplayName: 'YOUR_BUSINESS_NAME',
        // iOS: for payment methods that redirect to another app, such as bank apps
        returnURL: 'your-app://stripe-redirect',
      });
      if (initError) {
        host.showError(initError.message);
        return false;
      }

      const { error } = await presentPaymentSheet();
      if (!error) {
        return true;
      }
      if (error.code !== PaymentSheetError.Canceled) {
        host.showError(error.message);
      }
      return false; // the user stays on the flow
    } catch (error) {
      host.showError(error instanceof Error ? error.message : String(error));
      return false;
    } finally {
      this.paying = false;
    }
  }
}

在 iOS 上,PaymentSheet 在支付方式跳转到其他应用后,会通过返回 URL 跳回你的应用。请在应用中注册 URL scheme,具体步骤参见 Stripe 文档中的 Set up a return URL,并在应用打开该 URL 时将其传递给 Stripe。Android 无需设置返回 URL。


// Call this hook in your root component
export function useStripeReturnURL() {
  useEffect(() => {
    const forward = (url: string | null) => {
      if (url) void handleURLCallback(url);
    };
    void Linking.getInitialURL().then(forward);
    const subscription = Linking.addEventListener('url', ({ url }) => forward(url));
    return () => subscription.remove();
  }, []);
}

然后展示流程,并将其操作传递给 StripeCheckout:

使用 AdaptyFlowView 组件渲染流程,并将其处理器作为 props 传入。该组件会忽略处理器的返回值,因此要关闭流程,只需停止渲染该组件即可:


export function MembershipScreen() {
  const [stripeFlow, setStripeFlow] = useState<StripeFlow | null>(null);
  const [checkout] = useState(() => new StripeCheckout());
  const isLoadingFlow = useRef(false);
  const isFlowOpen = useRef(false);

  // The screen can close while the backend responds, for example on Android back navigation
  useEffect(() => () => {
    isFlowOpen.current = false;
  }, []);

  const host: CheckoutHost = {
    isFlowOpen: () => isFlowOpen.current,
    showError: (message) => Alert.alert("The payment didn't go through", message),
  };

  function closeFlow() {
    isFlowOpen.current = false;
    setStripeFlow(null);
  }

  async function showStripeFlow() {
    if (isLoadingFlow.current) return;
    isLoadingFlow.current = true;

    try {
      const loadedFlow = await loadStripeFlow();
      isFlowOpen.current = true;
      setStripeFlow(loadedFlow);
    } catch (error) {
      // handle the error
    } finally {
      isLoadingFlow.current = false;
    }
  }

  async function payAndClose(plan: string, variationId: string) {
    if (!(await checkout.pay(plan, variationId, host))) return;
    closeFlow();
    await unlockAfterPayment();
  }

  if (!stripeFlow) {
    return <Button title="Become a member" onPress={() => void showStripeFlow()} />;
  }

  return (
    <AdaptyFlowView
      flow={stripeFlow.flow}
      params={stripeFlow.params}
      style={{ flex: 1 }}
      onCloseButtonPress={() => {
        if (!checkout.isPaying) closeFlow();
      }}
      onUrlPress={(url, openIn) => {
        if (checkout.isPaying) return;
        adapty.openWebUrl(url, openIn).catch(() => {
          // handle the error
        });
      }}
      onError={() => {
        // Keep the flow, and PaymentSheet over it, while the user pays.
        // Otherwise stop rendering the flow, and show your own content.
        if (!checkout.isPaying) closeFlow();
      }}
      onCustomAction={(actionId) => {
        const plan = StripeCheckout.plans[actionId];
        if (!plan) return;
        payAndClose(plan, stripeFlow.flow.variationId).catch(() => {
          // handle the error
        });
      }}
    />
  );
}

async function unlockAfterPayment() {
  if (await waitForAccess()) {
    // unlock the service
  } else {
    // tell the user that the payment is processing, and how to reach your support
  }
}

如果你的流程还需要销售 App Store 产品,请按照处理流程事件中的说明,在购买处理器中处理相关购买操作。

付款后解锁访问权限

付款完成后,Adapty 会接收 Stripe 的 webhook 并在几秒内授予相应的访问等级。SDK 每分钟刷新一次用户画像,因此请持续请求用户画像,直到访问等级生效:


export async function waitForAccess(): Promise<boolean> {
  for (let attempt = 1; attempt <= 20; attempt++) {
    try {
      const profile = await adapty.getProfile();
      if (profile.accessLevels?.['YOUR_ACCESS_LEVEL']?.isActive) {
        return true;
      }
    } catch {
      // try again
    }
    await new Promise<void>((resolve) => setTimeout(resolve, 3000));
  }
  return false;
}

通常情况下,访问等级会在几秒钟内激活。如果 60 秒后仍未激活,请在 Stripe 的 Webhook 设置中核查 Adapty Webhook 端点的投递情况。

如需在支付完成后显示确认页面(例如欢迎界面),可在访问等级激活后从应用中展示。你也可以将该界面构建为第二个流程,添加到其专属版位,并在第一个流程关闭后呈现。响应购买结果介绍了如何为此设置第二个流程。

让用户管理订阅

Stripe 订阅不会出现在用户 iOS 设置中的 App Store 订阅列表,也不会出现在 Google Play 订阅列表中。若要让用户取消订阅或更改支付方式,请在应用中添加一个按钮(例如在账户页面),引导用户打开 Stripe 客户门户。由你的后端为该用户的 Stripe 客户创建一个门户会话,并返回对应的 URL。

当用户取消订阅时,Stripe 会通知 Adapty,Adapty 随即更新访问等级。有关 Adapty 如何处理立即取消和到期取消的详细信息,请参阅取消。

测试集成

使用 Stripe 的测试模式,连接到你的 Adapty 应用:

  1. 在 iOS 和 Android 上运行你的应用,使用你连接到 Stripe 的 Adapty 应用的 SDK 密钥。
  2. 打开流程。按钮上应显示你的应用传入的价格,而不是自定义标签的初始值。
  3. 点击某个 Stripe 方案按钮。在 PaymentSheet 中,使用 Stripe 测试卡 4242 4242 4242 4242、任意未来的到期日期以及任意 CVC 完成支付。
  4. 验证流程是否关闭,以及用户画像的访问等级是否在几秒内变为激活状态。
  5. 在 Adapty 看板中,打开 Event Feed。购买事件应包含 store: stripe、你的流程的 flow_id 和 flow_name、等于你的应用发送的 variationId 的 flow_variation_id,以及 developer_id 中的版位 ID。对于 Stripe 购买,variation_id 与 flow_variation_id 的值相同。

测试模式下的购买记录带有 Sandbox 环境标识。它们会出现在 Event Feed 和用户画像中,但不会计入数据分析或流程的数据图表,因为这些部分只统计生产环境的购买记录。

如果购买记录未在 Adapty 中出现,请确认以下几点:你的应用使用的是已连接 Stripe 的 Adapty 应用的 SDK 密钥、Adapty 中存在对应 Stripe 价格的产品,以及订阅的 metadata 中包含 customer_user_id。另请参阅 Stripe 集成指南中的故障排查部分。

限制

  • 流程无法接收 Stripe 结果:流程无法在 Stripe 支付成功、取消或失败后跳转到其他页面。您的应用需关闭流程并自行决定后续展示的内容。
  • 自定义标签中的价格为纯文本:流程会按应用传入的值原样显示自定义标签,不会基于此计算其他数值(例如每周价格或折扣)。如需展示多个值,请分别传入各自的标签。
  • 自定义标签的值在流程打开期间保持不变:如需显示新价格,请重新加载流程。