# Apple Pay

让客户通过其 Apple 设备上的 Apple Pay 安全完成支付。

Apple Pay 是一种数字钱包，客户无需手动输入银行卡信息，即可使用存储在 Apple 设备上的银行卡进行支付。客户可以在 iPhone、iPad、Mac 或 Apple Watch 上使用 Apple Pay 支付。有关支持设备的完整列表，请参阅 Apple 的[兼容性文档](https://support.apple.com/en-us/HT208531)。

对于 Payment Links 或托管式 Checkout，无需任何额外配置即可使用 Apple Pay。对于 Elements 或嵌入式 Checkout，则需要注册域名才能使用 Apple Pay。应用内支付需要进行额外配置。

#### 支付方式属性

- **客户所在地**

  全球1

- **出示货币**

  参见[受支持的出示货币](https://docs.stripe.com/currencies.md#presentment-currencies)

- **支付确认**

  客户发起

- **支付方式类型**

  钱包

- **经常性付款**

  [是](https://docs.stripe.com/apple-pay.md#recurring-payments)

- **提现时间**

  适用标准提现时间

- **Connect 支持**

  是

- **争议支持**

  [是](https://docs.stripe.com/apple-pay/disputes-refunds.md#disputed-payments)

- **手动捕获支持**

  是

- **退款/部分退款**

  [是 / 是](https://docs.stripe.com/apple-pay/disputes-refunds.md#refunds)

1 针对印度地区客户的 Apple Pay 定期付款功能即将推出。

#### 商家所在地

全球范围内的 Stripe 账户均可接收 Apple Pay 付款，并支持本地币种结算。

#### 产品支持

- Connect
- Checkout1

- Payment Links
- Elements
- Subscriptions
- Invoicing

1当 Checkout 的 [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) 为 `embedded_page` 时，它仅支持 Safari 和 iOS 的 17 或更高版本。

## Apple Pay 的 App Store 应用内购买规则

本指南说明了如何配置您的应用以直接接受 Apple Pay 支付实体商品、服务及其他符合条件的商品。Stripe 负责处理这些付款，您只需支付 Stripe 的[处理费用](https://stripe.com/pricing)。

对于在美国或欧洲经济区 (EEA) 销售的数字产品、内容和订阅服务，您的 iOS 应用可以通过重定向至外部支付页面来接受 Apple Pay。您可以使用以下支付 UI：

- [Stripe Checkout](https://docs.stripe.com/mobile/digital-goods/checkout.md)
- [Web Elements](https://docs.stripe.com/mobile/digital-goods/custom-checkout.md)
- [Payment Links](https://docs.stripe.com/mobile/digital-goods/payment-links.md)（最适合产品和定价数量有限的场景）

在其他地区，您的 iOS 应用无法针对数字产品、内容或订阅服务接受 Apple Pay。

## 接受 Apple Pay

Stripe 提供了多种添加 Apple Pay 的方法。有关集成的详细信息，请选择您最喜欢的方法：

# React Native iOS


使用 Stripe [React Native SDK](https://github.com/stripe/stripe-react-native) 同时接受 Apple Pay 和传统信用卡支付。开始之前，请注册 [Apple Developer Program](https://developer.apple.com/programs/)，并[在您的服务器和应用中设置 Stripe](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=react-native#react-native-setup)。然后，[注册 Apple Merchant ID](https://docs.stripe.com/apple-pay.md#merchantid) 并[创建一个新的 Apple Pay 证书](https://docs.stripe.com/apple-pay.md#csr)。

1. [用 Xcode 集成](https://docs.stripe.com/apple-pay.md#xcode-pay)
2. [在 StripeProvider 中设置您的 Apple Merchant ID](https://docs.stripe.com/apple-pay.md#set-merchantid)
3. [检查是否支持 Apple Pay](https://docs.stripe.com/apple-pay.md#check-if-apple-pay-supported)
4. [出示支付表单](https://docs.stripe.com/apple-pay.md#present-payment-sheet)
5. [向 Stripe 提交付款](https://docs.stripe.com/apple-pay.md#handle-payment)

> 如果您使用的是 React Native 和 Expo，则 Expo Go 不支持 Apple Pay。要将 Expo 与 Apple Pay 结合使用，您必须创建一个[开发版本](https://docs.expo.dev/get-started/set-up-your-environment/?mode=development-build&platform=ios)。如果您已经有 Expo Go 项目，您可以[将其迁移到开发版本](https://docs.expo.dev/develop/development-builds/expo-go-to-dev-build/)。

## 注册 Apple Merchant ID

可通过在 Apple 开发人员网站[注册新的标识符](https://developer.apple.com/account/resources/identifiers/add/merchant)来获取 Apple 商家 ID。

在表单中填写描述和标识符。描述内容仅供您自己记录之用，之后可随时更改。Stripe 建议用您的应用的名称作为标识符（例如，`merchant.com.{{YOUR_APP_NAME}}`）。

## 创建新的 Apple Pay 证书

为您的应用创建证书，以加密支付数据。

转到管理平台中的 [iOS 证书设置](https://dashboard.stripe.com/settings/ios_certificates)，点击**添加新应用程序**，然后按照说明进行操作。

下载证书签名请求 (CSR) 文件，来从 Apple 获取安全证书，以便使用 Apple Pay。

必须用一个 CSR 文件发布具体的一个证书。如果您切换您的 Apple Merchant ID，则必须前往管理平台的 [iOS 证书设置](https://dashboard.stripe.com/settings/ios_certificates)中获取一个新的 CSR 和证书。

## 集成 Xcode

将 Apple Pay 功能添加到您的应用程序。在 Xcode 中，打开您的项目设置，点击**签名和功能**选项卡，然后添加 **Apple Pay** 功能。此时，系统可能会提示您登入您的开发人员账户。选择您之前创建的商家 ID，您的应用程序就可以接受 Apple Pay 了。
![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png)

在 Xcode 中启用 Apple Pay 功能

## 在 StripeProvider 中设置您的 Apple Merchant ID

在 `StripeProvider` 组件中，指定您成功注册的 Apple Merchant ID：

```jsx
import { StripeProvider } from '@stripe/stripe-react-native';

function App() {
  return (
    <StripeProvider
      publishableKey="<<YOUR_PUBLISHABLE_KEY>>"
      merchantIdentifier="merchant.com.{{YOUR_APP_NAME}}"
    >
      {/* Your app code here */}
    </StripeProvider>
  );
}
```

## 检查是否支持 Apple Pay

在您的应用程序中显示 Apple Pay 此支付选项之前，请确定用户的设备支持 Apple Pay，并且他们的钱包中添加了银行卡：

```jsx
import { PlatformPayButton, isPlatformPaySupported } from '@stripe/stripe-react-native';

function PaymentScreen() {
  const [isApplePaySupported, setIsApplePaySupported] = useState(false);

  useEffect(() => {
    (async function () {
      setIsApplePaySupported(await isPlatformPaySupported());
    })();
  }, [isPlatformPaySupported]);

  // ...

  const pay = async () => {
    // ...
  };

  // ...

  return (
    <View>
      {isApplePaySupported && (
        <PlatformPayButton
          onPress={pay}
          type={PlatformPay.ButtonType.Order}
          appearance={PlatformPay.ButtonStyle.Black}
          borderRadius={4}
          style={{
            width: '100%',
            height: 50,
          }}
        />
      )}
    </View>
  );
}
```

## 创建 Payment Intent

### 服务器端

生成一个端点，创建一个具有 [amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-amount) 和 [currency](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-currency) 的 PaymentIntent。始终在服务器端决定扣款金额，这是一个可信的环境，客户端不行。这样可防止客户自己选择价格。

#### curl

```bash
curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "amount"=1099 \
  -d "currency"="usd"
```

### 客户端

创建一个从您的服务器请求 PaymentIntent 的方法：

```jsx
function PaymentScreen() {
  // ...
  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        some: 'value',
      }),
    });
    const { clientSecret } = await response.json();

    return clientSecret;
  };
  // ...
}
```

### 故障排除

如果您在尝试创建令牌时看到 Stripe API 出现错误，则很可能是您的 Apple Pay Certificate 有问题。如本页所述，您需要生成一个新证书并上传到 Stripe。请确保您使用的是从您的管理平台获得的 CSR，而不是您自己生成的那个。Xcode 经常错误地缓存旧的证书，所以除了生成新证书外，Stripe 建议创建一个新的 Apple Merchant ID。

如果您收到错误：

> 您尚未将您的 Apple 商家账户添加到 Stripe

您的应用程序好像正在发送用以前的（非 Stripe） CSR/Certificate 加密的数据。务必撤销您的 Apple Merchant ID 下任何不是由 Stripe 生成的证书。如果这样不能解决问题，请删除您的 Apple 账户中的商家 ID，然后重新创建它。然后，根据之前使用的相同（Stripe 提供的） CSR 创建一个新证书。您不需要将此新的证书上传到 Stripe。完成后，在您的应用程序中打开并关闭 Apple Pay Credentials，以确保正确刷新。

## 出示支付表单

在 [PlatformPayButton](https://stripe.dev/stripe-react-native/api-reference/index.html#PlatformPayButton) 的 `onPress` 属性中，调用 `confirmPlatformPayPayment` 以打开 Apple Pay 支付界面。若要在支付界面上显示客户的购物车商品，请将这些商品作为参数传入。最后一项必须是您的公司和总金额；该项显示在支付界面时，会在前面加上“Pay”字样（例如，“Pay iHats, Inc. 50 USD”）。

> 在您的那些处理客户操作的代码中，不要在显示支付表单前包含任何复杂或异步操作。如果用户操作不直接调用支付表单，Apple Pay 会返回一个错误。

```jsx
import { confirmPlatformPayPayment } from '@stripe/stripe-react-native';

function PaymentScreen() {
  // ... see above

  const pay = async () => {
    const clientSecret = await fetchPaymentIntentClientSecret()
    const { error, paymentIntent } = await confirmPlatformPayPayment(
      clientSecret,
      {
        applePay: {
          cartItems: [
            {
              label: 'Example item name',
              amount: '14.00',
              paymentType: PlatformPay.PaymentType.Immediate,
            },
            {
              label: 'Tax',
              amount: '1.60',
              paymentType: PlatformPay.PaymentType.Immediate,
            },
            {
              label: 'iHats, Inc.',
              amount: '15.60',
              paymentType: PlatformPay.PaymentType.Immediate,
            },
          ],
          merchantCountryCode: 'US',
          currencyCode: 'USD',
          requiredShippingAddressFields: [
            PlatformPay.ContactField.PostalAddress,
          ],
          requiredBillingContactFields: [PlatformPay.ContactField.PhoneNumber],
        },
      }
    );
    if (error) {
      // handle error
    } else {
      Alert.alert('Success', 'Check the logs for payment intent details.');
      console.log(JSON.stringify(paymentIntent, null, 2));
    }
  };

  // ... see above
}
```

## Optional: 创建 Payment Method [客户端]

如果您在服务器端确认支付，则可以使用 Apple Pay 仅收集 `PaymentMethod` 而无需确认支付。为此，请调用 `createPlatformPayPaymentMethod` 方法：

```javascript
import {PlatformPayButton, isPlatformPaySupported, createPlatformPayPaymentMethod} from '@stripe/stripe-react-native';

function PaymentScreen() {
  const [isApplePaySupported, setIsApplePaySupported] = useState(false);

  useEffect(() => {
    (async function () {
      setIsApplePaySupported(await isPlatformPaySupported());
    })();
  }, [isPlatformPaySupported]);

  const createPaymentMethod = async () => {
    const { error, paymentMethod } = await createPlatformPayPaymentMethod({
      applePay: {
        cartItems: [
          {
            label: 'Example item name',
            amount: '14.00',
            paymentType: PlatformPay.PaymentType.Immediate,
          },
          {
            label: 'Total',
            amount: '12.75',
            paymentType: PlatformPay.PaymentType.Immediate,
          },
        ],
        merchantCountryCode: 'US',
        currencyCode: 'USD',
      },
    });

    if (error) {
      Alert.alert(error.code, error.message);
      return;
    } else if (paymentMethod) {
      Alert.alert(
        'Success',
        `The payment method was created successfully. paymentMethodId: ${paymentMethod.id}`
      );
    }
  };

  return (
    <View >
      {isApplePaySupported && (
        <PlatformPayButton
          onPress={createPaymentMethod}
          type={PlatformPay.ButtonType.SetUp}
          appearance={PlatformPay.ButtonStyle.WhiteOutline}
          style={{
            width: '65%',
            height: 50,
          }}
        />
      )}
    </View>
  );
}
```

## Optional: 经常性付款 [客户端]

在 iOS 16 及以上版本中，可通过在 `confirmPlatformPayPayment()` 和 `confirmPlatformPaySetupIntent` 的 `applePay` 参数对象中设置 `request` 字段来采用[商家令牌](https://developer.apple.com/apple-pay/merchant-tokens/)。

```js
await confirmPlatformPayPayment(
  clientSecret,
  {
    applePay: {
      // Make sure to include the rest of the necessary fields
      request: {
        type: PlatformPay.PaymentRequestType.Recurring,
        description: 'String describing my payment',
        managementUrl:
          'www.<a URL where the user can update the payment method for the recurring payment>.com',
        billing: {
          paymentType: PlatformPay.PaymentType.Recurring,
          intervalUnit: PlatformPay.IntervalUnit.Month,
          intervalCount: 3,
          label: 'My label',
          amount: '39.00',
        },
      },
    },
  }
);
```

要了解有关如何通过 Apple Pay 使用经常性付款的更多信息，请参阅 [Apple 的 PassKit 文档](https://developer.apple.com/documentation/passkit/pkpaymentrequest)。

## Optional: 订单跟踪 [客户端]

要在 iOS 16 及以上版本中采用[订单跟踪](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)，为 `PlatformPayButton` 组件使用 `setOrderTracking` 回调。

在您的部署环境中：

1. 从您的服务器获取已完成订单的详情。
2. 用结果在 `setOrderTracking` 中从您的服务器调用提供的完成处理程序。

```jsx
<PlatformPayButton
  // Make sure to include the rest of the necessary props
  setOrderTracking={(completion) => {
    const { orderIdentifier, orderType, authToken, webServiceUrl } =
      fetchOrderDetailsFromMyBackend();
    completion(orderIdentifier, orderType, authToken, webServiceUrl);
  }}
/>
```

要了解有关订单跟踪的更多信息，请参阅 [Apple 钱包订单文档](https://developer.apple.com/documentation/walletorders)。


## 测试 Apple Pay

要测试 Apple Pay，必须使用真实的信用卡卡号和测试 [API 密钥](https://docs.stripe.com/keys.md)。Stripe 会识别到您处于测试模式，并返回一个成功的测试卡令牌供您使用，因此您可以在不收款的情况下使用真实卡来测试付款。

您无法将[Stripe测试卡](https://docs.stripe.com/testing.md#use-test-cards)或 [Apple Pay 测试卡](https://developer.apple.com/apple-pay/sandbox-testing/)保存到 Apple Pay 钱包来测试 Apple Pay。

## See also

- [iOS 集成](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios)
- [网页版 Apple Pay](https://docs.stripe.com/elements/express-checkout-element.md)
- [Apple Pay 最佳实践](https://docs.stripe.com/apple-pay/best-practices.md)
