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

如何在Swift/SwiftUI iOS应用中调用Stripe API创建Stripe Payment Link?

在iOS(Swift/SwiftUI)中使用Stripe API创建Payment Link及请求机制

Stripe的Payment Link API是一个REST接口(POST /v1/payment_links),核心逻辑如下:

  • 向Stripe服务器发送包含商品信息、金额、支付配置等参数的请求
  • 请求必须通过Bearer Token身份验证(使用Stripe私钥)
  • Stripe验证通过后,生成唯一的支付链接URL返回,你可在App内打开该链接引导用户完成支付

重点提醒:Stripe私钥绝对不能直接放在iOS客户端代码中,一旦被逆向破解,攻击者会滥用你的账户权限。生产环境必须通过自己的后端服务代理请求,客户端仅与你的后端交互获取支付链接。以下示例仅用于演示API调用流程,请勿直接用于生产。

二、用URLSession实现的具体步骤

1. 定义Codable模型(序列化请求参数、解析响应)

// 响应模型
struct PaymentLinkResponse: Codable {
    let url: String // 生成的支付链接
    let id: String // Payment Link的唯一ID
}

2. 构建URLSession请求并发送

结合Swift的async/await实现异步请求:

func createStripePaymentLink() async throws -> String {
    // 仅演示用,生产环境请替换为你的后端接口地址
    let stripeApiUrl = URL(string: "https://api.stripe.com/v1/payment_links")!
    let stripeSecretKey = "sk_test_your_test_secret_key" // 测试用私钥,生产环境绝对不能放这里
    
    var request = URLRequest(url: stripeApiUrl)
    request.httpMethod = "POST"
    
    // 设置请求头
    request.setValue("Bearer \(stripeSecretKey)", forHTTPHeaderField: "Authorization")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
    // 构建form-urlencoded格式的请求参数(Stripe API支持该格式和JSON)
    let params: [String: String] = [
        "line_items[0][price_data][currency]": "usd",
        "line_items[0][price_data][product_data][name]": "Premium Subscription",
        "line_items[0][price_data][unit_amount]": "3999", // $39.99,单位为分
        "line_items[0][quantity]": "1"
    ]
    
    // 编码参数为请求体数据
    request.httpBody = params
        .map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)" }
        .joined(separator: "&")
        .data(using: .utf8)
    
    // 发送请求并处理响应
    let (data, response) = try await URLSession.shared.data(for: request)
    
    guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
        let errorDetails = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
        throw NSError(domain: "StripeAPIError", code: httpResponse.statusCode, userInfo: errorDetails)
    }
    
    let paymentLink = try JSONDecoder().decode(PaymentLinkResponse.self, from: data)
    return paymentLink.url
}

3. 在SwiftUI视图中调用并使用支付链接

struct PaymentView: View {
    @State private var paymentUrl: String?
    @State private var errorMessage: String?
    
    var body: some View {
        VStack(spacing: 20) {
            if let url = paymentUrl {
                Button("前往支付") {
                    guard let paymentLink = URL(string: url) else { return }
                    UIApplication.shared.open(paymentLink)
                }
                .buttonStyle(.borderedProminent)
            } else {
                Button("创建支付链接") {
                    Task {
                        do {
                            paymentUrl = try await createStripePaymentLink()
                            errorMessage = nil
                        } catch {
                            errorMessage = "创建失败:\(error.localizedDescription)"
                        }
                    }
                }
            }
            
            if let msg = errorMessage {
                Text(msg)
                    .foregroundColor(.red)
                    .font(.caption)
            }
        }
        .padding()
    }
}

三、关键注意事项

  • 后端代理要求:生产环境必须将Stripe API调用放在你的后端服务中,客户端请求后端获取支付链接,避免暴露私钥。
  • 参数编码:Stripe API支持application/json和application/x-www-form-urlencoded两种格式,根据需求选择即可。
  • 错误处理:实际开发中要解析Stripe返回的错误详情(通常包含error字段),给用户更友好的提示。
  • 测试环境:使用Stripe提供的测试密钥和测试信用卡(如4242 4242 4242 4242)进行调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:21:32