---
title: 決済を確認・完了する
url: ja/amazon-pay-buy-now-checkout/ja-verify-and-complete-checkout.html
---

**[Step 4 of 7]** onCompleteCheckoutイベントハンドラが呼び出されたら、`Finalize Checkout Session` APIを利用します。このAPIは標準的な[Amazon Pay CV2フロー](https://developer.amazon.com/ja/docs/amazon-pay-checkout/verify-and-complete-checkout.html)の`Complete Checkout Session` APIを置き換えるものです。このAPIは重要な情報を検証するのでこのAPIからの応答が成功した場合のみ、決済が成功したとみなします。このステップの最後に購入者にチェックアウト結果を提示することができます。


<!-- <script>
  function keySpecifics(){
    const keyQuery = "?environmentSpecificKeys=";
    const currentSetting = window.location.search?.split("?environmentSpecificKeys=")[1] ?? 'false';
    const newSetting = currentSetting === 'false' ? 'true' : 'false';
    window.location = window.location.origin + window.location.pathname + keyQuery + newSetting // +  window.location.hash (not included as it feels weird to jump down)
  }
</script>
<div style="display:none" class="environmentSpecificKeys">
  <div markdown="span" class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> If your publicKeyId <b>_does not_</b> have an environment prefix (does not begin with 'SANDBOX' or 'LIVE') follow <a href='#' onclick='keySpecifics()' rel='noopener noreferrer'>these instructions</a> instead.</div>
</div>
<div style="display:none" class="notEnvironmentSpecificKeys">
  <div markdown="span" class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> If your publicKeyId has an environment prefix (for example: SANDBOX-AFVX7ULWSGBZ5535PCUQOY7B) follow <a href='#' onclick='keySpecifics()' rel='noopener noreferrer'>these instructions</a> instead.</div>
</div>
 -->

* TOC
{:toc}
{::options toc_levels="3" /}

---

### Finalize Checkout Session

`OnCompleteCheckout` イベントを正常に受信したことを確認するには、[Finalize Checkout Session](./verify-and-complete-checkout.html#finalize-checkout-session---api) を使用します。
リクエストの `chargeAmount` は、注文金額を確認するためのチェックアウトセッションオブジェクト `paymentDetails.chargeAmount` と一致しなければならないです。また、チェックアウトセッションで `totalOrderAmount` と `supplementaryData` が提供されている場合は、それを指定する必要があります。`PayAndShip`のユースケースでは、`shippingAddress`も必須で、Amazonが共有する住所と一致しなければなりません。`billingAddress`にも同じ要件があります。

<div markdown="span" class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> Amazon PayはFinalize Checkout Sessionでチェックアウトを確定するまで、`paymentIntent`を確定しません。24時間以内に確認されなかったチェックアウトセッションはキャンセルされます。オーソリが要求された場合もキャンセルされます。</div>

**成功のレスポンス:**

[Finalize Checkout Session](../amazon-pay-api-v2/checkout-session.html#finalize-checkout-session)はトランザクションが正常に処理された場合、成功レスポンスを返します。チェックアウトセッションの `paymentIntent` に対応するガイダンスを実装してください：

<table width="100%" border="1"> 
    <tbody>
        <tr id='SNR9CAGnO6p'>
            <td id='s:SNR9CAGnO6p;SNR9CAhxnzV' style='vertical-align: top; font-weight: bold; width: 30%;' class='bold'>paymentIntent
                <br /></td>
            <td id='s:SNR9CAGnO6p;SNR9CA8ReW0' style='vertical-align: top; font-weight: bold; width: 70%;' class='bold'>説明
                <br /></td>
        </tr>
        <tr id='SNR9CAHofkb'>
            <td id='s:SNR9CAHofkb;SNR9CAhxnzV' style=''>AuthorizeWithCapture
                <br /></td>
            <td id='s:SNR9CAHofkb;SNR9CA8ReW0' style=''>支払いのオーソリが取得され、売上請求も実施されます。 <br><br>1. <code>ChargeId</code>の保管 - <code>ChargeId</code>は返金実施時の為に必ず保管してください。<br><br> 2. <code>ChargePermissionId</code>の保管 - もし <code>totalOrderAmount</code> を設定していて、売上請求が未済のレコードがある場合は、 <a href="../amazon-pay-checkout/deferred-transactions.md" target="_blank" rel="noopener noreferrer">延期されたトランザクションを管理する</a> を参照してください。また、30日以内であれば、<code>ChargePermissionId</code> を使用して、<a href="../amazon-pay-api-v2/charge-permission.md#get-charge-permission" target="_blank" rel="noopener noreferrer">Get Charge Permission</a>を行い、購入者とトランザクションの情報を取得することもできます。情報を30日を超えて保持するには、データを事業者側で保存する必要があります。
                <br /></td>
        </tr>
        <tr id='SNR9CAGci5Y'>
            <td id='s:SNR9CAGci5Y;SNR9CAhxnzV' style=''>Authorize
                <br /></td>
            <td id='s:SNR9CAGci5Y;SNR9CA8ReW0' style=''>オーソリが取得されます。 <br><br>1. <code>ChargeId</code>の保管 - 後に売上請求するのCharge IDを格納する必要があります。詳細については、<a href="../amazon-pay-checkout/deferred-transactions.md" target="_blank" rel="noopener noreferrer">延期されたトランザクションを管理する</a>を参照してください。<br><br> 2. <code>ChargePermissionId</code>の保管 - もし <code>totalOrderAmount</code> を設定していて、売上請求が未済のレコードがある場合は、 <a href="../amazon-pay-checkout/deferred-transactions.md" target="_blank" rel="noopener noreferrer">延期されたトランザクションを管理する</a> を参照してください。また、30日以内であれば、<code>ChargePermissionId</code> を使用して、<a href="../amazon-pay-api-v2/charge-permission.md#get-charge-permission" target="_blank" rel="noopener noreferrer">Get Charge Permission</a>を行い、購入者とトランザクションの情報を取得することもできます。情報を30日を超えて保持するには、データを事業者側で保存する必要があります。
                <br /></td>
        </tr>
        <tr id='SNR9CA2df1n'>
            <td id='s:SNR9CA2df1n;SNR9CAhxnzV' style=''>Confirm
                <br /></td>
            <td id='s:SNR9CA2df1n;SNR9CA8ReW0' style=''>オーソリが取得されず、売上請求も行なわれません。<br><br>1. <code>ChargePermissionId</code>の保管 - <code>ChargePermissionId</code>を将来行うオーソリ取得、売上請求の為に保管します。詳細については、<a href="../amazon-pay-checkout/deferred-transactions.md" target="_blank" rel="noopener noreferrer">延期されたトランザクションを管理する</a>を参照してください。また、30日以内であれば、<code>ChargePermissionId</code> を使用して、<a href="../amazon-pay-api-v2/charge-permission.md#get-charge-permission" target="_blank" rel="noopener noreferrer">Get Charge Permission</a>を行い、購入者とトランザクションの情報を取得することもできます。情報を30日を超えて保持するには、データを事業者側で保存する必要があります。
                <br /></td>
        </tr>
    </tbody>
</table>


**エラーレスポンス:**

[Finalize Checkout Session](../amazon-pay-api-v2/checkout-session.html#finalize-checkout-session) は失敗したトランザクションに対しては、エラーレスポンスを返します。購入者は決済を途中でキャンセルしたか、有効なお支払い方法を選択し決済を完了できませんでした。この場合は次の手順を実施してください。

1. 購入者を決済の開始時点にリダイレクトします。
2. 「Amazon Payでのお支払いに失敗しました。別のお支払い方法をお試しください。」などのメッセージを表示します。


### Finalize Checkout Session - API <!-- Move this section to the checkout-session.md for API docs -->

`onCompleteCheckout` イベントハンドラが `paymentIntent` を確定するために呼び出された後、チェックアウトセッションを確定します。
リクエストの `chargeAmount` は、注文金額を確認するためにチェックアウトセッションオブジェクト `paymentDetails.chargeAmount` と一致しなければなりません。また、チェックアウトセッションで `totalOrderAmount` と `supplementaryData` が提供されている場合は、それも指定しなければならない。PayAndShip`のユースケースでは、`shippingAddress`も必須で、Amazonが共有する住所と一致しなければなりません。`billingAddress`にも同じ要件があります。

このリクエストは、`canHandlePendingAuthorization`がtrueに設定され、オーソリがまだ保留中の場合、<a href="https://restfulapi.net/http-status-202-accepted/" target="_blank" rel="noopener noreferrer">HTTP 202 ステータスレスポンス</a>を返します。オーソリの結果が確定した場合、このリクエストはオーソリが成功した場合は <a href="https://restfulapi.net/http-status-202-accepted/" target="_blank" rel="noopener noreferrer">HTTP 200 ステータスレスポンスコード</a>を、オーソリに失敗した場合は 4xx/5xx レスポンスを返します。詳しくは<a href="../amazon-pay-checkout/asynchronous-processing.md">非同期処理</a> をご覧ください。

#### Request

<div style="display:none" class="environmentSpecificKeys">
<code style="color:black">
curl "https://pay-api.amazon.com/:version/checkoutSessions/:checkoutSessionId/finalize" \<br />
-X POST<br />
-H "authorization:Px2e5oHhQZ88vVhc0DO%2FsShHj8MDDg%3DEXAMPLESIGNATURE"<br />
-H "x-amz-pay-date:20201012T235046Z"<br />
-d @request_body<br />
</code>
</div>
<div style="display:none" class="notEnvironmentSpecificKeys">
<code style="color:black">
curl "https://pay-api.amazon.com/:environment/:version/checkoutSessions/:checkoutSessionId/finalize" \<br />
-X POST<br />
-H "authorization:Px2e5oHhQZ88vVhc0DO%2FsShHj8MDDg%3DEXAMPLESIGNATURE"<br />
-H "x-amz-pay-date:20201012T235046Z"<br />
-H "x-amz-pay-idempotency-key:AVLo5tI10BHgEk2jEXAMPLEKEY"<br />
-d @request_body<br />
</code>
</div>

#### Request body

```JSON
{
    "shippingAddress": {
        "name": "Susy S",
        "addressLine1": "11 Ditka Ave",
        "addressLine2": "Suite 2500",
        "city": "Chicago",
        "county": null,
        "district": null,
        "stateOrRegion": "IL",
        "postalCode": "60602",
        "countryCode": "US",
        "phoneNumber": "800-000-0000"
    },
    "billingAddress": {
        "name": "Susy S",
        "addressLine1": "11 Ditka Ave",
        "addressLine2": "Suite 2500",
        "city": "Chicago",
        "county": null,
        "district": null,
        "stateOrRegion": "IL",
        "postalCode": "60602",
        "countryCode": "US",
        "phoneNumber": "800-000-0000"
    },
    {
    "chargeAmount": {
        "amount": "14",
        "currencyCode": "USD"
    },
    "totalOrderAmount": {
        "amount": "14",
        "currencyCode": "USD"
    },
    "paymentIntent": "AuthorizeWithCapture",
    "canHandlePendingAuthorization": "false"
}
```



#### Request parameters

<table width="100%" border="1">
    <tbody>
        <tr id="ERL9CAipzsl">
            <td id="s:ERL9CAipzsl;ERL9CAFccoh" style="vertical-align: top; font-weight: bold; width: 30%;" class="bold">名前
                <br></td>
            <td id="s:ERL9CAipzsl;ERL9CAjQdu4" style="vertical-align: top; font-weight: bold; width: 20%;" class="bold">ロケーション
                <br></td>
            <td id="s:ERL9CAipzsl;ERL9CAxmCJ7" style="vertical-align: top; font-weight: bold; width: 50%;" class="bold">説明
                <br></td>
        </tr>
        <tr id="ERL9CA4LMaA">
            <td id="s:ERL9CA4LMaA;ERL9CAFccoh" style="vertical-align: top;">checkoutSessionId<br><b>(必須)</b><br><br>Type: string
                <br></td>
            <td id="s:ERL9CA4LMaA;ERL9CAjQdu4" style="vertical-align: top;">Path parameter
                <br></td>
            <td id="s:ERL9CA4LMaA;ERL9CAxmCJ7" style="vertical-align: top;">Checkout Session識別子
                <br></td>
        </tr>
        <tr id='ERL9CA4LMaA'>
            <td id='s:ERL9CA4LMaA;ERL9CAFccoh' style='vertical-align: top;'>paymentIntent<br><b>(必須)</b><br><br>Type: string
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAjQdu4' style='vertical-align: top;'>Body
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAxmCJ7' style='vertical-align: top;'>購入者への支払いフロー
                <br /></td>
        </tr>
        <tr id="ERL9CAvm2Or">
            <td id="s:ERL9CAvm2Or;ERL9CAFccoh" style="vertical-align: top;">chargeAmount<br><b>(必須)</b><br><br>Type: <a href="../amazon-pay-api-v2/checkout-session.md#type-price" target="_blank" rel="noopener noreferrer">price</a>
                <br></td>
            <td id="s:ERL9CAvm2Or;ERL9CAjQdu4" style="vertical-align: top;">Body
                <br></td>
            <td id="s:ERL9CAvm2Or;ERL9CAxmCJ7" style="vertical-align: top;">決済時に<code>paymentIntent</code>を使用して処理される金額。Checkout Sessionオブジェクトの<code>paymentDetails.chargeAmount</code>と一致する必要があります
                <br></td>
        </tr>
        <tr>
            <td style="vertical-align: top;">totalOrderAmount<br><br>Type: <a href="../amazon-pay-api-v2/checkout-session.md#type-price" target="_blank" rel="noopener noreferrer">price</a>
                <br></td>
            <td style="vertical-align: top;">Body
                <br></td>
            <td style="vertical-align: top;">注文の総額。この項目に値が指定されている場合は、Checkout Sessionオブジェクト<code>paymentDetails.totalOrderAmount</code>と一致する必要があります
                <br></td>
        </tr>
        <tr id='ERL9CA4LMaA'>
            <td id='s:ERL9CA4LMaA;ERL9CAFccoh' style='vertical-align: top;'>canHandlePendingAuthorization<br><br>Type: boolean
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAjQdu4' style='vertical-align: top;'>Body
                <br /></td>
            <td id='s:ERL9CAlQj26;ERL9CAxLjJC' style='vertical-align: top;'>非同期オーソリ処理を行うかどうかのBoolean <br><br>詳細は <a href="../amazon-pay-checkout/ja-asynchronous-processing.md">asynchronous processing</a> をご参照ください
                <br /></td>
        </tr>            
        <tr id='ERL9CA4LMaA'>
            <td id='s:ERL9CA4LMaA;ERL9CAFccoh' style='vertical-align: top;'>shippingAddress<br><b>(必須)</b><br><br>Type: <a href="../amazon-pay-api-v2/checkout-session.md#type-address">address</a>
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAjQdu4' style='vertical-align: top;'>Body
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAxmCJ7' style='vertical-align: top;'>Amazonが検証するための配送先住所
                <br /><br />`PayAndShip`では<b>必須</b> です</td>
        </tr>
        <tr id='ERL9CA4LMaA'>
            <td id='s:ERL9CA4LMaA;ERL9CAFccoh' style='vertical-align: top;'>billingAddress<br><b>(必須)</b><br><br>Type: <a href="../amazon-pay-api-v2/checkout-session.md#type-address">address</a>
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAjQdu4' style='vertical-align: top;'>Body
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAxmCJ7' style='vertical-align: top;'>Amazonが検証するための請求先住所
                <br /><br />`PayOnly`では<b>必須</b> です</td>
        </tr>
        <tr id='ERL9CA4LMaA'>
            <td id='s:ERL9CA4LMaA;ERL9CAFccoh' style='vertical-align: top;'>supplementaryData<br><br>Type: string
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAjQdu4' style='vertical-align: top;'>Body
                <br /></td>
            <td id='s:ERL9CA4LMaA;ERL9CAxmCJ7' style='vertical-align: top;'>オーダーにおける補足データ（通常は利用しません）
                <br /></td>
        </tr>
    </tbody>
</table>


#### Sample Code

<div style="display:none" class="environmentSpecificKeys">
<ul id="profileTabs" class="nav nav-tabs">
  <li class="nav-item"><a class="active nav-link noExtIcon" href="#phptab-completeCheckoutSession" data-toggle="tab">PHP</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#dotnettab-completeCheckoutSession" data-toggle="tab">.NET</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#javatab-completeCheckoutSession" data-toggle="tab">Java</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#nodejstab-completeCheckoutSession" data-toggle="tab">Node.js</a></li>
</ul>
<div class="tab-content">
  <div role="tabpanel" class="tab-pane active" id="phptab-completeCheckoutSession">   
<div markdown="block">
```php
<?php

    include 'vendor/autoload.php';
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2'
    );

    $payload = array(
        'shippingAddress' => array(
            'name' => 'Susi S',
            'addressLine1' => '11 Ditka Ave',
            'addressLine2'=> 'Suite 2500',
            'city'=> 'Chicago',
            'stateOrRegion'=> 'IL',
            'postalCode'=> '60602',
            'countryCode'=> 'US',
            'phoneNumber'=> '800-000-0000'
        ),
        'chargeAmount' => array(
            'amount' => '14.00',
            'currencyCode' => 'USD'
        ),
        'paymentIntent' => 'AuthorizeWithCapture'
    );

    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->finalizeCheckoutSession('bd504926-f659-4ad7-a1a9-9a747aaf5275', $payload);

        if ($result['status'] === 202) {
            // Charge Permission is in AuthorizationInitiated state
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];
            $chargePermissionId = $response['chargePermissionId'];
        }
        else if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargePermissionId = $response['chargePermissionId'];
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }

?>
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="dotnettab-completeCheckoutSession">
<div markdown="block">
```csharp

using Amazon.Pay.API.Types;
using Amazon.Pay.API.WebStore;
using Amazon.Pay.API.WebStore.Types;
using Amazon.Pay.API.WebStore.CheckoutSession;

public class Sample
{
    public WebStoreClient InitiateClient()
    {
        // set up config
        var payConfiguration = new ApiConfiguration
        (
        region: Region.YOUR_REGION_CODE,
        publicKeyId: "YOUR_PUBLIC_KEY_ID",
        privateKey: "PATH_OR_CONTENT_OF_YOUR_PRIVATE_KEY",
        algorithm: AmazonSignatureAlgorithm.V2
        );

        // init API client
        var client = new WebStoreClient(payConfiguration);

        return client;
    }

    public CheckoutSessionResponse FinalizeCheckoutSession(string checkoutSessionId, Address shippingAddress, String paymentIntent)
    {
        // prepare the request
        var request = new FinalizeCheckoutSessionRequest(14.00M, Currency.USD, paymentIntent);
        request.ShippingAddress = address;

        // send the request
        var result = client.FinalizeCheckoutSession(checkoutSessionId, request);

        // check if API call was successful
        if (!result.Success)
        {
            // do something, e.g. throw an error
        }

        return result;
    }

}
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="javatab-completeCheckoutSession">
<div markdown="block">
```Java
import com.amazon.pay.api.AmazonPayResponse;
import com.amazon.pay.api.PayConfiguration;
import com.amazon.pay.api.WebstoreClient;
import com.amazon.pay.api.exceptions.AmazonPayClientException;
import com.amazon.pay.api.types.Region;

import org.json.JSONObject;

public void sample() {
    PayConfiguration payConfiguration = null;
    try {
        payConfiguration = new PayConfiguration()
        .setPublicKeyId("YOUR_PUBLIC_KEY_ID")
        .setRegion(Region.YOUR_REGION_CODE)
        .setPrivateKey("YOUR_PRIVATE_KEY")
        .setAlgorithm("AMZN-PAY-RSASSA-PSS-V2");

        WebstoreClient webstoreClient = new WebstoreClient(payConfiguration);
        AmazonPayResponse response = null;
        String checkoutSessionId = "bd504926-f659-4ad7-a1a9-9a747aaf5275";

        JSONObject payload = new JSONObject();

        JSONObject chargeAmount = new JSONObject();
        chargeAmount.put("amount", "14.00");
        chargeAmount.put("currencyCode", "USD");
        payload.put("chargeAmount", chargeAmount);

        JSONObject shippingAddress = new JSONObject();
        shippingAddress.put("name", "Susy S");
        shippingAddress.put("addressLine1", "11 Ditka Ave");
        shippingAddress.put("addressLine2", "Suite 2500");
        shippingAddress.put("city", "Chicago");
        shippingAddress.put("stateOrRegion", "IL");
        shippingAddress.put("postalCode", "60602");
        shippingAddress.put("countryCode", "US");
        shippingAddress.put("phoneNumber", "800-000-0000");
        payload.put("shippingAddress", shippingAddress);

        payload.put("paymentIntent", "AuthorizeWithCapture");

        response = webstoreClient.finalizeCheckoutSession(checkoutSessionId, payload);
        String chargePermissionId = response.getResponse().getString("chargePermissionId");
    } catch (AmazonPayClientException e) {
        e.printStackTrace();
    }

}
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="nodejstab-completeCheckoutSession">
<div markdown="block">
```JavaScript
const fs = require('fs');
const Client = require('@amazonpay/amazon-pay-api-sdk-nodejs');

const config = {
    publicKeyId: 'YOUR_PUBLIC_KEY_ID',
    privateKey: fs.readFileSync('tst/private.pem'),
    region: 'YOUR_REGION_CODE',
    algorithm: 'AMZN-PAY-RSASSA-PSS-V2'
};

const payload = {
    chargeAmount: {
        amount: "14.00",
        currencyCode: "USD"
    },
    shippingAddress: {
        "name": "Susy S",
        "addressLine1": "11 Ditka Ave",
        "addressLine2": "Suite 2500",
        "city": "Chicago",
        "stateOrRegion": "IL",
        "postalCode": "60602",
        "countryCode": "US",
        "phoneNumber": "800-000-0000"
    },
    paymentIntent: "AuthorizeWithCapture",
};

const testPayClient = new Client.WebStoreClient(config);
const response = testPayClient.finalizeCheckoutSession('bd504926-f659-4ad7-a1a9-9a747aaf5275', payload);

response.then(function (result) {
    console.log(result.data);
}).catch(err => {
    console.log(err);
});
```

</div>
  </div>
</div>

</div>
<div style="display:none" class="notEnvironmentSpecificKeys">
<ul id="profileTabs" class="nav nav-tabs">
  <li class="nav-item"><a class="active nav-link noExtIcon" href="#phptab-completeCheckoutSession-NESK" data-toggle="tab">PHP</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#dotnettab-completeCheckoutSession-NESK" data-toggle="tab">.NET</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#javatab-completeCheckoutSession-NESK" data-toggle="tab">Java</a></li>
  <li class="nav-item"><a class="nav-link noExtIcon" href="#nodejstab-completeCheckoutSession-NESK" data-toggle="tab">Node.js</a></li>
</ul>
<div class="tab-content">
  <div role="tabpanel" class="tab-pane active" id="phptab-completeCheckoutSession-NESK">   
<div markdown="block">
```php
<?php

    include 'vendor/autoload.php';
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2'
    );

    $payload = array(
        'shippingAddress' => array(
            'name' => 'Susi S',
            'addressLine1' => '11 Ditka Ave',
            'addressLine2'=> 'Suite 2500',
            'city'=> 'Chicago',
            'stateOrRegion'=> 'IL',
            'postalCode'=> '60602',
            'countryCode'=> 'US',
            'phoneNumber'=> '800-000-0000'
        ),
        'chargeAmount' => array(
            'amount' => '14.00',
            'currencyCode' => 'USD'
        ),
        'paymentIntent' => 'AuthorizeWithCapture'
    );

    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->finalizeCheckoutSession('bd504926-f659-4ad7-a1a9-9a747aaf5275', $payload);

        if ($result['status'] === 202) {
            // Charge Permission is in AuthorizationInitiated state
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];
            $chargePermissionId = $response['chargePermissionId'];
        }
        else if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargePermissionId = $response['chargePermissionId'];
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }

?>
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="dotnettab-completeCheckoutSession-NESK">
<div markdown="block">
```csharp

using Amazon.Pay.API.Types;
using Amazon.Pay.API.WebStore;
using Amazon.Pay.API.WebStore.Types;
using Amazon.Pay.API.WebStore.CheckoutSession;

public class Sample
{
    public WebStoreClient InitiateClient()
    {
        // set up config
        var payConfiguration = new ApiConfiguration
        (
            region: Region.YOUR_REGION_CODE,
            environment: Environment.Sandbox,
            publicKeyId: "YOUR_PUBLIC_KEY_ID",
            privateKey: "PATH_OR_CONTENT_OF_YOUR_PRIVATE_KEY",
            algorithm: AmazonSignatureAlgorithm.V2
        );

        // init API client
        var client = new WebStoreClient(payConfiguration);

        return client;
    }

    public CheckoutSessionResponse FinalizeCheckoutSession(string checkoutSessionId, Address shippingAddress, String paymentIntent)
    {
        // prepare the request
        var request = new FinalizeCheckoutSessionRequest(14.00M, Currency.USD, paymentIntent);
        request.ShippingAddress = address;

        // send the request
        var result = client.FinalizeCheckoutSession(checkoutSessionId, request);

        // check if API call was successful
        if (!result.Success)
        {
            // do something, e.g. throw an error
        }

        return result;
    }

}
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="javatab-completeCheckoutSession-NESK">
<div markdown="block">
```Java
import com.amazon.pay.api.AmazonPayResponse;
import com.amazon.pay.api.PayConfiguration;
import com.amazon.pay.api.WebstoreClient;
import com.amazon.pay.api.exceptions.AmazonPayClientException;
import com.amazon.pay.api.types.Region;

import org.json.JSONObject;

public void sample() {
    PayConfiguration payConfiguration = null;
    try {
        payConfiguration = new PayConfiguration()
        .setPublicKeyId("YOUR_PUBLIC_KEY_ID")
        .setRegion(Region.YOUR_REGION_CODE)
        .setPrivateKey("YOUR_PRIVATE_KEY")
        .setEnvironment(Environment.SANDBOX)
        .setAlgorithm("AMZN-PAY-RSASSA-PSS-V2");

        WebstoreClient webstoreClient = new WebstoreClient(payConfiguration);
        AmazonPayResponse response = null;
        String checkoutSessionId = "bd504926-f659-4ad7-a1a9-9a747aaf5275";

        JSONObject payload = new JSONObject();

        JSONObject chargeAmount = new JSONObject();
        chargeAmount.put("amount", "14.00");
        chargeAmount.put("currencyCode", "USD");
        payload.put("chargeAmount", chargeAmount);

        JSONObject shippingAddress = new JSONObject();
        shippingAddress.put("name", "Susy S");
        shippingAddress.put("addressLine1", "11 Ditka Ave");
        shippingAddress.put("addressLine2", "Suite 2500");
        shippingAddress.put("city", "Chicago");
        shippingAddress.put("stateOrRegion", "IL");
        shippingAddress.put("postalCode", "60602");
        shippingAddress.put("countryCode", "US");
        shippingAddress.put("phoneNumber", "800-000-0000");
        payload.put("shippingAddress", shippingAddress);

        payload.put("paymentIntent", "AuthorizeWithCapture");

        response = webstoreClient.finalizeCheckoutSession(checkoutSessionId, payload);
        String chargePermissionId = response.getResponse().getString("chargePermissionId");
    } catch (AmazonPayClientException e) {
        e.printStackTrace();
    }

}
```

</div>
  </div>
  <div role="tabpanel" class="tab-pane" id="nodejstab-completeCheckoutSession-NESK">
<div markdown="block">
```JavaScript
const fs = require('fs');
const Client = require('@amazonpay/amazon-pay-api-sdk-nodejs');

const config = {
    publicKeyId: 'YOUR_PUBLIC_KEY_ID',
    privateKey: fs.readFileSync('tst/private.pem'),
    region: 'YOUR_REGION_CODE',
    sandbox: true,
    algorithm: 'AMZN-PAY-RSASSA-PSS-V2'
};

const payload = {
    chargeAmount: {
        amount: "14.00",
        currencyCode: "USD"
    },
    shippingAddress: {
        "name": "Susy S",
        "addressLine1": "11 Ditka Ave",
        "addressLine2": "Suite 2500",
        "city": "Chicago",
        "stateOrRegion": "IL",
        "postalCode": "60602",
        "countryCode": "US",
        "phoneNumber": "800-000-0000"
    },
    paymentIntent: "AuthorizeWithCapture",
};

const testPayClient = new Client.WebStoreClient(config);
const response = testPayClient.finalizeCheckoutSession('bd504926-f659-4ad7-a1a9-9a747aaf5275', payload);

response.then(function (result) {
    console.log(result.data);
}).catch(err => {
    console.log(err);
});
```

</div>
  </div>
</div>

</div>

#### Response

`paymentIntent`が成功した場合、<a href="https://restfulapi.net/http-status-200-ok" target="_blank" rel="noopener noreferrer">HTTP 200 ステータスレスポンスコード</a> を返し、オーソリが保留中の場合は<a href="https://restfulapi.net/http-status-202-accepted/" target="_blank" rel="noopener noreferrer">HTTP 202 ステータスレスポンスコード</a>を返します。


```JSON
{
    "checkoutSessionId": "bd504926-f659-4ad7-a1a9-9a747aaf5275",
    "webCheckoutDetails": null,
    "chargePermissionType": "OneTime",   
    "recurringMetadata": null,
    "productType": null,
    "paymentDetails": null,
    "merchantMetadata": null,
    "supplementaryData":null, // Amazon Pay system data 
    "buyer": null,
    "billingAddress": null,
    "paymentPreferences": [
        null
    ],
    "statusDetails": {
        "state": "Completed",
        "reasonCode": null,
        "reasonDescription": null,
        "lastUpdatedTimestamp": "20191015T204327Z"
    },
    "shippingAddress": null,
    "platformId":null,
    "chargePermissionId": "S01-5105180-3221187",
    "chargeId": "S01-5105180-3221187-C056351",
    "constraints": [
        null
    ],
    "creationTimestamp": "20191015T204313Z",
    "expirationTimestamp": null,
    "storeId": null,
    "deliverySpecifications": null,
    "providerMetadata": null,
    "checkoutButtonText": null,
    "releaseEnvironment": null
}
```

#### Error codes

<table width="100%" border="1">
    <tbody>
        <tr id="RRV9CAAwEhs">
            <td id="s:ERL9CA9q0ob;ERL9CADTh10" style="vertical-align: top; font-weight: bold; width: 30%;" class="bold">HTTPステータスコード
                <br></td>
            <td id="s:ERL9CA9q0ob;ERL9CAq22MQ" style="vertical-align: top; font-weight: bold; width: 20%;" class="bold">理由コード
                <br></td>
            <td id="s:ERL9CA9q0ob;ERL9CAFbHzY" style="vertical-align: top; font-weight: bold; width: 50%;" class="bold">説明
                <br></td>
        </tr>
        <tr>
            <td style="vertical-align: top;"><br>400 BAD_REQUEST
                <br></td>
            <td style="vertical-align: top;"><br>CurrencyMismatch
                <br></td>
            <td style="vertical-align: top;">リクエストで提供された通貨コードが、決済時に設定された通貨と一致しません
                <br></td>
        </tr>
        <tr>
            <td style="vertical-align: top;"><br>400 BAD_REQUEST
                <br></td>
            <td style="vertical-align: top;"><br>TransactionAmountExceeded
                <br></td>
            <td style="vertical-align: top;">Checkout Sessionで許可されている最大請求金額を超えました
                <br></td>
        </tr>
        <tr id="RRV9CApF183">
            <td id="s:RRV9CApF183;RRV9CADEXUO" style="vertical-align: top;"><br>404 NOT_FOUND
                <br></td>
            <td id="s:RRV9CApF183;RRV9CADSdxj" style="vertical-align: top;"><br>ResourceNotFound
                <br></td>
            <td id="s:RRV9CApF183;RRV9CAxD9sC" style="vertical-align: top;">Checkout Sessionは、30日後に完全に削除されます。以降、Checkout Sessionに対してリクエストを行うと、このエラーコードが返されます
                <br></td>
        </tr>
        <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">ChargeAmountMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトの<code>chargeAmount</code>とリクエスト<code>chargeAmount</code>が一致していません
                <br></td>
        </tr>
                <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">TotalOrderAmountMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトの<code>TotalOrderAmount</code>とリクエスト<code>TotalOrderAmount</code>が一致していません
                <br></td>
        </tr>        
        <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">CanHandlePendingAuthorizationMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトの<code>canHandlePendingAuthorization</code>とリクエスト<code>canHandlePendingAuthorization</code>が一致していません
                <br></td>
        </tr>
        <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">PaymentIntentMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトの<code>paymentIntent</code>とリクエスト<code>paymentIntent</code>が一致していません
                <br></td>
        </tr>
        <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">ShippingAddressMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトとリクエスト<code>ShippingAddress</code>が一致していません
                <br></td>
        </tr>
        <tr id="RRV9CAFTKSt">
            <td id="s:RRV9CAFTKSt;RRV9CADEXUO" style="">409 CONFLICT
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CADSdxj" style="">BillingAddressMismatch
                <br></td>
            <td id="s:RRV9CAFTKSt;RRV9CAxD9sC" style="">Checkout Sessionオブジェクトとリクエスト<code>billingAddress</code>が一致していません
                <br></td>
        </tr>
        <tr>
            <td style="vertical-align: top;"><br>422 UNPROCESSABLE_ENTITY
                <br></td>
            <td style="vertical-align: top;"><br>CheckoutSessionCanceled
                <br></td>
            <td style="vertical-align: top;">購入者が取引をキャンセルしたか、支払いが拒否されたため、決済に失敗しました
                <br></td>
        </tr>
        <tr id="RRV9CApBW84">
            <td id="s:RRV9CApBW84;RRV9CADEXUO" style="vertical-align: top;"><br>422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CApBW84;RRV9CADSdxj" style="vertical-align: top;">InvalidCheckoutSessionStatus
                <br></td>
            <td id="s:RRV9CApBW84;RRV9CAxD9sC" style="vertical-align: top;">その処理が許可されていないstateのCheckout Sessionに対して処理を実行しようとしました
                <br></td>
        </tr>
        <tr id="RRV9CApBW84">
            <td id="s:RRV9CApBW84;RRV9CADEXUO" style="vertical-align: top;"><br>422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CApBW84;RRV9CADSdxj" style="vertical-align: top;">InvalidChargeStatus
                <br></td>
            <td id="s:RRV9CApBW84;RRV9CAxD9sC" style="vertical-align: top;">その処理が許可されていないstateのChargeに対して処理を実行しようとしました。または、<code>paymentIntent</code>がAuthorizeWithCaptureで<code>canHandlePendingAuthorization</code>をtrueに設定しているCheckout Sessionに対して、Complete Checkout Sessionを実行しようとしました
                <br></td>
        </tr>
        <tr id="RRV9CARZv8O">
            <td id="s:RRV9CARZv8O;RRV9CADEXUO" style="vertical-align: top;">422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CARZv8O;RRV9CADSdxj" style="vertical-align: top;">HardDeclined
                <br></td>
            <td id="s:RRV9CARZv8O;RRV9CAxD9sC" style="vertical-align: top;">Chargeはhard declinedとなりました。再試行は成功しません。購入者に連絡して、別のお支払い方法を選択してもらいます
                <br></td>
        </tr>
        <tr id="RRV9CADgbCA">
            <td id="s:RRV9CADgbCA;RRV9CADEXUO" style="vertical-align: top;">422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CADgbCA;RRV9CADSdxj" style="vertical-align: top;">PaymentMethodNotAllowed
                <br></td>
            <td id="s:RRV9CADgbCA;RRV9CAxD9sC" style="vertical-align: top;">購入者が選択した支払い方法は、このChargeに対しては許可されていません
                <br></td>
        </tr>
        <tr id="RRV9CAUzZgT">
            <td id="s:RRV9CAUzZgT;RRV9CADEXUO" style="vertical-align: top;">422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CAUzZgT;RRV9CADSdxj" style="vertical-align: top;">AmazonRejected
                <br></td>
            <td id="s:RRV9CAUzZgT;RRV9CAxD9sC" style="vertical-align: top;">ChargeはAmazonによって拒否されました。紐づくCharge Permissionもキャンセルされます
                <br></td>
        </tr>
        <tr id="RRV9CAY9tT2">
            <td id="s:RRV9CAY9tT2;RRV9CADEXUO" style="vertical-align: top;">422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CAY9tT2;RRV9CADSdxj" style="vertical-align: top;">MFANotCompleted
                <br></td>
            <td id="s:RRV9CAY9tT2;RRV9CAxD9sC" style="vertical-align: top;">トランザクションを処理するには、購入者が多要素認証(MFA)を完了する必要があります
                <br></td>
        </tr>
        <tr id="RRV9CAm8slJ">
            <td id="s:RRV9CAm8slJ;RRV9CADEXUO" style="vertical-align: top;">422 UNPROCESSABLE_ENTITY
                <br></td>
            <td id="s:RRV9CAm8slJ;RRV9CADSdxj" style="vertical-align: top;">TransactionTimedOut
                <br></td>
            <td id="s:RRV9CAm8slJ;RRV9CAxD9sC" style="vertical-align: top;"><code>canHandlePendingAuthorization</code>がfalseの場合,Amazon Payがオーソリを取得するのに十分な時間な時間が取れずChargeは拒否されました。購入者に連絡して、別の支払い方法を選択してもらいます。このエラーが頻繁に発生する場合は、<code>canHandlePendingAuthorization</code>をtrueに設定して下さい。もし<code>canHandlePendingAuthorization</code>をtrueにした場合,Amazon Payが注文の有効性を判断できなかったため、このChargeは拒否されました。購入者に連絡して、別の支払い方法を選択してもらいます。詳細については、<a href="https://pay.amazon.com">非同期処理</a>を参照してください
                <br></td>
        </tr>
        <tr id="RRV9CA59kyj">
            <td id="s:RRV9CA59kyj;RRV9CADEXUO" style="vertical-align: top;">500 INTERNAL_SERVER_ERROR
                <br></td>
            <td id="s:RRV9CA59kyj;RRV9CADSdxj" style="vertical-align: top;">ProcessingFailure
                <br></td>
            <td id="s:RRV9CA59kyj;RRV9CAxD9sC" style="vertical-align: top;">内部処理エラーのため、AmazonはChargeを処理できませんでした。 Charge PermissionがChargeable状態の場合にのみChargeを再試行する必要があります
                <br></td>
        </tr>
    </tbody>
</table>


その他エラーは <a href="../amazon-pay-api-v2/error-handling.md" target="_blank" rel="noopener noreferrer">こちら</a>をご参照ください.

<!-- ### 2. Add shipment tracking info

**Note:** This section is optional and only applicable if you ship packages using a <a href="https://eps-eu-external-file-share.s3.eu-central-1.amazonaws.com/Alexa/Delivery+Notifications/amazon-pay-delivery-tracker-supported-carriers-v2.csv" target="_blank" rel="noopener noreferrer">supported carrier</a>.

Send shipment tracking information to Amazon Pay using the Delivery Tracker API. Amazon Pay will notify your buyers on their Alexa device when their package is shipped and when their package is delivered. See <a href="../amazon-pay-checkout/setting-up-delivery-notifications.md" target="_blank" rel="noopener noreferrer">setting up delivery notifications</a> for more info. -->
