在 iOS 流程中接受 Stripe 支付

您可以通过在流程与付费墙编辑工具中构建的流程来销售 Stripe 订阅。该流程会展示您的 Stripe 价格,其按钮会在流程上方弹出 Stripe 的 PaymentSheet。支付完成后,Stripe 会通知 Adapty。Adapty 随即向用户授予访问等级,并将收入归因于该流程、其版位及其 A/B 测试实验变体。这种设置适合销售用户在应用之外使用的服务订阅,例如线下活动会员资格、课程通票或定期配送服务。如果您同时将某项真实服务的方案作为 App Store 产品出售,也可以将 Stripe 添加到同一流程中,作为另一种支付方式。

Important

App Store 要求数字内容和功能必须使用应用内购买(指南 3.1.1)。通过 Stripe 进行的应用内支付适用于实体商品以及用户在应用外消费的服务(指南 3.1.3(e))。如需将用户引导至网页结账页面购买数字内容,请使用网页付费墙。

工作原理

  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 iOS SDK 4.0.0 或更高版本:使用已连接到 Stripe 的 Adapty 应用密钥激活 SDK。Adapty 仅接收该应用的 Stripe Webhook。请通过 customer user ID 识别用户,并仅向已登录且已识别的用户展示此流程。Adapty 使用该 ID 查找并授予相应用户画像的访问等级。
  5. Stripe iOS SDK,需在应用中包含 StripePaymentSheet 模块。请参阅 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. 在应用中,在加载 flow 之前从后端获取价格。
  4. 在 getFlowConfiguration 的 tagResolver 参数中传入价格。

以下函数加载带有 Stripe 价格的流程,同时返回流程的 variationId,因为您的后端会将此 ID 写入 Stripe 订阅。您可以在从流程打开 PaymentSheet 中展示该流程。

struct StripeFlow {
    let configuration: AdaptyUI.FlowConfiguration
    let variationId: String
}

@MainActor
func loadStripeFlow() async throws -> StripeFlow {
    // If the prices fail to load, the flow shows the tags' initial values
    let prices = (try? await Backend.fetchPrices()) ?? [:]

    let flow = try await Adapty.getFlow(placementId: "YOUR_PLACEMENT_ID")
    let configuration = try await AdaptyUI.getFlowConfiguration(
        forFlow: flow,
        tagResolver: [
            "stripe_monthly_price": prices["monthly"],
            "stripe_annual_price": prices["annual"],
        ].compactMapValues { $0 }
    )
    return StripeFlow(configuration: configuration, variationId: flow.variationId)
}

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

Adapty 展示类型需要 iOS 16。如果您的应用支持更早版本,请在本指南中使用这些类型的代码上添加 @available(iOS 16.0, *)。

添加打开 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)),例如线下活动的会员资格。对于数字内容或功能,请通过 网页付费墙 提供其他支付方式。

该流程照常显示您的 App Store 产品,用户点击”以其他方式付款”等链接即可打开 PaymentSheet。App Store 购买按钮无需任何改动,仍可正常使用。

  1. 将 Custom Action 操作分配给该链接,并设置一个操作 ID,例如 pay_with_stripe。
  2. 为流程中的每个 App Store 产品,创建一个对应相同套餐的 Stripe 价格。
  3. 在你的应用中,将每个 App Store 产品 ID 映射到其对应的 Stripe 套餐。
  4. 存储用户选择的产品。流程会通过 UIKit 中的 flowController(_:didSelectProduct:) 或 SwiftUI 中 .flow 修饰符的 didSelectProduct 闭包来上报每次选择。在流程与付费墙编辑工具中构建的流程默认不会上报用户选择的产品,因此请以你在编辑工具中设置为选中状态的产品作为起始值。如果 A/B 测试的各实验变体选择了不同的产品,则需要为每个实验变体分别存储其默认产品。
  5. 当应用收到 pay_with_stripe 时,使用已存储产品对应的 Stripe 套餐,调用从流程中打开 PaymentSheet 中的 StripeCheckout.pay(plan:variationId:over:)。

流程中显示的是这些产品在 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

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

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

本示例使用 Node.js(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。

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

enum Backend {
    static let baseURL = URL(string: "https://YOUR_BACKEND")!

    struct Subscription: Decodable {
        let subscriptionId: String
        let clientSecret: String
        let publishableKey: String
    }

    struct BackendError: LocalizedError, Decodable {
        let error: String
        var errorDescription: String? { error }
    }

    struct HTTPError: LocalizedError {
        let statusCode: Int
        var errorDescription: String? { "The server returned HTTP \(statusCode)." }
    }

    static func fetchPrices() async throws -> [String: String] {
        let request = URLRequest(url: baseURL.appendingPathComponent("prices"))
        return try await send(request)
    }

    static func createSubscription(plan: String, variationId: String) async throws -> Subscription {
        var request = URLRequest(url: baseURL.appendingPathComponent("subscriptions"))
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        // add your authentication header
        request.httpBody = try JSONEncoder().encode([
            "plan": plan,
            "variationId": variationId,
        ])
        return try await send(request)
    }

    private static func send<T: Decodable>(_ request: URLRequest) async throws -> T {
        let (data, response) = try await URLSession.shared.data(for: request)
        let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
        guard statusCode == 200 else {
            // Use the backend's message when the response has one
            throw (try? JSONDecoder().decode(BackendError.self, from: data)) ?? HTTPError(statusCode: statusCode)
        }
        return try JSONDecoder().decode(T.self, from: data)
    }
}

从流程中打开 PaymentSheet

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

  1. 将自定义操作 ID 映射到对应方案。在应用等待后端响应或显示 PaymentSheet 期间,忽略用户的点击操作以及流程的关闭按钮。这样每次点击只会创建一个订阅。
  2. 向后端请求订阅,并传入方案及流程的 variationId。
  3. 在流程上方显示 PaymentSheet,并处理其结果:
    • Completed:关闭流程。关闭后,等待访问等级生效。
    • Canceled:不执行任何操作。用户留在流程中,可以选择其他方案。
    • Failed:显示错误信息。用户留在流程中,可以重试。
  4. 处理流程的关闭和打开 URL 操作。您的操作处理器会替代 SDK 的默认处理器,后者负责关闭流程和打开 URL。
  5. 实现购买和恢复处理器,在 SwiftUI 中还需实现错误处理器。即使流程中没有 App Store 产品,SDK 也要求实现这些处理器。

步骤 2 和步骤 3 在 UIKit 和 SwiftUI 中完全相同,因此本指南将它们合并到一个章节中:


@MainActor
final class StripeCheckout {
    // Custom action IDs from the flow, mapped to your backend's plan keys
    static let plans = [
        "buy_stripe_monthly": "monthly",
        "buy_stripe_annual": "annual",
    ]

    private(set) var isPaying = false

    /// Opens PaymentSheet for a plan over the flow. Returns `true` when the user paid.
    func pay(plan: String, variationId: String, over presenter: UIViewController) async -> Bool {
        guard !isPaying else { return false }
        isPaying = true
        defer { isPaying = false }

        do {
            let subscription = try await Backend.createSubscription(
                plan: plan,
                variationId: variationId
            )
            // The flow may have closed, or opened a link, while the backend responded
            guard presenter.viewIfLoaded?.window != nil, presenter.presentedViewController == nil else {
                return false
            }

            STPAPIClient.shared.publishableKey = subscription.publishableKey
            var configuration = PaymentSheet.Configuration()
            configuration.merchantDisplayName = "YOUR_BUSINESS_NAME"
            // For payment methods that redirect to another app, such as bank apps
            configuration.returnURL = "your-app://stripe-redirect"

            let paymentSheet = PaymentSheet(
                paymentIntentClientSecret: subscription.clientSecret,
                configuration: configuration
            )
            let result = await withCheckedContinuation { continuation in
                paymentSheet.present(from: presenter) { continuation.resume(returning: $0) }
            }

            switch result {
            case .completed:
                return true
            case .canceled:
                return false // the user stays on the flow
            case let .failed(error):
                showError(error, over: presenter)
                return false
            }
        } catch {
            showError(error, over: presenter)
            return false
        }
    }

    /// Opens a URL from the flow in the browser that the flow's button specifies.
    func open(_ url: URL, presentation: AdaptyWebPresentation, over presenter: UIViewController) {
        let isWebURL = url.scheme == "https" || url.scheme == "http"
        if presentation == .inAppBrowser, isWebURL {
            presenter.present(SFSafariViewController(url: url), animated: true)
        } else {
            UIApplication.shared.open(url)
        }
    }

    private func showError(_ error: Error, over presenter: UIViewController) {
        let alert = UIAlertController(
            title: "The payment didn't go through",
            message: error.localizedDescription,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        presenter.present(alert, animated: true)
    }
}

付款完成后,对于需要跳转到其他应用的支付方式,PaymentSheet 会通过返回 URL 跳回你的应用。按照 Stripe 文档中设置返回 URL 的说明,在应用中注册 URL scheme,并在应用接收到该 URL 时将其传递给 Stripe:

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

如果你的流程还需要销售 App Store 产品,请按照处理流程事件中的说明,在购买处理程序中处理相应的购买逻辑。

支付后解锁访问权限

支付完成后,Adapty 会接收 Stripe 的 webhook 并在几秒内授予访问等级。SDK 每分钟刷新一次用户画像,因此请持续请求用户画像,直到访问等级变为激活状态:

@MainActor
func waitForAccess() async -> Bool {
    for _ in 1...20 {
        if let profile = try? await Adapty.getProfile(),
           profile.accessLevels["YOUR_ACCESS_LEVEL"]?.isActive == true {
            return true
        }
        try? await Task.sleep(for: .seconds(3))
    }
    return false
}

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

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

让用户管理订阅

Stripe 订阅不会出现在 iOS 设置中用户的 App Store 订阅列表里。为了让用户能够取消订阅或更改付款方式,请在应用中添加一个按钮(例如在账户页面),用于打开 Stripe 客户门户。您的后端需要为该用户的 Stripe 客户创建一个门户会话,并返回其 URL。

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

测试集成

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

  1. 使用已连接到 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,以及版位 ID(位于 developer_id)。对于 Stripe 购买,variation_id 与 flow_variation_id 的值相同。

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

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

限制

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