# PayPangea Integration Guide

Welcome to the PayPangea integration guide. This document is designed to help web developers integrate PayPangea's payment and authentication services into their applications. By following this guide, you'll be able to add PayPangea buttons to your web pages, allowing users to make payments or log in using PayPangea.


# Getting Started

Before you begin, ensure you have the following:

## A PayPangea account

Sign up for a PayPangea account if you haven't already. This will give you access to the PayPangea dashboard where you can manage your payments, view transaction history, and access your API keys.

## **Familiarity with Web Development**

A basic understanding of HTML, CSS, and JavaScript is necessary to integrate PayPangea into your website. Our integration script is straightforward, but knowing how to customize and troubleshoot your webpage will help you tailor the experience to your needs.

## An API key provided by PayPangea

To authenticate your integration and initiate transactions securely, you will need an API key. You can obtain this key from your PayPangea dashboard. Keep this key confidential and do not share it publicly to ensure your transactions remain secure.

***

Once you have these prerequisites in place, you can proceed with integrating PayPangea into your website using our JavaScript SDK. Follow the integration guide closely, and refer to our comprehensive API documentation for detailed information on request parameters, response objects, and error handling. Our support team is also available to assist you with any questions or issues you may encounter during the integration process.


# Integration Options

PayPangea offers two primary methods for integrating its payment solutions into your application or website: through the PayPangea SDK or directly via the PayPangea API. Each method caters to different needs and technical preferences, providing flexibility in incorporating payment functionalities. Below, we'd like to explore both options to help you decide the best fit for your project.

### Option 1: Integration via PayPangea SDK

The PayPangea SDK is a set of pre-built libraries that simplify integrating PayPangea's payment functionalities into your application. It abstracts the complexity of direct API calls into easy-to-use functions and components, making it ideal for developers looking for a quick and straightforward integration process.

#### Benefits of Using the SDK:

* **Simplified Implementation:** The SDK provides high-level functions to handle payment processes, requiring less code and reducing the chance of errors.
* **Pre-Built UI Components:** Utilize ready-made UI components for payment buttons, login prompts, and more, ensuring a consistent and user-friendly experience.
* **Automatic Updates:** Receive updates and new features automatically, keeping your payment integration up-to-date with the latest advancements and security measures.

### Option 2: Integration via PayPangea API

PayPangea offers direct access to its API for developers requiring more control over their payment integration. This method allows for a more customizable integration, enabling you to design and manage the payment flow exactly as you see fit.

#### Benefits of Using the API:

* **Full Customization:** Direct API integration gives you complete control over the payment process, allowing for a fully customized user experience.
* **Deep Integration:** Integrate payment functionalities more deeply into your application's logic and workflows.
* **Advanced Features:** Access to more advanced and specific features that might not be available through the SDK.


# Introduction

PayPangea is transforming the Web3 development landscape by enabling developers to seamlessly integrate wallet creation into their applications, requiring only an email or phone number from the end user, without any further intervention. This streamlined approach allows for the automatic generation of Web3 wallets, simplifying the user's journey into blockchain-based services. Developers can now offer a frictionless onboarding experience, where users gain access to digital assets and blockchain functionalities instantly, bypassing the complexities traditionally associated with wallet setup and security. PayPangea's innovative platform empowers developers to enhance user engagement and adoption of Web3 technologies, by removing barriers and making digital wallet management as straightforward as entering an email or phone number.


# API Integration

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/6XXAGYPXVdaBWylaqdpU" %}
[Integration steps](/login-with-paypangea/api-integration/integration-steps)
{% endcontent-ref %}


# Integration steps

## **Environment Setup**

Decide whether you will test your integration in a development environment or deploy it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Environments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |


# Request a wallet

<mark style="color:green;">`POST`</mark> `/auth/request-wallet`

This endpoint is designed to initiate the process of creating or retrieving a user's wallet. It requires the user to authenticate and then submit a request with either an email or a phone number. The system will then either create a new wallet if one does not exist for the submitted credentials or return an existing wallet if it is already associated with them.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <API_KEY>` |

**Body**

<table><thead><tr><th width="210">Name</th><th>Type</th><th width="278">Description</th><th>Required</th></tr></thead><tbody><tr><td>email</td><td>string</td><td>email of wallet holder </td><td>OPTIONAL</td></tr><tr><td>phone</td><td>string</td><td>phone of wallet holder </td><td>OPTIONAL</td></tr></tbody></table>

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "status": 200,
  "wallet": <wallet_address>
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "code": 400,
  "message": <error message>
}
```

{% endtab %}
{% endtabs %}


# SDK Integration

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/SMdDimycQD63oOV4EwgP" %}
[Integration Steps](/login-with-paypangea/sdk-integration/integration-steps)
{% endcontent-ref %}

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/MIZ7CfwHwjn1SLuN0H61" %}
[Handling Logins](/login-with-paypangea/sdk-integration/handling-logins)
{% endcontent-ref %}

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/9gO46S4wpqHaeR1rQh2B" %}
[Event Handling](/login-with-paypangea/sdk-integration/event-handling)
{% endcontent-ref %}


# Integration Steps

## Adding PayPangea SDK

First, include the PayPangea SDK in your HTML file's `<head>` section. This is crucial for accessing the PayPangea functions in your application.

```html
<script src="https://sdk.paypangea.com/sdk.js?ver=4"></script>
```

## **Environment Setup**

Decide whether you will be testing your integration in a development environment or deploying it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Evironments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |

## Initializing PayPangea

Once the SDK is loaded, you can initialize PayPangea in your JavaScript code. This step involves creating a new `PayPangea` instance with your API key and specifying the environment.

```javascript
let payPangeaWidget;

document.addEventListener('DOMContentLoaded', function () {
    payPangeaWidget = new PayPangea({
        apiKey: 'YOUR_API_KEY_HERE',
        environment: 'ENVIRONMENT',
    });
});
```

Replace `'YOUR_API_KEY_HERE'` with your actual PayPangea API key.

Replace `'ENVIRONMENT'` with the environment you want to target.

## **Server Configuration**

If you plan to use webhooks or process transactions server-side, ensure your server is configured to receive HTTPS POST requests. This is crucial for handling callbacks and transaction notifications securely.


# Handling Logins

For handling logins with PayPangea, add a login button and set up an event listener for click events.

```html
<button id="loginbtn" class="buybtn">Login with PayPangea</button>
```

Then, add JavaScript to handle the button click and invoke the showLogin method :

```javascript
var loginBtn = document.getElementById('loginbtn');

loginBtn.addEventListener('click', function() {
    payPangeaWidget.showLogin({});
});
```


# Event Handling

PayPangea SDK provides various events that you can listen to, such as `success`, `error`, `cancel`, and `update`. Here's how to log these events:

```javascript
const events = ['success', 'error', 'cancel', 'update'];

events.forEach(event => {
    payPangeaWidget.on(event, (data) => {
        console.log(`Event '${event}' received from PayPangea`, data);
    });
});
```


# API Integration

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/6XXAGYPXVdaBWylaqdpU" %}
[Integration steps](/login-with-paypangea/api-integration/integration-steps)
{% endcontent-ref %}


# Integration steps

## **Environment Setup**

Decide whether you will test your integration in a development environment or deploy it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Environments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |


# Show login page

#### Using an Iframe

To seamlessly integrate PayPangea's authentication process within your application, you mustp use an iframe. This method provides a cohesive user experience, keeping the user within your application environment throughout the payment process.

Steps:

* **Embed the Iframe**: Insert an iframe into your HTML, setting its `src` attribute to `https://paypangea.com/request/auth/?walletconnect=${showwalletconnect}`, where `${showwalletconnect}` is is either true or false depending on the fact if you want to show wallet connect button or not.

```html
<iframe src="https://paypangea.com/request/auth/?walletconnect=${showwalletconnect}" width="600" height="400"></iframe>
```

* **Listen for Iframe Events**: PayPangea's iframe integration emits several events that you can listen to for managing the payment flow:
  * `PAYPANGEA_WIDGET_CLOSE`: Triggered when the payment widget is closed.
  * `PAYPANGEA_WIDGET_OPEN`: Triggered when the payment widget is opened.
  * `PAYPANGEA_WIDGET_CLOSE_REQUEST`: Emitted when a request to close the widget is made. This is crucial for detecting the end of a payment process.
  * `PAYPANGEA_WIDGET_INITIALISED`: Indicates that the widget has been initialized and is ready to use.
* **Handling Login outcome:** Monitor the `PAYPANGEA_WIDGET_CLOSE_REQUEST` event for `event.data.outcome.code = 200` to confirm a successful login.

```javascript
window.addEventListener('message', (event) => {
    if (event.data.type === 'PAYPANGEA_WIDGET_CLOSE_REQUEST' && event.data.outcome.code === 200) {
        // Handle successful payment
    }
});
```

Response object

<table><thead><tr><th width="210">Name</th><th>Type</th><th width="278">Description</th></tr></thead><tbody><tr><td>code</td><td>int</td><td>200 for succesfull login</td></tr><tr><td>message</td><td>string</td><td>OK for succesfull login, otherwise reason why it was not succesfull</td></tr><tr><td>wallet</td><td>string</td><td>WEB3 wallet address of user</td></tr><tr><td>token</td><td>string</td><td>A token to verify login on your backend</td></tr></tbody></table>


# Server-side verification


# Integration steps

## **Environment Setup**

Decide whether you will test your integration in a development environment or deploy it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Environments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |


# Request authentication

<mark style="color:green;">`POST`</mark> `/auth/address-check`

This endpoint is designed to be executed on the server-side as part of our secure authentication process. It validates the integrity and authenticity of a wallet address using a token received during the frontend login procedure. This verification step is crucial for ensuring that the wallet address in question is legitimately associated with the current user session, enhancing the overall security of our system.

#### Request format

To initiate the verification process, a POST request should be sent to this endpoint with a JSON payload containing two key pieces of information: the `wallet` address to be verified and the `token` received from the frontend after the initial login phase.

**Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

<table><thead><tr><th width="210">Name</th><th>Type</th><th width="278">Description</th><th>Required</th></tr></thead><tbody><tr><td>wallet</td><td>string</td><td>requested amount </td><td>YES</td></tr><tr><td>token</td><td>string</td><td>token for verification</td><td>YES</td></tr></tbody></table>

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "status": 200,
  "valid": <true/false>
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "code": 400,
  "message": <error message>
}
```

{% endtab %}
{% endtabs %}

Once you obtain the token, follow the instructions on this page:


# SDK Integration

{% content-ref url="/spaces/O5RUY6X5HKbSZDKZGgVl/pages/t3UXFp4IOvtElCQj3Kc4" %}
[Integration Steps](/crypto-payments/sdk-integration/integration-steps)
{% endcontent-ref %}

{% content-ref url="/pages/dfWA7iMGX1ee2lfSsV3v" %}
[Handling Payments](/crypto-payments/sdk-integration/handling-payments)
{% endcontent-ref %}

{% content-ref url="/pages/zPkLm36Jgkfz1hvn6qXA" %}
[Event Handling](/crypto-payments/sdk-integration/event-handling)
{% endcontent-ref %}


# Integration Steps

## Adding PayPangea SDK

First, include the PayPangea SDK in your HTML file's `<head>` section. This is crucial for accessing the PayPangea functions in your application.

```html
<script src="https://sdk.paypangea.com/sdk.js?ver=4"></script>
```

## **Environment Setup**

Decide whether you will be testing your integration in a development environment or deploying it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Evironments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |

## Initializing PayPangea

Once the SDK is loaded, you can initialize PayPangea in your JavaScript code. This step involves creating a new `PayPangea` instance with your API key and specifying the environment.

```javascript
let payPangeaWidget;

document.addEventListener('DOMContentLoaded', function () {
    payPangeaWidget = new PayPangea({
        apiKey: 'YOUR_API_KEY_HERE',
        environment: 'ENVIRONMENT',
    });
});
```

Replace `'YOUR_API_KEY_HERE'` with your actual PayPangea API key.

Replace `'ENVIRONMENT'` with the environment you want to target.

## **Server Configuration**

If you plan to use webhooks or process transactions server-side, ensure your server is configured to receive HTTPS POST requests. This is crucial for handling callbacks and transaction notifications securely.


# Handling Payments

To initiate a payment with PayPangea, you can set up a button on your webpage. When this button is clicked, it will trigger the `initPayment` method, which is responsible for opening the PayPangea payment interface with the parameters you specify. Here's how you can do it:

```html
<button id="buybtn" class="buybtn">Buy with PayPangea</button>
```

Then, add JavaScript to handle the button click and invoke the `initPayment` method with all available options:

```javascript
var buyBtn = document.getElementById('buybtn');

buyBtn.addEventListener('click', function() {
    payPangeaWidget.initPayment({
        amount: 'AMOUNT', // The amount to be paid
        token: 'TOKEN_NAME', // The name of the token to be used for payment
        currency: 'CURRENCY', // The fiat currency equivalent if applicable
        tokenaddress: 'ACCEPTED TOKEN ADDRESS', // The blockchain address for the token
        chain: 'NAME OF CHAIN', // The blockchain network to use (e.g., Ethereum, BSC)
        title: 'TRANSACTION TITLE', // A title for the transaction
        text: 'DESCRIPTION TEXT', // A description or additional text for the transaction
        successurl: 'SUCCESS_REDIRECT_URL', // URL to redirect to on successful payment
        failurl: 'FAIL_REDIRECT_URL', // URL to redirect to on failed payment
        webhookurl: 'YOUR_WEBHOOK_URL' // Your server endpoint to receive callbacks
    });
});
```

**Options Explained:**

* **amount**: The total payment amount, formatted as a string.
* **token**: Specifies the cryptocurrency token to be used for the payment.
* **currency**: The fiat currency equivalent, useful for displaying to users.
* **tokenaddress**: The address for the accepted token, necessary for blockchain transactions.
* **chain**: Identifies the blockchain network (e.g., Ethereum, Binance Smart Chain).
* **title**: A brief title for the payment, visible to the user.
* **text**: Additional description or information about the payment.
* **successurl**: URL to which the user will be redirected after a successful payment.
* **failurl**: URL to which the user will be redirected after a failed payment.
* **webhookurl**: Endpoint URL for your server to receive transaction updates via webhook.

These options allow for a highly customizable payment process, ensuring that you can tailor the experience to match your application's requirements and provide your users with a seamless payment experience.


# Event Handling

PayPangea SDK provides various events that you can listen to, such as `success`, `error`, `cancel`, and `update`. Here's how to log these events:

```javascript
const events = ['success', 'error', 'cancel', 'update'];

events.forEach(event => {
    payPangeaWidget.on(event, (data) => {
        console.log(`Event '${event}' received from PayPangea`, data);
    });
});
```


# API integration

{% content-ref url="/pages/OKzg7Jse3z8deH3JbWaX" %}
[Integration steps](/crypto-payments/api-integration/integration-steps)
{% endcontent-ref %}

{% content-ref url="/pages/C2M7P8qI2LmjsFqDJbgG" %}
[Authentication](/crypto-payments/api-integration/authentication)
{% endcontent-ref %}

{% content-ref url="/pages/iPM57GYIgheNyWzFx0oS" %}
[Request payment based on crypto](/crypto-payments/api-integration/request-payment-based-on-crypto)
{% endcontent-ref %}

{% content-ref url="/pages/IlaZMj10ivNYqKtiC4MR" %}
[Request payment based on fiat](/crypto-payments/api-integration/request-payment-based-on-fiat)
{% endcontent-ref %}

{% content-ref url="/pages/GXJGW0ZE6I3l0cv4BziQ" %}
[Collecting Payments](/crypto-payments/api-integration/collecting-payments)
{% endcontent-ref %}


# Integration steps

## **Environment Setup**

Decide whether you will test your integration in a development environment or deploy it directly to production. PayPangea supports both environments, allowing you to test your integration thoroughly before going live.

#### Environments

| Value      | Descripton                         |
| ---------- | ---------------------------------- |
| STAGING    | `Staging environment of PayPangea` |
| PRODUCTION | `Live environment of PayPangea`    |


# Authentication

Authenticating your API requests is essential to ensure secure communication between your application and PayPangea's services. Each request must include an Authorization header, using a bearer token format, to be properly authorized.

### Making Authenticated API Requests

To authenticate your API requests to PayPangea, you will include your `API_KEY` in the Authorization header as a Bearer token. Here is how you can structure your request:

#### Example API Request

This example demonstrates making a POST request to the PayPangea API to initiate a fiat payment request. Ensure you replace `API_KEY` with the actual API key obtained from PayPangea.

```http
POST https://api.paypangea.com/v1/pay/{endpoint}
Content-Type: application/json
Authorization: Bearer API_KEY
```

#### Detailed Steps

1. **Prepare the API request**: Compose your HTTP request to target the specific PayPangea API endpoint you wish to interact with. In this case, we're using `/v1/pay/request-pay-sdk-fiat`.
2. **Include the API Key**: Replace `API_KEY` in the Authorization header with your actual PayPangea API key.
3. **Set the Content-Type**: Ensure the `Content-Type` header is set to `application/json` to indicate the format of the request body.
4. **Send the request**: Use your preferred HTTP client or tool to send the request to PayPangea's API server.

### Handling API Responses

The PayPangea API will respond with various HTTP status codes to indicate the success or failure of your request. A successful request typically returns a `200 OK` status code, along with any requested data in the response body. It's important to handle different responses and status codes appropriately in your application.

### Security Best Practices

* **Secure Your API Key**: Treat your `API_KEY` as sensitive information. Do not hard-code it in your application's source code. Instead, use environment variables or secure secrets management tools.
* **Use HTTPS**: Ensure all API requests are made over HTTPS to protect the data in transit.
* **Monitor and Rotate Keys**: Regularly monitor the usage of your API key and rotate it periodically to maintain security.


# Request payment based on crypto

<mark style="color:green;">`POST`</mark> `/pay/request-pay-sdk`

This endpoint is designed to initiate the payment request process within PayPangea's ecosystem. By making a POST request to this endpoint, developers can obtain the unique token necessary to proceed with a payment operation. This token is then used to authenticate and facilitate payment transactions through an iframe or a separate webpage, ensuring a seamless and secure payment flow. This endpoint serves as the first step in integrating PayPangea's payment functionality into your application, enabling you to prepare for user-initiated transactions with the required authentication token.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <API_KEY>` |

**Body**

<table><thead><tr><th width="210">Name</th><th>Type</th><th width="278">Description</th><th>Required</th></tr></thead><tbody><tr><td>amount</td><td>string</td><td>requested amount </td><td>YES</td></tr><tr><td>token</td><td>string</td><td>Name of the crypto token you want to be paid in</td><td>YES</td></tr><tr><td>tokenaddress</td><td>string</td><td>Address of the crypto token you want to be paid in (0x00 if native token of the chain)</td><td>YES</td></tr><tr><td>chain</td><td>string</td><td>Name of the chain that will be used for transaction</td><td>YES</td></tr><tr><td>title</td><td>string</td><td>Name of the request to be shown to user</td><td>OPTIONAL</td></tr><tr><td>text</td><td>string</td><td>Description of the request</td><td>OPTIONAL</td></tr><tr><td>successredirectURL</td><td>string</td><td>Redirection URL if payemnt was success</td><td>OPTIONAL</td></tr><tr><td>failredirectURL</td><td>string</td><td>Redirection URL if payment failed</td><td>OPTIONAL</td></tr><tr><td>webhookURL</td><td>string</td><td>Webhook URL for notifications</td><td>OPTIONAL</td></tr><tr><td>merchantid</td><td>string</td><td>Uniques ID of payment request set my merchant</td><td>OPTIONAL</td></tr></tbody></table>

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "status": 1,
  "tkn": <token>
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "code": 400,
  "message": <error message>
}
```

{% endtab %}
{% endtabs %}

Once you obtain the token, follow the instructions on this page:

{% content-ref url="/pages/GXJGW0ZE6I3l0cv4BziQ" %}
[Collecting Payments](/crypto-payments/api-integration/collecting-payments)
{% endcontent-ref %}


# Request payment based on fiat

<mark style="color:green;">`POST`</mark> `/pay/request-pay-sdk-fiat`

This endpoint is designed to initiate the payment request process within PayPangea's ecosystem. By making a POST request to this endpoint, developers can obtain the unique token necessary to proceed with a payment operation. This token is then used to authenticate and facilitate payment transactions through an iframe or a separate webpage, ensuring a seamless and secure payment flow.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <API_KEY>` |

**Body**

<table><thead><tr><th width="210">Name</th><th>Type</th><th width="278">Description</th><th>Required</th></tr></thead><tbody><tr><td>amount</td><td>string</td><td>requested amount in currency</td><td>YES</td></tr><tr><td>token</td><td>string</td><td>Name of the crypto token you want to be paid in</td><td>YES</td></tr><tr><td>currency</td><td>string</td><td>3 letter fiat currency symbol (USD, EUR, INR, ...)</td><td>YES</td></tr><tr><td>chain</td><td>string</td><td>Name of the chain that will be used for transaction</td><td>YES</td></tr><tr><td>title</td><td>string</td><td>Name of the request to be shown to user</td><td>OPTIONAL</td></tr><tr><td>text</td><td>string</td><td>Description of the request</td><td>OPTIONAL</td></tr><tr><td>successredirectURL</td><td>string</td><td>Redirection URL if payemnt was success</td><td>OPTIONAL</td></tr><tr><td>failredirectURL</td><td>string</td><td>Redirection URL if payment failed</td><td>OPTIONAL</td></tr><tr><td>webhookURL</td><td>string</td><td>Webhook URL for notifications</td><td>OPTIONAL</td></tr><tr><td>merchantid</td><td>string</td><td>Uniques ID of payment request set my merchant</td><td>OPTIONAL</td></tr></tbody></table>

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "status": 1,
  "tkn": <token>
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "code": 400,
  "message": <error message>
}
```

{% endtab %}
{% endtabs %}

Once you obtain the token, follow the instructions on this page:

{% content-ref url="/pages/GXJGW0ZE6I3l0cv4BziQ" %}
[Collecting Payments](/crypto-payments/api-integration/collecting-payments)
{% endcontent-ref %}


# Collecting Payments

Once you have obtained a payment token through the API endpoint, you can initiate the payment process on your platform. This guide will walk you through the steps to collect payments using the token, showcasing both iframe and standalone page approaches.

### Integration Methods

#### Using an Iframe

To integrate PayPangea's payment process within your application seamlessly, you can use an iframe. This method provides a cohesive user experience, keeping the user within your application environment throughout the payment process.

Steps:

* **Embed the Iframe**: Insert an iframe into your HTML, setting its `src` attribute to `https://paypangea.com/request/paysdk/?tkn=${TOKEN}`, where `${TOKEN}` is the payment token you obtained from the API.

```html
<iframe src="https://paypangea.com/request/paysdk/?tkn=${TOKEN}" width="600" height="400"></iframe>
```

* **Listen for Iframe Events**: PayPangea's iframe integration emits several events that you can listen to for managing the payment flow:
  * `PAYPANGEA_WIDGET_CLOSE`: Triggered when the payment widget is closed.
  * `PAYPANGEA_WIDGET_OPEN`: Triggered when the payment widget is opened.
  * `PAYPANGEA_WIDGET_CLOSE_REQUEST`: Emitted when a request to close the widget is made. This is crucial for detecting the end of a payment process.
  * `PAYPANGEA_WIDGET_INITIALISED`: Indicates that the widget has been initialized and is ready to use.
* **Handling Payment Confirmation**: Monitor the `PAYPANGEA_WIDGET_CLOSE_REQUEST` event for `event.data.outcome = 'SUCCESS'` to confirm a successful payment.

```javascript
window.addEventListener('message', (event) => {
    if (event.data.type === 'PAYPANGEA_WIDGET_CLOSE_REQUEST' && event.data.outcome === 'SUCCESS') {
        // Handle successful payment
    }
});
```

#### Standalone Page

Alternatively, you can redirect users to a standalone payment page hosted by PayPangea. This method is straightforward and does not require embedding within your site.

Steps:

* **Redirect to PayPangea**: Redirect users to `https://paypangea.com?tkn=${TOKEN}` for payment. Ensure the user's browser navigates to this URL, where `${TOKEN}` is your obtained payment token.
* **Set a Redirect URL** (Optional): If you prefer to redirect users back to your site upon completion, specify a redirect URL during the token generation step in the API. PayPangea will redirect users to this URL after the payment process, allowing you to handle post-payment actions on your site.


# Webhooks

Integrating webhooks into your PayPangea payment flow allows your application to react in real-time to events such as payment confirmations. This section details how to set up and utilize webhooks for receiving transaction status updates.

#### **Handling Webhook Notifications**

When a relevant event occurs, PayPangea will send a POST request to your webhook endpoint with a JSON payload containing details about the event. For transaction events, the payload will look like this:

```json
{
  "tkn": "unique_transaction_identifier",
  "merchantid": "your_merchant_id",
  "status": "OK" // or "FAIL"
}
```

* `tkn`: This is the transaction's unique identifier.
* `merchantid`: Your unique merchant ID that yoou send when initiated the payment.
* `status`: Indicates the transaction's status, which can be "OK" for successful transactions or "FAIL" for unsuccessful ones.

#### **Receiving and Processing Webhook Data**

On your server, you'll need to set up a route that matches your configured endpoint URL to handle incoming POST requests. Here's an example of how you might process the received webhook data:

```
app.post('/your-webhook-endpoint', async (req, res) => {
  const { tkn, merchantid, status } = req.body;

  if(status === 'OK') {
    // Handle successful transaction
    // Update your database, send confirmation emails, etc.
  } else {
    // Handle failed transaction
    // Log the error, inform the customer, etc.
  }

  res.status(200).send('Webhook received');
});
```

**Best Practices**

* **Validation:** Always validate the received data to ensure it matches the expected format and comes from PayPangea.
* **Security:** Use HTTPS for your endpoint to ensure encrypted communication. Additionally, implement measures to verify the authenticity of the incoming requests.
* **Error Handling:** Implement robust error handling to gracefully manage failures or unexpected data in webhook notifications.

#### **Conclusion**

Webhooks are a powerful tool for automating real-time reactions to payment events in your application. By following the steps outlined above, you can seamlessly integrate PayPangea webhooks into your payment flow, enhancing the reliability and user experience of your service.


# Troubleshooting

If you encounter issues during integration, ensure that:

* The SDK script is correctly loaded in your HTML.
* Your API key is correct and has the necessary permissions.
* Event listeners are correctly set up for buttons.


# FAQ

#### **Q: Can I use PayPangea for any cryptocurrency?**

A: PayPangea supports a wide range of cryptocurrencies. Please refer to the PayPangea documentation for a list of supported tokens.

**Q: Is PayPangea available in all countries?**

A: There may be restrictions based on your location. Check the PayPangea website or contact their support for more information.


