# In-App Purchase

### **WTN IAP Plugin for WebtoNative**

The **WTN IAP Plugin** is a sub-plugin for WebtoNative that enables easy handling of iOS and Android in-app purchases (IAP). It provides a mechanism to verify purchases with the App Store and Google Play Store and allows developers to consume the verification result via a custom callback function.

***

### **Key Features**

* **In-App Purchase (IAP) Button**: Easily integrate IAP functionality into your WordPress site using a shortcode.
* **Platform Detection**: Automatically detects whether the user is on iOS or Android and processes the purchase accordingly.
* **Server-Side Verification**: Verifies the purchase receipt with the respective store (App Store or Google Play).
* **Callback Integration**: Enables developers to handle the verification result with a custom PHP callback function.

***

### **Configuration**

1. Navigate to **Settings > WTN IAP (In-App Purchase)** in your WordPress admin dashboard.

<figure><img src="/files/hnGF0bblX1kHhG4gs6gX" alt="" width="159"><figcaption></figcaption></figure>

2. Configure the following options:

<figure><img src="/files/0STM5DWngHa1GtqxmuTo" alt=""><figcaption></figcaption></figure>

* **App Store Secret Key**:
  * Enter the shared secret from your App Store Connect account. This is required for verifying iOS purchases.
* **Callback Function Name**:
  * Specify the name of the PHP function that will handle the verification results.

***

### **Usage**

**Shortcode**

Use the <mark style="color:green;">**`[wtn_iap]`**</mark> shortcode to add an IAP button to your pages or posts.

**Attributes**

| Attribute                                          | Description                                                            | Default Value |
| -------------------------------------------------- | ---------------------------------------------------------------------- | ------------- |
| <mark style="color:green;">`google_play_id`</mark> | The product ID of the in-app purchase on Google Play.                  | `''`          |
| <mark style="color:green;">`app_store_id`</mark>   | The product ID of the in-app purchase on the App Store.                | `''`          |
| <mark style="color:green;">`product_type`</mark>   | The type of product (INAPP for consumable or `SUBS` for subscription). | INAPP         |
| <mark style="color:green;">`is_consumable`</mark>  | Whether the product is consumable (`true` or `false`).                 | `false`       |

**Example**

```html
[wtn_iap google_play_id="com.example.app.product" app_store_id="example_product" product_type="INAPP" is_consumable="true"]
```

***

### **How It Works**

1. **IAP Initialization**:
   * The user clicks the IAP button.
   * The platform (Android or iOS) is detected using the `window.WTN` object.
   * The purchase process is initiated using `WTN.inAppPurchase`.
2. **Purchase Handling**:
   * After the user completes the purchase, a receipt is generated.
   * The receipt is sent to the WordPress backend for server-side verification.
3. **Server-Side Verification**:
   * The plugin verifies the receipt with the respective store's API.
   * A success or failure message is returned based on the verification result.
4. **Callback Execution**:
   * If a custom callback function is configured, it is invoked with the platform and verification data.

***

### **Server-Side Callback Integration**

Developers can consume the IAP verification result by implementing a custom PHP callback function.

**Callback Function Requirements**

* **Function Name**: The function's name must match the one configured in the plugin settings.
* **Parameters**:
  * `$platform`: The platform of the purchase (`ios` or `android`).
  * `$receipt_data`: An array containing:
    * `receipt`: The raw receipt data.
    * `verification_result`: The verification result returned by the respective store's API.

**Example Callback Function for Verification**

Users must define a callback function in their theme’s <mark style="color:green;">**`functions.php`**</mark> or a custom plugin. This function will process the verification result and take appropriate actions, such as granting access to content or updating the user’s status.

```php
function my_custom_callback($platform, $receipt_data) {
    // Log the platform and data for debugging
    error_log("Platform: $platform");
    error_log("Verification Data: " . print_r($receipt_data, true));

    // Process the verification result
    $receipt = $receipt_data['receipt'];
    $verification_result = $receipt_data['verification_result'];

    if ($verification_result['success']) {
        // Example: Grant access to premium content
        $user_id = get_current_user_id();
        update_user_meta($user_id, 'premium_access', true);
        error_log("User ID $user_id granted premium access.");
    } else {
        error_log("Verification failed: " . $verification_result['message']);
    }
}
add_action('simple_iap_callback', 'my_custom_callback');
```

***

### **Frontend Integration**

**JavaScript Integration**

The plugin includes a JavaScript file (`wtn-iap.js`) that handles the IAP process on the client side.

1. **IAP Button**:
   * When the button is clicked, the `WTN.inAppPurchase` a method is invoked with the product details.
2. **Purchase Callback**:
   * The purchase callback (`paymentCallback`) processes the response and sends the receipt to the server via an AJAX request.
3. **Server Response Handling**:
   * The front end displays appropriate success or error messages based on the server's response.

**Example Workflow**

1. The user clicks the "Buy Now" button.
2. The IAP process starts, and the receipt is obtained.
3. The receipt is sent to the WordPress backend for verification.
4. A success or error message is displayed based on the verification result.

***

### **Error Handling**

**Frontend Errors**

* **Payment Failure**: Alerts the user if the purchase fails.
* **Invalid Response**: Logs and displays an error message if the server returns an invalid response.

**Backend Errors**

* **Missing App Store Secret**: Returns an error if the secret key is not configured.
* **Invalid Receipt**: Returns an error if the receipt verification fails.

### For more reference

{% embed url="<https://docs.webtonative.com/plugin/in-app-purchase-ios-setup>" %}
In App Purchase - iOS Setup
{% endembed %}

{% embed url="<https://docs.webtonative.com/plugin/in-app-purchase-android-setup>" %}
In App Purchase - Android Setup
{% endembed %}

{% embed url="<https://docs.webtonative.com/javascript-apis/in-app-purchase-ios-integration>" %}
In App Purchase - iOS Integration
{% endembed %}

{% embed url="<https://docs.webtonative.com/javascript-apis/in-app-purchase-android-integration>" %}
In App Purchase - Android Integration
{% endembed %}

***

This documentation provides a comprehensive guide for using the **Simple IAP Plugin** and customizing it to meet specific requirements.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.webtonative.com/website-plugins/wordpress/in-app-purchase/in-app-purchase.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
