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

iOS集成Stripe:卡片保存与复用技术咨询

Stripe Integration Guide for Your Usage-Based Billing App

Hey there! Let's break down your Stripe integration questions step by step— I've been through a similar setup for a usage-based subscription app, so I know exactly where you're coming from. No need to worry about physical addresses here; we can focus purely on payment card management.


1. Linking Payment Cards to a Specific customer_id

Stripe's Customer object is the core of saved payment methods, so here's the clear play-by-play:

Step 1: Create a Customer (Server-Side Only)

First, you need a unique customer_id for each user. Always create this server-side when a user signs up—never do this client-side, since it requires your sensitive Stripe secret key.

# Example Ruby server code
customer = Stripe::Customer.create(
  email: "user@yourapp.com",
  description: "Usage-based billing user"
)
# Store customer.id in your database linked to the user's account

To save a card, use Stripe's iOS SDK to securely collect card info (never handle raw card numbers yourself), generate a PaymentMethod, then attach it to the customer via your server.

Client-Side (iOS)

Use STPPaymentCardTextField or the more robust STPPaymentSheet to collect card details. Here's a quick example with the text field:

// When the user submits their card details
if let cardParams = cardTextField.cardParams {
  STPPaymentMethod.create(withCard: cardParams, completion: { paymentMethod, error in
    guard let paymentMethod = paymentMethod else {
      // Handle validation errors (e.g., invalid card number)
      return
    }
    // Send the paymentMethod.id to your backend
    yourAPIClient.attachPaymentMethod(toCustomer: customerId, paymentMethodId: paymentMethod.id) { success in
      // Show a success message to the user
    }
  })
}

Server-Side

Attach the PaymentMethod to the customer using your Stripe secret key:

# Example Ruby server code
Stripe::PaymentMethod.attach(
  params[:payment_method_id],
  customer: params[:customer_id]
)

Step 3: Reusing Saved Cards

When you need to charge the user later, fetch their saved PaymentMethods server-side (or via an ephemeral key client-side) and use the payment_method ID when creating a PaymentIntent:

# Server-side: Create a PaymentIntent with the saved card
payment_intent = Stripe::PaymentIntent.create(
  amount: calculateUsageCharges(), # Your usage-based amount in cents
  currency: "usd",
  customer: customer_id,
  payment_method: saved_payment_method_id,
  confirm: true # Auto-confirm if charging immediately
)

2. Ephemeral Keys: When Do You Need Them?

This is a super common point of confusion—let's cut through the noise:

  • Ephemeral keys are mandatory if you want to access a Customer's sensitive data (like saved payment methods) from the client-side. They act as short-lived, restricted tokens that let your iOS app interact with Stripe's Customer API without exposing your secret key.
  • Why some tutorials skip them? If you're only doing one-time payments without saving cards, you might not need them—you can create a PaymentIntent server-side and confirm it directly client-side. But since you need saved cards, ephemeral keys are non-negotiable for:
    • Fetching saved payment methods to display to the user
    • Using STPPaymentSheet to let users select saved cards (the sheet uses ephemeral keys under the hood)

How to Use Ephemeral Keys

Generate them server-side when your client needs access to the customer's data:

# Example Ruby server code
ephemeral_key = Stripe::EphemeralKey.create(
  customer: customer_id,
  stripe_version: "2024-06-20" # Use your active Stripe API version
)
# Send ephemeral_key.secret to your iOS client

On iOS, pass this key to STPPaymentSheet during initialization, or use it with STPCustomerContext to fetch saved payment methods manually.


3. Stripe ViewControllers for Adding/Displaying Saved Cards

Stripe provides pre-built, compliance-friendly UI components to avoid reinventing the wheel:

Adding Saved Cards

  • STPPaymentSheet (Highly Recommended): This is Stripe's all-in-one payment UI that supports adding new cards and selecting saved ones. It automatically handles 3D Secure, card validation, and regulatory compliance. To use it, you'll need to pass the customer ID, ephemeral key, and either a PaymentIntent (for immediate charges) or SetupIntent (for just saving a card).
  • STPPaymentCardTextField: A lightweight text field for collecting card details if you want to build a fully custom UI around it. You'll still need to handle attaching the card to the customer as we covered earlier.

Displaying Saved Cards

  • STPPaymentSheet: When initialized with a customer and ephemeral key, the sheet will automatically show all saved payment methods for the user—they can pick an existing one or add a new card in the same flow.
  • Custom UITableView: If you want full control over the UI, fetch the customer's PaymentMethods using STPCustomerContext (which requires an ephemeral key), then use STPPaymentMethodCell to display card details (brand, last 4 digits, expiration date) in a table view.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:12:50