# Apple Pay

顧客が iPhone、iPad、および Apple Watch で Apple Pay を使用して安全に支払いを実行できるようにします。

Apple Pay に対応しているデバイスについては、Apple の[互換性に関するドキュメント](https://support.apple.com/en-us/HT208531)を参照してください。

Apple Pay は、ほとんどの Stripe プロダクトおよびサービスと互換性があります。Stripe ユーザーは、iOS 9 以降の iOS アプリケーション、および iOS 10 または macOS Sierra 以降の Safari (ウェブ) で [Apple Pay](https://stripe.com/apple-pay) を受け付けることができます。Apple Pay 決済の処理に追加料金はかからず、他のカード取引と同じ[料金体系](https://stripe.com/pricing/local-payment-methods#apple-pay)が適用されます。

Apple Pay を利用できるのは、サポート対象国の加盟銀行のカードの保有者です。詳細については Apple の[加盟銀行](https://support.apple.com/en-us/ht204916)に関するドキュメントをご覧ください。

#### 決済手段のプロパティ

- **顧客の所在地**

  インドを除く世界各地

- **取引通貨**

  [サポートされている取引通貨](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)

#### ビジネスの所在地

インドを除く世界各地の Stripe アカウントは、Apple Pay による支払いを現地通貨決済で受け付けることができます。

#### サポート対象のプロダクト

- Connect
- Checkout1

- Payment Links
- Elements
- Subscriptions
- Invoicing

1Checkout の [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) が `embedded_page` の場合、Safari と iOS のバージョン 17 以降のみがサポートされます。

## 決済フロー

以下は、決済ページから行われる Apple Pay の決済フローのデモンストレーションです。
![テスト中に Apple Pay の支払いフローのアニメーションは、Stripe 決済フローページ、Apple Pay ボタン、確認ダイアログを示します。](https://b.stripecdn.com/docs-statics-srv/assets/apple-pay.3447ce2deeaab40d6d231eed4dc34644.gif)

## Apple Pay のアプリ内課金の資格

このガイドでは、物理的な製品、サービス、その他の対象となる品目に対し、Apple Pay を直接受け付けるように App を設定する方法について説明します。Stripe はこれらの決済を処理し、Stripe の [処理手数料](https://stripe.com/pricing) のみを支払います。

アメリカまたは欧州経済領域 (EEA) で販売されるデジタル製品、コンテンツ、サブスクリプションの場合、アプリは、外部の決済ページにリダイレクトすることで 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) (商品数と価格が限定されている場合に最適)

その他の地域では、デジタル製品、コンテンツ、またはサブスクリプションに対して App で Apple Pay を使用することはできません。

## Apple Pay を受け付ける

Stripe では、さまざまな方法で Apply Pay を支払い方法として追加することができます。組み込みの詳細については、各方法から選択してご確認ください。

# Native iOS

> This is a Native iOS for when platform is ios. View the full page at https://docs.stripe.com/apple-pay?platform=ios.

> Stripe の[構築済み UI](https://docs.stripe.com/payments/mobile.md) を使用している場合は、代わりに[このガイド](https://docs.stripe.com/payments/mobile/accept-payment.md?platform=ios&type=payment#apple-pay)の手順に従ってください。

[Stripe iOS SDK](https://github.com/stripe/stripe-ios) を使用すると、Apple Pay と従来のクレジットカードによる決済の両方を受け付けることができます。開始前に [Apple Developer Program (Apple 開発者プログラム) (英語)](https://developer.apple.com/programs/) に登録する必要があります。次に、以下の手順に従ってください。

1. [Stripe を設定する](https://docs.stripe.com/apple-pay.md#setup)
1. [Apple 加盟店 ID を登録する](https://docs.stripe.com/apple-pay.md#merchantid)
1. [新しい Apple Pay 証明書を作成する](https://docs.stripe.com/apple-pay.md#csr)
1. [Xcode を導入する](https://docs.stripe.com/apple-pay.md#xcode-pay)
1. [Apple Pay がサポートされているかを確認する](https://docs.stripe.com/apple-pay.md#check-if-apple-pay-supported)
1. [支払いリクエストを作成する](https://docs.stripe.com/apple-pay.md#create-payment-request)
1. [支払い画面を表示する](https://docs.stripe.com/apple-pay.md#present-payment-sheet)
1. [Stripe に支払いを送信する](https://docs.stripe.com/apple-pay.md#handle-payment)

## Stripe を設定する [サーバー側] [クライアント側]

まず、Stripe アカウントが必要です。[今すぐ登録してください](https://dashboard.stripe.com/register)。

### サーバー側

この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから Stripe API にアクセスするには、Stripe の公式ライブラリーを使用します。

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

### クライアント側

[Stripe iOS SDK](https://github.com/stripe/stripe-ios) はオープンソースです。[詳細なドキュメントが提供されており](https://stripe.dev/stripe-ios/index.html)、iOS 13 以降をサポートするアプリと互換性があります。

#### Swift Package Manager

SDK をインストールするには、以下のステップに従います。

1. Xcode で、**File (ファイル)** > **Add Package Dependencies… (パッケージ依存関係を追加)** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。
1. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。
1. **StripeApplePay** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。

#### CocoaPods

1. まだインストールしていない場合は、[CocoaPods](https://guides.cocoapods.org/using/getting-started.html) の最新バージョンをインストールします。
1. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。
   ```bash
   pod init
   ```
1. この行を `Podfile` に追加します。
   ```podfile
   pod 'StripeApplePay'
   ```
1. 以下のコマンドを実行します。
   ```bash
   pod install
   ```
1. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。
1. 今後、SDK の最新バージョンに更新するには、以下を実行します。
   ```bash
   pod update StripeApplePay
   ```

#### Carthage

1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。
1. この行を `Cartfile` に追加します。
   ```cartfile
   github "stripe/stripe-ios"
   ```
1. [Carthage のインストール手順](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)に従います。必ず、[こちら](https://github.com/stripe/stripe-ios/tree/master/StripeApplePay/README.md#manual-linking)にリストされている必要なフレームワークのすべてを埋め込んでください。
1. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。
   ```bash
   carthage update stripe-ios --platform ios
   ```

#### 手動のフレームワーク

1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。
1. **StripeApplePay.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。
1. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripeApplePay/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。
1. 今後、Stripe の SDK の最新バージョンに更新するには、ステップ 1 から 3 を繰り返します。

> SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases (リリース)](https://github.com/stripe/stripe-ios/releases) ページをご覧ください。リポジトリの[リリースをウォッチ](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)して、新しいリリースの公開時に通知を受け取ることも可能です。

アプリの起動時に Stripe [公開可能キー](https://dashboard.stripe.com/test/apikeys)を使用して SDK を設定します。これにより、アプリが Stripe API にリクエストを送信できるようになります。

#### Swift

```swift
import UIKitimportStripeApplePay

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<<YOUR_PUBLISHABLE_KEY>>"
        // do any other necessary launch configuration
        return true
    }
}
```

> テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。

## Apple 加盟店 ID を登録する

Apple Developer Web サイトで [新規 ID を登録](https://developer.apple.com/account/resources/identifiers/add/merchant) して、Apple 加盟店 ID を取得します。

フォームに説明と ID を入力します。説明はお客様の記録用であり、後で変更できます。アプリの名前を ID として使用することをお勧めします (`merchant.com.{{YOUR_APP_NAME}}` など)。

## 新しい Apple Pay 証明書を作成する

支払いデータを暗号化するためのアプリの証明書を作成します。

ダッシュボードの [iOS certificate settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、**新規アプリケーションを追加**をクリックし、表示されるガイドに従います。

証明書署名リクエスト (CSR) ファイルをダウンロードして、Apple Pay の利用を可能にする安全な証明書を Apple から取得します。

1 つの CSR ファイルを使用して証明書を 1 つだけ発行する必要があります。Apple 加盟店 ID を切り替えた場合、ダッシュボードの [iOS Certificate Settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、新しい CSR と証明書を取得する必要があります。

## Xcode を導入する

Apple Pay ケイパビリティをアプリに追加します。Xcode でプロジェクト設定を開き、**Signing & Capabilities (署名およびケイパビリティ)** タブを選択して、**Apple Pay** ケイパビリティを追加します。この段階で開発者アカウントへのログインを要求される場合があります。前の手順で作成した加盟店 ID を選択すると、アプリで Apple Pay を受け付けられるようになります。
![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png)

Xcode で Apple Pay ケイパビリティを有効化する

## Apple Pay がサポートされているかを確認する

アプリ内で Apple Pay を支払いオプションとして表示する前に、ユーザーのデバイスが Apple Pay に対応しているか、およびユーザーのウォレットにカードが追加されているかを判別します。

#### Swift

```swift
import StripeApplePay
import PassKit

class CheckoutViewController: UIViewController, ApplePayContextDelegate {
    let applePayButton: PKPaymentButton = PKPaymentButton(paymentButtonType: .plain, paymentButtonStyle: .black)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Only offer Apple Pay if the customer can pay with it
        applePayButton.isHidden = !StripeAPI.deviceSupportsApplePay()
        applePayButton.addTarget(self, action: #selector(handleApplePayButtonTapped), for: .touchUpInside)
    }

    // ...continued in next step
}
```

## 支払いリクエストを作成する

ユーザーが **Apple Pay** ボタンをタップしたら、[StripeAPI paymentRequestWithMerchantIdentifier:country:currency:](https://stripe.dev/stripe-ios/stripe-payments/Classes/StripeAPI.html#/c:@M@StripeCore@objc\(cs\)StripeAPI\(cm\)paymentRequestWithMerchantIdentifier:country:currency:) を呼び出して、[PKPaymentRequest](https://developer.apple.com/documentation/passkit/pkpaymentrequest) を作成します。

次に、ビジネス名と合計額が表示されるように `PKPaymentRequest` を設定します。請求の詳細または配送先情報などの情報を収集することもできます。

支払いリクエストをカスタマイズする方法のガイダンスについては、[Apple のドキュメント](https://developer.apple.com/design/human-interface-guidelines/apple-pay/overview/checkout-and-payment/#customize-the-payment-sheet)をご覧ください。

#### Swift

```swift
func handleApplePayButtonTapped() {
    let merchantIdentifier = "merchant.com.your_app_name"
    let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD")

    // Configure the line items on the payment request
    paymentRequest.paymentSummaryItems = [
        // The final line should represent your company;
        // it'll be prepended with the word "Pay" (that is, "Pay iHats, Inc $50")
        PKPaymentSummaryItem(label: "iHats, Inc", amount: 50.00),
    ]
    // ...continued in next step
}
```

## 支払い画面を表示する

`PKPaymentRequest` を使用して [STPApplePayContext](https://stripe.dev/stripe-ios/stripe-applepay/Classes/STPApplePayContext.html) インスタンスを作成し、そのインスタンスを使用して Apple Pay 支払い画面を表示します。

#### Swift

```swift
func handleApplePayButtonTapped() {
    // ...continued from previous step

    // Initialize an STPApplePayContext instance
    if let applePayContext = STPApplePayContext(paymentRequest: paymentRequest, delegate: self) {
        // Present Apple Pay payment sheet
        applePayContext.presentApplePay(on: self)
    } else {
        // There is a problem with your Apple Pay configuration
    }
}
```

Apple では、ユーザージェスチャーによって Apple Pay モーダル (ボタンのクリックやフォームの操作など) がトリガーされることが義務付けられています。コードが以下に準拠しているかを確認します。

- ユーザー有効化イベントで支払いシートを直接呼び出します。
- 支払いシートのコードを、非同期コードまたは実行時間の長いコードの前、ユーザージェスチャーイベントハンドラの上部またはその近くに追加します。
- ユーザージェスチャーの後に `confirmPayment` を呼び出すための、妥当な時間制限を設定します。

## Stripe に支払いを送信する

### サーバー側

[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"
```

### クライアント側

#### Payment Intents API

`applePayContext(_:didCreatePaymentMethod:paymentInformation:)` を実装して、上記のエンドポイントから取得したPaymentIntent Client Secretを返すか、リクエストが失敗した場合にエラーをスローします。

Client Secret を返すと、`STPApplePayContext` は支払いを完了し、Apple Pay シートを閉じて、支払いの状態で `applePayContext(_:didCompleteWithStatus:error:)` を呼び出します。このメソッドを実装して、顧客に領収書を表示します。

#### Swift

```swift
extension CheckoutViewController {
    func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod, paymentInformation: PKPayment) async throws -> String {
        let clientSecret = try await ... // Retrieve the PaymentIntent client secret from your backend (see Server-side step above)
        // Return the client secret or throw an error
        return clientSecret
    }

    func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPApplePayContext.PaymentStatus, error: Error?) {
          switch status {
        case .success:
            // Payment succeeded, show a receipt view
            break
        case .error:
            // Payment failed, show the error
            break
        case .userCancellation:
            // User canceled the payment
            break
        @unknown default:
            fatalError()
        }
    }
}
```

最後に、[決済後イベントの処理](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-post-payment)を実行して、顧客に注文確認メールを送信したり、データベースに売上を記録したり、配送ワークフローを開始したりする操作を行います。

#### Payment Intents API (サーバ側での確定)

`applePayContext(_:didCreatePaymentMethod:paymentInformation:)` を実装してサーバーに `paymentMethod.id` を送信し、PaymentIntent を作成して確認します。サーバーから返された PaymentIntent クライアントシークレットを返すか、リクエストが失敗した場合はエラーをスローします。

Client Secret を返すと、`STPApplePayContext` は支払いを完了し、Apple Pay シートを閉じて、支払いの状態で `applePayContext(_:didCompleteWithStatus:error:)` を呼び出します。このメソッドを実装して、顧客に領収書を表示します。

#### Swift

```swift
extension CheckoutViewController {
    func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod, paymentInformation: PKPayment) async throws -> String {
        let clientSecret = try await ... // Call your backend to create and confirm a PaymentIntent and get its client secret
        // Return the client secret or throw an error
        return clientSecret
    }

    func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPApplePayContext.PaymentStatus, error: Error?) {
          switch status {
        case .success:
            // Payment succeeded, show a receipt view
            break
        case .error:
            // Payment failed, show the error
            break
        case .userCancellation:
            // User canceled the payment
            break
        @unknown default:
            fatalError()
        }
    }
}
```

### トラブルシューティング

トークンの作成時に Stripe API のエラーが表示される場合は、お客様の Apple Pay 証明書に問題のあるケースがほとんどです。前述のように、新しい証明書を生成して Stripe にアップロードする必要があります。自身で生成したものではなく、必ずダッシュボードから取得した CSR を使用してください。Xcode は誤って古い証明書をキャッシュに入れることがよくあるため、新しい証明書を生成するだけではなく、新しい Apple 加盟店 ID を作成することもお勧めします。

次のエラーを受信した場合:

> Stripe に Apple 加盟店アカウントを追加していません

アプリが以前の (Stripe 以外の) CSR/証明書を使用して暗号化されたデータを送信している可能性があります。お客様の Apple 加盟店 ID で、Stripe 以外の CSR によって生成された証明書が取り消されていることを確認してください。それでも問題が解決しない場合は、お客様の Apple アカウントの加盟店 ID を削除してから再作成してください。その後、前回使用したものと同じ (Stripe が提供した) CSR から新しい証明書を作成します。この新しい証明書を Stripe に再度アップロードする必要はありません。完了したら、アプリで Apple Pay 証明書をオフにしてからオンに切り替え、正しく更新されていることを確認します。

## App Clips

`StripeApplePay` モジュールは簡略版の Stripe SDK であり、[App Clip](https://developer.apple.com/app-clips/) での使用に合わせて最適化されています。[上記のステップ](https://docs.stripe.com/apple-pay.md?platform=ios#accept)に従い、`StripeApplePay` モジュールを App Clip のターゲットに追加します。

> `StripeApplePay` モジュールは、Swift でのみサポートされています。Objective-C ユーザーは、`STPApplePayContext` を `Stripe` モジュールからインポートする必要があります。

### STPApplePayContext からの移行

`STPApplePayContext` をすでに使用していて簡略版の Apple Pay SDK に切り替える場合は、以下の手順に従います。

1. App Clip ターゲットの依存関係では、`Stripe` モジュールを `StripeApplePay` モジュールに置き換えます。
1. コードでは、`import Stripe` を `import StripeApplePay` に置き換えます。
1. `STPApplePayContextDelegate` の使用は新しい `ApplePayContextDelegate` プロトコルに置き換えます。
1. `applePayContext(_:didCreatePaymentMethod:)` が `StripeAPI.PaymentMethod` を受け入れるように、実装を変更します。
1. `applePayContext(_:didCompleteWith:error:)` の実装を変更して `STPApplePayContext.PaymentStatus` を受け入れるようにします。

### Before

```swift


    func applePayContext(_ context: STPApplePayContext,
      paymentInformation: PKPayment,
        // ...
    }

    func applePayContext(_ context: STPApplePayContext,
      error: Error?) {
        // ...
    }
}
```

### After

```swift
import StripeApplePay
class CheckoutViewController: UIViewController, ApplePayContextDelegate {
    func applePayContext(_ context: STPApplePayContext,didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod,
      paymentInformation: PKPayment
        // ...} async throws -> String {

    func applePayContext(_ context: STPApplePayContext,didCompleteWith status: STPApplePayContext.PaymentStatus,
      error: Error?) {
        // ...
    }
}
```

## 継続課金

iOS 16 以降では、`PKPaymentRequest`で `recurringPaymentRequest` または `automaticReloadPaymentRequest` のプロパティーを設定することで[加盟店トークン](https://developer.apple.com/apple-pay/merchant-tokens/)を導入することができます。

継続支払いでは、保存された決済手段を [off-session transactions](https://docs.stripe.com/apple-pay/apple-pay-recurring.md#set-up-off-session-payments)にのみ使用できます。

#### Swift

```swift
extension CheckoutViewController {
  func handleApplePayButtonTapped() {
    let request = StripeAPI.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD")

    let billing = PKRecurringPaymentSummaryItem(label: "My Subscription", amount: NSDecimalNumber(string: "59.99"))
    billing.startDate = Date()
    billing.endDate = Date().addingTimeInterval(60 * 60 * 24 * 365)
    billing.intervalUnit = .month

    request.recurringPaymentRequest = PKRecurringPaymentRequest(paymentDescription: "Recurring",
                                                                regularBilling: billing,
                                                                managementURL: URL(string: "https://my-backend.example.com/customer-portal")!)
    request.recurringPaymentRequest?.billingAgreement = "You'll be billed $59.99 every month for the next 12 months. To cancel at any time, go to Account and click 'Cancel Membership.'"
    request.paymentSummaryItems = [billing]
  }
}
```

Apple Pay で継続支払いを使用する方法の詳細については、[Apple の PassKit に関するドキュメント](https://developer.apple.com/documentation/passkit/pkpaymentrequest)をご覧ください。

## 注文の追跡

iOS 16 以降で[注文の追跡](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)を導入するには、[applePayContext(context:willCompleteWithResult:handler:)](https://github.com/stripe/stripe-ios/blob/22.8.0/StripeApplePay/StripeApplePay/Source/ApplePayContext/STPApplePayContext.swift#L38) 関数を `ApplePayContextDelegate` に実装します。支払いの完了後、Stripe は iOS が Apple Pay の決済画面を閉じる前に実装を呼び出します。

実装内で次のようにします。

1. サーバーから、完了した注文の注文詳細を取得します。
1. この詳細を指定された [PKPaymentAuthorizationResult](https://developer.apple.com/documentation/passkit/pkpaymentauthorizationresult) に追加します。
1. 指定された完了ハンドラーをメインキューで呼び出します。

注文の追跡の詳細については、[Apple のウォレットでの注文に関するドキュメント](https://developer.apple.com/documentation/walletorders)をご覧ください。

#### Swift

```swift
extension CheckoutViewController {
    func applePayContext(_ context: STPApplePayContext, willCompleteWithResult authorizationResult: PKPaymentAuthorizationResult) async -> PKPaymentAuthorizationResult {
        // Fetch the order details from your service
        do {
          let myOrderDetails = try await MyAPIClient.shared.fetchOrderDetails(orderID: myOrderID)
          authorizationResult.orderDetails = PKPaymentOrderDetails(
            orderTypeIdentifier: myOrderDetails.orderTypeIdentifier, // "com.myapp.order"
            orderIdentifier: myOrderDetails.orderIdentifier, // "ABC123-AAAA-1111"
            webServiceURL: myOrderDetails.webServiceURL, // "https://my-backend.example.com/apple-order-tracking-backend"
            authenticationToken: myOrderDetails.authenticationToken // "abc123"
          )
          // Return your modified PKPaymentAuthorizationResult
          return authorizationResult
        } catch {
          return PKPaymentAuthorizationResult(status: .failure, errors: [error])
        }
    }
}
```


# React Native iOS

> This is a React Native iOS for when platform is react-native. View the full page at https://docs.stripe.com/apple-pay?platform=react-native.

Stripe [React Native SDK](https://github.com/stripe/stripe-react-native) を使用すると Apple Pay と従来のクレジットカード払いの双方を受け付けられます。開始する前に、[Apple 開発者プログラム](https://developer.apple.com/programs/)に登録し、[サーバーとアプリで Stripe を設定](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=react-native#react-native-setup)する必要があります。次の手順は以下のとおりです。

1. [Apple 加盟店 ID を登録する](https://docs.stripe.com/apple-pay.md#merchantid)
1. [新しい Apple Pay 証明書を作成する](https://docs.stripe.com/apple-pay.md#csr)
1. [Xcode を導入する](https://docs.stripe.com/apple-pay.md#xcode-pay)
1. [StripeProvider で Apple 加盟店 ID を設定する](https://docs.stripe.com/apple-pay.md#set-merchantid)
1. [Apple Pay がサポートされているかを確認する](https://docs.stripe.com/apple-pay.md#check-if-apple-pay-supported)
1. [支払い画面を表示する](https://docs.stripe.com/apple-pay.md#present-payment-sheet)
1. [Stripe に支払いを送信する](https://docs.stripe.com/apple-pay.md#handle-payment)

> React Native と Expo を使用している場合、Expo Go は Apple Pay に対応していません。Apple Pay を Expo で使用するには、[開発ビルド](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 加盟店 ID を登録する

Apple Developer Web サイトで [新規 ID を登録](https://developer.apple.com/account/resources/identifiers/add/merchant) して、Apple 加盟店 ID を取得します。

フォームに説明と ID を入力します。説明はお客様の記録用であり、後で変更できます。アプリの名前を ID として使用することをお勧めします (`merchant.com.{{YOUR_APP_NAME}}` など)。

## 新しい Apple Pay 証明書を作成する

支払いデータを暗号化するためのアプリの証明書を作成します。

ダッシュボードの [iOS certificate settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、**新規アプリケーションを追加**をクリックし、表示されるガイドに従います。

証明書署名リクエスト (CSR) ファイルをダウンロードして、Apple Pay の利用を可能にする安全な証明書を Apple から取得します。

1 つの CSR ファイルを使用して証明書を 1 つだけ発行する必要があります。Apple 加盟店 ID を切り替えた場合、ダッシュボードの [iOS Certificate Settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、新しい CSR と証明書を取得する必要があります。

## Xcode を導入する

Apple Pay ケイパビリティをアプリに追加します。Xcode でプロジェクト設定を開き、**Signing & Capabilities (署名およびケイパビリティ)** タブを選択して、**Apple Pay** ケイパビリティを追加します。この段階で開発者アカウントへのログインを要求される場合があります。前の手順で作成した加盟店 ID を選択すると、アプリで Apple Pay を受け付けられるようになります。
![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png)

Xcode で Apple Pay ケイパビリティを有効化する

## StripeProvider で Apple 加盟店 ID を設定する

`StripeProvider` コンポーネントで、登録した Apple 加盟店 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 証明書に問題のあるケースがほとんどです。前述のように、新しい証明書を生成して Stripe にアップロードする必要があります。自身で生成したものではなく、必ずダッシュボードから取得した CSR を使用してください。Xcode は誤って古い証明書をキャッシュに入れることがよくあるため、新しい証明書を生成するだけではなく、新しい Apple 加盟店 ID を作成することもお勧めします。

次のエラーを受信した場合:

> Stripe に Apple 加盟店アカウントを追加していません

アプリが以前の (Stripe 以外の) CSR/証明書を使用して暗号化されたデータを送信している可能性があります。お客様の Apple 加盟店 ID で、Stripe 以外の CSR によって生成された証明書が取り消されていることを確認してください。それでも問題が解決しない場合は、お客様の Apple アカウントの加盟店 ID を削除してから再作成してください。その後、前回使用したものと同じ (Stripe が提供した) CSR から新しい証明書を作成します。この新しい証明書を Stripe に再度アップロードする必要はありません。完了したら、アプリで Apple Pay 証明書をオフにしてからオンに切り替え、正しく更新されていることを確認します。

## 支払い画面を表示する

[`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: 支払い方法を作成する [クライアント側]

サーバーで支払いを確定する場合は、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. サーバーから、完了した注文の注文詳細を取得します。
1. サーバーからの結果を指定して、指定された完了ハンドラーを `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)をご覧ください。


# Web

> This is a Web for when platform is web. View the full page at https://docs.stripe.com/apple-pay?platform=web.

[Checkout](https://docs.stripe.com/payments/checkout.md) または [Elements](https://docs.stripe.com/payments/elements.md) を使用して、ウェブで Apple Pay 決済を受け付けることができます。Checkout で Apple Pay を使用するために追加の設定は不要です。Elements の場合、ウェブサイトに Apple Pay を追加する方法については、[Express Checkout Element](https://docs.stripe.com/elements/express-checkout-element.md) または[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout)ガイドを参照してください。

### ウェブでの導入に関する考慮事項

- **[Elements](https://docs.stripe.com/payments/elements.md) での iframe の使用** : iframe を使用する場合は、そのオリジンがトップレベルのオリジンと一致している必要があります (Safari 17 以降で `allow="payment"` 属性を指定する場合を除く)。プロトコル、ホスト (フルドメイン名)、ポート (指定されている場合) が 2 つのページで同一である場合、そのオリジンは同一です。
- **トップレベルドメインと iframe ドメイン**: トップレベルドメインが iframe のドメインと異なる場合、トップレベルドメインと iframe のソースドメインの両方が、関連アカウントに[登録された支払い方法のドメイン](https://docs.stripe.com/payments/payment-methods/pmd-registration.md)でなければなりません。
- **既存の Stripe.js v2 システム**: できるだけ早急に、Checkout または Elements にアップグレードしてください。
- **[Checkout](https://docs.stripe.com/payments/checkout.md) で [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) を `embedded_page` に設定した場合**: Safari バージョン 17 以降と iOS バージョン 17 以降のみをサポートします。

Web 版 Apple Pay を利用する際は、[Web 版 Apple Pay の利用規約](https://stripe.com/apple-pay/legal)に同意する必要があります。

### Apple Pay にドメインを登録する

Apple Pay を使用するには、Apple Pay ボタンを表示するすべてのウェブドメインを Apple に登録する必要があります。これには、本番環境とテスト環境の最上位のドメイン (**stripe.com** など) とサブドメイン (**shop.stripe.com** など) が含まれます。

> #### サブドメイン
> 
> `www` は、合わせて登録が必要なサブドメイン (**www.stripe.com** など) です。

Stripe は、Apple 加盟店 ID や証明書署名リクエストの作成など、Apple 加盟店の検証を代理で処理します。Apple Pay ドキュメントに記載されている加盟店検証プロセスに従わないでください。代わりに、次の手順を実行します。

1. ドメインを Apple に登録するように Stripe に指示します。これを行うには、ダッシュボードの[支払い方法のドメインページ](https://dashboard.stripe.com/settings/payment_method_domains)を使用するか、「または」以下に示すように、本番環境用のシークレットキーを指定して API を使用します。1 つのアカウントにドメインを複数回登録しないでください。

```curl
curl https://api.stripe.com/v1/payment_method_domains \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "domain_name=example.com"
```

[ダイレクト支払い](https://docs.stripe.com/connect/direct-charges.md)を*Connect* (Connect is Stripe's solution for multi-party businesses, such as marketplace or software platforms, to route payments between sellers, customers, and other recipients)と組み合わせて使用する場合、API を使用して連結されたアカウントごとに、ドメインを設定する必要があります。これは、他の支払いタイプを使用している連結アカウント要件ではありません。

ドメインを登録したら、本番環境用の API キーを使用して、サイトで支払いを作成できます。

## 継続課金

Apple Pay 加盟店トークンを実装すると、継続決済、後払い、自動リロード決済などの加盟店主導型取引 (MIT) を有効にできます。加盟店トークン (MPAN) は、加盟店のビジネスと顧客の Apple Wallet の決済手段を関連付けるため、複数のデバイスで機能し、紛失または盗難したデバイスからその決済手段が削除された場合でも、新しいデバイスで決済情報を有効な状態に保てます。導入の詳細については、[Apple Pay merchant tokens](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=ece) をご覧ください。


## 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 をテストすることはできません。

# Web

> This is a Web for when platform is web. View the full page at https://docs.stripe.com/apple-pay?platform=web.

デバイスとシステムの要件を満たしていない場合、Stripe は支払いオプションに Apple Pay を表示しません。トラブルシューティングには[テストページ](https://docs.stripe.com/testing/wallets.md)をご利用ください。


## See also

- [iOS Integration](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios)
- [Apple Pay on the Web](https://docs.stripe.com/elements/express-checkout-element.md)
- [Apple Pay のベストプラクティス](https://docs.stripe.com/apple-pay/best-practices.md)
