# PWI Sample Imp.

Here at the page, we are going to look closer on [Implementation Steps](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/..#implementation-steps) of [PWI](https://docs.iyzico.com/en/payment-methods/paywithiyzico) comprehensively while providing sample requests, responses and best practices from fast, ease and secure implementation point of view.

### Pre-Requirements;

Before proceeding, please ensure that you have the following pre-requisites in place:

* [A sandbox account](https://docs.iyzico.com/en/getting-started/preliminaries/sandbox)
* [Pair of API & Secret keys](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/broken-reference)
* A software tool to manage API calls; [Postman](https://docs.iyzico.com/en/getting-started/preliminaries/postman-collections), Insonmina, Github clients

If so, keep going.

### Overview

Implementation requires two subsequent `POST` requests orchestrate one by one.

In short;

* First, we will illustrate a **PWI-Initialize** `POST` request.
* Then, we will cover up with **PWI-Retrieve** `POST` section.

### Adımlar

1. [PWI-Initialize](#step-1-pwi-initialize)
2. [Token + URL](#step-2-token--url)
3. [Redirection](#step-3-redirection)
4. [PWI-Retrieve](#step-4-pwi-retrieve)
5. [Webhook](#step-5-webhook)

### Step 1 - PWI Initialize

PWI implementation begins with [PWI-Initialize](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-initialize) `POST` request.

This step involves sending a POST request to initialize the PWI payment. The request body contains various parameters such as locale, conversationId, price, basketId, paymentGroup, callbackUrl, currency, paidPrice, enabledInstallments, buyer details, shipping address, billing address, and basket items.

The following object is a sample **PWI-Initialize** request body.

\
**Sample PWI-Initialize Request;**

{% code lineNumbers="true" %}

```json
{
    "locale": "en", //tr
    "conversationId": "conversationID",
    "price": "10.91",
    "basketId": "basketID",
    "paymentGroup": "OTHER",
    "callbackUrl": "YOUR_CALLBACKURL",
    "currency": "TRY",
    "paidPrice": "49.91",
    "enabledInstallments": [
        2,
        3,
        6,
        9,
        12
    ],
    "buyer": {
        "id": "buyerID",
        "name": "buyerName",
        "surname": "buyerSurname",
        "identityNumber": "11111111111",
        "email": "email@email.com",
        "gsmNumber": "+905350000000",
        "registrationAddress": "Burhaniye Mahallesi Atilla Sokak No:7 Üsküdar",
        "city": "Istanbul",
        "country": "Turkey",
        "ip": "85.34.78.112"
    },
    "shippingAddress": {
        "address": "Burhaniye Mahallesi Atilla Sokak No:7 Üsküdar",
        "contactName": "Contact Name",
        "city": "Istanbul",
        "country": "Turkey"
    },
    "billingAddress": {
        "address": "Burhaniye Mahallesi Atilla Sokak No:7 Üsküdar",
        "contactName": "Contact Name",
        "city": "Istanbul",
        "country": "Turkey"
    },
    "basketItems": [
        {
            "id": "ItemID",
            "price": "10.91",
            "name": "product Name",
            "category1": "Category Name",
            "itemType": "PHYSICAL"
        }
    ]
}
```

{% endcode %}

Once you have triggered above request, there are 3(three) scenarios you will monitor mostly.\
Happy path includes a variable called, `payWithIyzicoPageUrl`.

{% code lineNumbers="true" %}

```json
{
    "status": "success",
    "locale": "en", //tr
    "systemTime": 1619779710035,
    "conversationId": "123456789",
    "token": "a641ab63-0b7b-4a50-bb09-6c7325041acd",
    "tokenExpireTime": 1800,
    "payWithIyzicoPageUrl": "https://sandbox-consumer.iyzico.com/checkout?token=a641ab63-0b7b-4a50-bb09-6c7325041acd&lang=tr"
}
```

{% endcode %}

### Step 2 - Token + URL

Hereby, `token` and `payWithIyzicoPageUrl` are essential knots of for the rest of payment journey.&#x20;

In this step, you need to extract the token and payWithIyzicoPageUrl from the response obtained in the previous step. The token should be saved for later validation, and the payWithIyzicoPageUrl is used to redirect the user to the payment page.

* **token;** Its expected that merchants saves `token` parameter to confront and validate payment at the very end of payment journey.
* **payWithIyzicoPageUrl;** where payment page appears briefly. Redirection to `payWithIyzicoPageUrl` provides an interface to accomplish checkouts safely for end-users.

#### An example of payWithIyzicoPageUrl interface on the browser;

<div align="left"><figure><img src="https://3756320043-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBnccQ14a3b6OedaJJFT4%2Fuploads%2FaFJUlTJReLzNBSZT7QAH%2FScreen%20Shot%202021-05-02%20at%2011.41.55%20AM.png?alt=media&#x26;token=7fc23d90-be29-49dc-b7cf-2bab47d1bd76" alt=""><figcaption></figcaption></figure></div>

### Step 3 - Redirection

Redirection phase ties [PWI-Initialize](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-initialize) and [PWI-Retrieve](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-retrieve) steps overall.

Following up end user interact on PWI payment page, iyzico will automatically redirect the page to the address given in the "callbackUrl" parameter. Redirection `POST`  includes;

| Input Name                | Type   | Description                                                                                          |
| ------------------------- | ------ | ---------------------------------------------------------------------------------------------------- |
| **status**                | String | Service response result (success / failure)                                                          |
| **iyziPaymentId**         | String | If verification is successful, iyzico will return a paymentid. It must be set in Auth request        |
| **merchantId**            | String | ID of your merchant identification.                                                                  |
| **paymentConversationId** | Long   | If set, conversation ID to match request and response                                                |
| **token**                 | String | Unique value created for each checkout form request. This token is used to access the payment result |
| **iyziReferenceCode**     | String | A unique reference code for the notification                                                         |
| **iyziEventType**         | String | Shows the request type. Exepcted value is CHECKOUT\_FORM\_AUTH                                       |

{% hint style="info" %}
`mdStatus` parameter will only appear on 3DS operations.

Please check further details around mdStatus [here](https://iyzico-new-documentation.gitbook.io/iyzico-dokuemantasyon/payment-methods/3ds/3ds-implementation#mdstatuses).
{% endhint %}

### Step 4 - PWI Retrieve

**PWI-Retrieve** is the last step of PWI chain.

Basically, we have just accepted a payment on the previous step.\
It is now time to legalize the transaction in this step.\
The following example is a sample **PWI-Retrieve** request body.

**Sample PWI-Retrieve Request;**

{% code lineNumbers="true" %}

```json
{
    "locale": "en", //tr
    "conversationId": "YOUR_CONVERSATION_ID",
    "token": "YOUR_TOKEN"
}
```

{% endcode %}

Once you have triggered above request, there are 2(two) scenarios you will monitor mostly.\
Happy path includes `SUCCESS` parameter in the `paymentStatus` variable.

**Sample PWI-Retrieve Response;**

{% code lineNumbers="true" %}

```json
{
    "status": "success",
    "locale": "en", //tr
    "systemTime": 1,
    "conversationId": "YOUR_CONVERSATION_ID",
    "price": 1,
    "paidPrice": 1,
    "installment": 1,
    "paymentId": "GENERIC_PAYMENT_ID",
    "fraudStatus": 1,
    "merchantCommissionRate": 1,
    "merchantCommissionRateAmount": 1,
    "iyziCommissionRateAmount": 1,
    "iyziCommissionFee": 1,
    "binNumber": "000000",
    "lastFourDigits": "0000",
    "basketId": "basketID",
    "currency": "TRY",
    "itemTransactions": [
        {
            "itemId": "ItemID",
            "paymentTransactionId": "GENERIC_PAYMENT_TRANSACTION_ID",
            "transactionStatus": 2,
            "price": 1,
            "paidPrice": 1,
            "merchantCommissionRate": 1,
            "merchantCommissionRateAmount": 1,
            "iyziCommissionRateAmount": 1,
            "iyziCommissionFee": 1,
            "blockageRate": 1,
            "blockageRateAmountMerchant": 1,
            "blockageRateAmountSubMerchant": 1,
            "blockageResolvedDate": "GENERIC_DATE",
            "subMerchantPrice": 1,
            "subMerchantPayoutRate": 1,
            "subMerchantPayoutAmount": 1,
            "merchantPayoutAmount": 1,
            "convertedPayout": {
                "paidPrice": 1,
                "iyziCommissionRateAmount": 1,
                "iyziCommissionFee": 1,
                "blockageRateAmountMerchant": 1,
                "blockageRateAmountSubMerchant": 1,
                "subMerchantPayoutAmount": 1,
                "merchantPayoutAmount": 1,
                "iyziConversionRate": 1,
                "iyziConversionRateAmount": 1,
                "currency": "TRY"
            }
        }
    ],
    "phase": "AUTH",
    "token": "YOUR_TOKEN",
    "callbackUrl": "YOUR_CALLBACK_URL",
    "paymentStatus": "SUCCESS"
}
```

{% endcode %}

### Step 5 - Webhook

Webhooks are tail subject of our implementation streamline.&#x20;

Receiving real-time payment notifications leverages overall PWI experience while ensuring that the notifications are coming from trusted sources, preventing any potential tampering or unauthorized access to sensitive data.&#x20;

Each payment event triggers webhooks;&#x20;

* In `15` seconds.&#x20;
* Until your server responds with `200`.
* For every `10` minutes.
* Max `3` times.

**Sample PWI Webhook**

| Parametere                | Type   | Description                                                           |
| ------------------------- | ------ | --------------------------------------------------------------------- |
| **iyziEventTime**         | long   | Unix timestamp value of first notification.                           |
| **iyziEventType**         | string | Shows the request type. Values: API\_AUTH, THREE\_DS\_AUTH, BKM\_AUTH |
| **iyziReferenceCode**     | string | A unique reference code for the notification                          |
| **paymentId**             | long   | Unique iyzico reference code of related payment                       |
| **paymentConversationId** | string | Merchant's reference id for the related payment                       |
| **status**                | string | Payment status. Values: SUCCESS, FAILURE                              |

Happy path includes `success` parameter in the `status` variable.

#### Confirmation

To finalize payment operations successfully, correlation of certain variables plays significant role;

* `paymentId`
* `status`
* `price`
* Other [Idempotency](file:///iyzico-dokuemantasyon/getting-started/preliminaries/idempotency) parameters optionally

&#x20;

[PWI-Retrieve](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-retrieve) response and [Webhook](file:///iyzico-dokuemantasyon/advanced/webhook) notification have to authenticate each other.

It is crucial to cross-verify the response received from [PWI-Retrieve](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-retrieve) and the data received in the [Webhook](https://docs.iyzico.com/en/advanced/webhook) notification. Match the paymentId, status, price, and other relevant parameters to ensure the authenticity and correctness of the transaction.

* `paymentId` on [PWI-Retrieve](https://docs.iyzico.com/en/payment-methods/paywithiyzico/pwi-implementation/pwi-retrieve) response should be equal to `paymentId`from Webhook
* Both of the `status` parameters should be `success`
* `price` parameter amounts should be the same
* And lastly, Idempotency parameters should be the same as well.

&#x20;

If so, congratulations! Just finished PWI implementation.

Transaction details could get from merchant panel.

{% hint style="info" %}
Please note that the provided sample requests and responses are for illustration purposes only, and you should adapt them to your specific implementation requirements and API documentation.
{% endhint %}
