> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Create a WordPress Plugin

## Article: Create a WordPress Plugin

## Article Link: https://dev.wix.com/docs/go-headless/self-managed-headless/tutorials/other-tutorials/create-a-word-press-plugin.md

## Article Content:

# Create a WordPress Plugin

WordPress is a common web content management platform that allows users to build, maintain, and publish web pages. [Wix Headless](https://dev.wix.com/docs/go-headless/get-started/about-wix-headless.md) allows you to integrate many of Wix's business solutions into your WordPress site.

This tutorial shows you how to create a WordPress plugin that integrates your Wix headless project with your WordPress site. It includes implementing a "Buy Now" flow that allows your visitor to purchase a product from a list.

You can find the full source code [here](https://github.com/wix-incubator/headless-tutorial-wordpress-plugin).

In this tutorial, you will:

1. Set up a Wix headless project and a WordPress environment.
2. Create a script to rebuild your plugin whenever you update it.
3. Create a full authorization flow that allows your WordPress site to make requests to your headless project and Wix APIs.
4. Query and display a dynamic list of products on your WordPress site using the Wix Stores API.
5. Implement a secured checkout functionality using the Wix eCommerce API.
6. Implement the necessary routing functionality using the Wix Redirect Session API.


## Step 1: Set up the Wix headless project

First, set the Wix headless project to act as your site's dashboard. Here you can install apps to add Wix functionality to your WordPress site.

To set up the Wix headless project, follow these steps:

1. If you haven't already, [create a Wix headless project](https://dev.wix.com/docs/go-headless/get-started/quick-starts/self-managed-headless/quick-start-a-self-managed-headless-project.md). When prompted to add functionalities to your new project, select **eCommerce**.
2. Set up authorization by [creating and configuring](https://dev.wix.com/docs/go-headless/authentication/about-authentication.md) an OAuth app on your headless project. Name the app `wix_example_client_id`. Note your client ID. You will need it later to integrate your WordPress site with the Wix headless project.

    ![Headless OAuth Settings Page](images/f068518c0806ff5ac3121e4cccdc9bce.png)

3. Finally, make sure that the Wix Stores app is installed: In your headless project dashboard, click **Apps**. If the **Wix Stores** app is not installed, install it. This Wix Stores app allows your WordPress site to access the [Wix Stores API](https://dev.wix.com/docs/api-reference/business-solutions/stores/introduction.md).

    ![Wix Stores App](images/dbfcd0d70ccd9d77b07bd802c0607099.png)


## Step 2: Set up a WordPress plugin

A WordPress plugin is a `zip` file that contains one or more PHP files. These files contain the functionality you want to add to your site with some metadata. This step describes how to write a script that automatically creates a `zip` file with your updated plugin files.

### Create a script to automatically build your plugin file

This script *builds* your code as a `zip` file. The script is written in JavaScript in a node.js environment. However, you can use any build tool and runtime environment you prefer.

Create the plugin zip file:

1. Create a new folder named `headless-wordpress-tutorial`. This folder will contain all the plugin files, including the build script and the finalized `zip` plugin file.

2. In this folder, create a new file named `wix-headless-example.php`. In it, add the following code:

    ```php
    <?php
    namespace HeadlessExample;

    /**
     * Plugin Name: Wix Headless Tutorial: Writing a WordPress Plugin
     * Description: This tutorial describes how to write a WordPress plugin that integrates the WordPress site with Wix Headless.
     * Version: 1.0.0
     * Author: Wix Headless
     * Author URI: https://www.wix.com/developers/headless
     */
    class WixHeadlessPlugin
    {
      public function __construct()
      {
      }
    }

    $WixHeadlessPlugin = new WixHeadlessPlugin();
    ```

    This serves as the basis for the plugin's functionality.

3. In the same `headless-wordpress-tutorial` folder, create two new folders:

   - A folder named `build`, to contain the automated build script.
   - A folder named `plugin`, to contain the plugin's functionality.

4. In `build`, create a new file named `zip-plugin.js`, and write the following code:

    ```js
    const fs = require('fs');
    const { exec } = require('child_process');

    const folderToDelete = 'dist';
    const folderToCreate = 'dist';
    const folderToZip = 'plugin';
    const zipFilePath = 'dist/wix-headless-example.zip';

    // Delete the "dist" folder, if it already exists
    if (fs.existsSync(folderToDelete)) {
      fs.rmSync(folderToDelete, { recursive: true });
    }

    // Create an empty folder "dist"
    fs.mkdirSync(folderToCreate);

    // Zip the contents of the "plugin" folder into "dist/plugin.zip"
    exec(`zip -r ${zipFilePath} ${folderToZip}/*`, (error, stdout, stderr) => {
      if (error) {
        console.error(`Error: ${error.message}`);
        return;
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`);
        return;
      }
      console.log(`Folder ${folderToZip} has been zipped successfully into ${zipFilePath}`);
    });
    ```

    This code removes any existing `zip` files, and generates a Wordpress-ready `plugin.zip` file, with all your plugin's functionality, in the `dist` folder. Whenever you add functionality to your plugin, you need to run the build script again, and upload the updated `plugin.zip` file to your Wordpress site.


### Optional: Test your plugin on your WordPress site

To test whether the plugin is recognized and rendered correctly on your WordPress site, include a test shortcode:

1. Update `wix-headless-example.php` with the following code:

    ```php
    class WixHeadlessPlugin
    {
      public function __construct() {
        add_shortcode('initial_shortcode', array($this, 'initial_shortcode'));
      }

      public function initial_shortcode() {
        return "Hello, this is a minimal WordPress plugin";
      }
    }
    ```

2. From the `headless-wordpress-tutorial` root directory, type `node build/zip-plugin.js` to run the build script.
3. On your site's WP Admin panel, click `Plugins` -> `Add New` -> `Upload Plugin`, and upload `dist/zip-plugin.js` to the site.
4. Activate the plugin.
5. Launch one of your site's pages and add a shortcode block with the content `[initial_shortcode]`.
6. Save and view the page to see the result.
7. Once you've confirmed the plugin is rendered on your site, remove the code you added in [Step 1](#step-1-set-up-the-wix-headless-project).

### Create a plugin settings page on your WordPress site

Once you have installed the OAuth app on your Wix headless project dashboard, your headless project is configured to provide services only to clients that carry the correct client ID.

To enable communication between your WordPress site and your headless project, configure your site with the correct client ID as provided by the OAuth app in [Step 1](#step-1-set-up-the-wix-headless-project). However, since the WP Admin panel does not have a built-in settings page to enable it to integrate with Wix Headless, you need to manually create a plugin settings page.

To create a plugin settings page and configure it with the client ID:

1. In the `plugin` folder, create a new folder named `templates`.
2. In `plugin/templates`, create a new file named `settings.php` with the following code:

    ```php
    <?php
    ?>

    <div class="wrap">
      <h2 style="display: none"></h2>
      <?php

      ?>
      <div id="Connect-OAuth" class="tabcontent">
        <h2>Wix Headless</h2>
        <form method="post" action="options.php">
          <?php settings_fields('wix_headless_example_settings_group'); ?>
          <?php do_settings_sections('wix-headless-example-settings'); ?>
          <table class="form-table">
            <tr style="vertical-align:top">
            <th scope="row">Wix Client ID</th>
            <td>
              <input required type="text" name="wix_example_client_id" value="<?php echo esc_attr(get_option('wix_example_client_id')); ?>" />
            </td>
            </tr>
            <!-- Add more settings fields here -->
          </table>
        <?php submit_button(); ?>
        </form>
      </div>
    </div>
    ```

    This file creates the structure of the plugin's settings page.

3. Add the plugin's settings page to your site's Admin panel. In `wix-headless-example.php`, add the following code:

    ```php
    <?php
    namespace HeadlessExample;

    class WixHeadlessPlugin
    {
      public function __construct() {
        // Register the plugin's settings
        add_action('admin_init', array($this, 'register_settings'));

        // Add the plugin's settings page
        add_action('admin_menu', array($this, 'create_settings_page'));
      }

      public static function register_settings() {
        add_option('wix_example_client_id', ''); // Add your settings here

        // Register the settings
        register_setting('wix_headless_example_settings_group', 'wix_example_client_id');
      }

      // Create the plugin's settings page
      public static function create_settings_page() {
        add_options_page(
          'Wix Headless Example Settings',    // Define the page title
          'Wix Headless Example',             // Define the menu title
          'manage_options',           // Add the capability required to access the page
          'wix-headless-example-settings',    // Define menu slug
          array(__CLASS__, 'render_settings_page') // Define callback function to render the page
        );
      }

      // Render the plugin's settings page on the site's Admin panel
      public static function render_settings_page() {
        $template = plugin_dir_path(__FILE__) . 'templates/settings.php';
        if (file_exists($template)) {
          include $template;
        } else {
          error_log('Wix Headless Example: Could not find settings template');
        }
      }
    }

    $WixHeadlessPlugin = new WixHeadlessPlugin();
    ```

    This code creates, registers, and renders your plugin's settings page on your WordPress site's Admin panel.

    Lastly, on your WordPress site's Admin panel, set the client ID from your project's [**Headless Settings**](https://www.wix.com/my-account/site-selector/?buttonText=Select%20Site&title=Select%20a%20Site&autoSelectOnSingleSite=true&actionUrl=https:%2F%2Fwww.wix.com%2Fdashboard%2F%7B%7BmetaSiteId%7D%7D%2Foauth-apps-settings).

4. On your WordPress site's Admin panel, click **Settings** > **Wix Headless Example**.
5. In the **Wix Client ID** input field, paste the client ID as it appears on your headless project's [**Headless Settings**](https://www.wix.com/my-account/site-selector/?buttonText=Select%20Site&title=Select%20a%20Site&autoSelectOnSingleSite=true&actionUrl=https:%2F%2Fwww.wix.com%2Fdashboard%2F%7B%7BmetaSiteId%7D%7D%2Foauth-apps-settings).

    ![WordPress Plugin Settings](images/f45ca94d6d014fa62ebc9dbb01eb63d5.png)

    Your WordPress site is now configured as the valid client of your Wix headless project.

## Step 3: Generate authorization tokens

To access Wix APIs, a client needs to carry valid access tokens. These include the client ID as defined in the previous step, and can be found in your project's [**Headless Settings**](https://www.wix.com/my-account/site-selector/?buttonText=Select%20Site&title=Select%20a%20Site&autoSelectOnSingleSite=true&actionUrl=https:%2F%2Fwww.wix.com%2Fdashboard%2F%7B%7BmetaSiteId%7D%7D%2Foauth-apps-settings). Access tokens are only valid for several hours. When they expire, they must be refreshed. Without a valid authorization token, a client cannot make requests to a headless project.

This step shows how to add a simple authorization service to your plugin. The service retrieves and checks for valid access tokens, refreshes them if necessary, and saves, or *persists*, them locally to your browser as cookies.

> **Note:** For additional information about creating and using access tokens, see the [Making API Calls with OAuth](https://dev.wix.com/docs/go-headless/authentication/setup/make-rest-api-calls-with-oauth.md) in the Wix REST API reference.

<blockquote class="important">

**Important:** To keep this tutorial simple and easy to understand, this authorization service applies to all devices. You might want to handle access tokens separately for each type of device.

</blockquote>

To create the authorization service:

1. In your `plugin` folder, create a new folder named `services`. In it, create a new file named `wix-auth.php` and add to it the following code:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      private static $tokens = null;

      public static function getTokens() {
        return Auth::$tokens;
      }
    }
    ```

    This creates the basic structural outline of the authorization service.

2. Add the functionality to retrieve, or *get*, any tokens that might already be locally saved in the form of a browser cookie:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      // ...

      private static string $COOKIE_NAME = 'wix-headless-example-tokens';

      public static function getPersistedTokens() {
        if (isset($_COOKIE[Auth::$COOKIE_NAME])) {
          // Retrieve existing JSON data from the cookie
          $jsonData = urldecode($_COOKIE[Auth::$COOKIE_NAME]);

          // Decode the JSON data
          $decodedData = json_decode($jsonData, true);

          if ($decodedData !== null) {
            // Return the decoded JSON data
            return $decodedData;
          } else {
            // Debug: Print the JSON decoding error
            error_log('Failed to decode JSON from the cookie.');
            return null;
          }
        } else {
          // Cookie not set or has expired
          return null;
        }
      }
    }
    ```

    This function checks and decodes any tokens that already exist in a user's browser. If no cookies are found, the function returns null.

3. Add the functionality to persist tokens in the user's browser as cookies:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      // ...

      public static function persistTokens(): void {
        $jsonData = json_encode(Auth::$tokens);
        $expiry = time() + 60 * 60 * 24 * 30; // Set token validity for 30 days
        $path = '/'; // Cookies are available in the entire domain
        $domain = '';
        setcookie(Auth::$COOKIE_NAME, urlencode($jsonData), $expiry, $path, $domain, false, false);
      }
    }
    ```

    This function saves a token to a user's browser in the form of a cookie. Each token is valid for 30 days, and can be used to access all parts of the site.

4. Add the functionality to check whether an access token has expired:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      // ...
      public static function isAccessTokenValid(): bool {
        $currentDate = time();
        return !!(Auth::$tokens['accessToken']['value'] ?? false) && Auth::$tokens['accessToken']['expiresAt'] > $currentDate;
      }
    }
    ```

5. Use the Wix API to get and refresh tokens:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class TokenRole
    {
      const VISITOR = 'visitor';
      const MEMBER = 'member';
    }

    class Auth
    {
      // ...

      // Convert the raw tokens to access tokens and refresh them
      private static function rawTokensToTokensResult(array $raw_tokens): array {
        return array(
          'accessToken' => Auth::createAccessToken($raw_tokens['access_token'], $raw_tokens['expires_in']),
          'refreshToken' => array(
            'value' => $raw_tokens['refresh_token'],
            'role' => TokenRole::VISITOR,
          ),
        );
      }

      // Create an access token with an expiration date
      private static function createAccessToken(string $accessToken, int $expiresIn): array {
        $now = time();
        return array(
            'value' => $accessToken,
            'expiresAt' => $expiresIn + $now,
        );
      }

      // Generate a visitor token using the Wix Token endpoint
      public static function generateVisitorTokens(): array {
        $client_id = get_option('wix_example_client_id');
        if (!empty($client_id)) {
          $token_request = Auth::$tokens['refreshToken'] && Auth::$tokens['refreshToken']['role'] == TokenRole::VISITOR ? array(
            'refresh_token' => Auth::$tokens['refreshToken']['value'], 'grantType' => 'refresh_token', 'scope' => 'offline_access',
          ) : array(
            'clientId' => $client_id, 'grantType' => 'anonymous', 'scope' => 'offline_access',
          );

          $response = wp_remote_post('https://www.wixapis.com/oauth2/token', array(
            'method' => 'POST',
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode($token_request),
            'data_format' => 'body',
          ));

          if (!is_wp_error($response) && $response['response']['code'] === 200) {
            $body = wp_remote_retrieve_body($response);
            $raw_tokens = json_decode($body, true);
            return Auth::rawTokensToTokensResult($raw_tokens);
          } else {
              error_log('Failed to get tokens : Wix request ID: '.get_wix_request_id($response).' full response '.json_encode($response));
            throw new \RuntimeException('Failed to get tokens');
          }
        } else {
          return [];
        }
      }
    }
    ```


    This code defines two types of tokens, one for site visitors and one for logged-in site members. Then, the `generateVisitorTokens()` function creates and processes visitor tokens using the Wix REST `Token` endpoint.

    These tokens are required to make calls to Wix APIs on behalf of your visitor. Without them, your calls will not be authorized. You can read more about visitor tokens in the [Wix Headless REST API documentation](https://dev.wix.com/docs/go-headless/authentication/setup/make-rest-api-calls-with-oauth.md).

6. Finally, now that tokens have been set up, set the authorization service to initialize as soon as your WordPress site initializes the plugin.

7. Still in `services/wix-auth.php`, add the service initialization function:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      // ...
      public static function init(): void {
        Auth::$tokens = Auth::getPersistedTokens();
        if (!Auth::isAccessTokenValid()) {
          Auth::$tokens = Auth::generateVisitorTokens();
          Auth::persistTokens();
        }
      }
    }
    ```

    This function checks for existing visitor tokens, and if none are found, creates and persists new ones. It makes sure that your site has valid tokens when making calls to Wix APIs.

8. Back in `wix-headless-example.php`, bring the authorization service into the scope of the file:

    ```php
    <?php
    namespace HeadlessExample;

    use HeadlessExample\Services\Auth;
    require_once plugin_dir_path(__FILE__) . 'services/wix-auth.php';

    // ...
    ```

    These `use` and `require_once` statements allow the functions in this file to access the functions defined in the authorization service.

9. Finally, register and call the authorization service's initialization method:

    ```php
    <?php
    namespace HeadlessExample;

    use HeadlessExample\Services\Auth;

    require_once plugin_dir_path(__FILE__) . 'services/wix-auth.php';

    class WixHeadlessPlugin
    {
      public function __construct() {
      // ...
        add_filter('init', array($this, 'init'));
      }

      // ...

      public static function init() {
        Auth::init();
      }
    }

    $WixHeadlessPlugin = new WixHeadlessPlugin();
    ```

    The `add_filter()` function registers the `init()` function for the `init` WordPress hook. This means that, whenever the `init` WordPress hook fires, the local `init()` function runs and initializes the authorization service.


## Step 4: Get Wix Request ID Returned by Wix APIs

Whenever a Wix API responds to a client request, a unique request ID is included in the response. This can be helpful if you need to contact Wix support for help. In this step, you will add a service to retrieve the request ID as returned by the Wix API.

To get the Wix request ID:

1. In the `plugin` folder, create a new folder named `utils`. This folder will contain various utility services.
2. In `plugin/utils`, create a new file named `wix-request-id.php` and add to it the following code:

    ```php
    <?php

    function get_wix_request_id($response) {
      $headers = wp_remote_retrieve_headers( $response );
      return $headers['x-wix-request-id'] ?? 'Header not found';
    }
    ```

    When called, this function extracts the Wix request ID from the given response, and returns it to the caller.

3. Back in `services/wix-auth.php`, call the `get_wix_request_id()` method whenever an error is logged by the `generateVisitorTokens()` function:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class Auth
    {
      // ...
      public static function generateVisitorTokens(): array {

        // ...
        if (!empty($client_id)) {
        // ...
          if (!is_wp_error($response) && $response['response']['code'] === 200) {
            // ...
          } else {
            error_log('Failed to get tokens : Wix request ID: '.get_wix_request_id($response).' full response '.json_encode($response));
            throw new \RuntimeException('Failed to get tokens');
          }
        } else {
          // ...
        }
      }
    }
    ```

    Adding a call to `get_wix_request_id()` whenever tokens have failed to generate makes it easier to debug, resolve errors, and request additional help from Wix's support teams.


## Step 5: Get products using the Wix Stores API

Now that you can make authorized calls to Wix APIs, you can integrate any of Wix Headless's business solutions into your site. In this tutorial, you will implement two eCommerce functionalities&mdash;a product list, and a checkout.

<blockquote class="important">

**Important:** A complete eCommerce user flow is usually comprised of a product list, a single-product page, a cart, and a checkout. However, this tutorial only covers creating a product list and a checkout. This is because this tutorial focuses on a pure server-side implementation, while implementing a product page and a cart requires client-side code using the [Wix eCommerce SDK](https://dev.wix.com/docs/go-headless/self-managed-headless/self-managed-tutorials/java-script-sdk-tutorials/e-commerce-quick-start.md).

</blockquote>

## Query the existing products

The first Wix eCommerce functionality to implement is the product list. Use the Wix Stores API to create a service that queries and lists the products in your Wix headless project's CMS.

First, create the service:

1. In the `plugin/services` folder, create a new file named `wix-products.php`.
2. In `wix-products.php`, add the following code:

    ```php
    <?php

    namespace HeadlessExample\Services;

    class WixStoresProducts
    {
      public static function getProducts(string $slug = null): array {
        $tokens = Auth::getTokens();

        if (! $tokens['accessToken']) {
          throw new \RuntimeException('No access token');
        }

        $response = wp_remote_post('https://www.wixapis.com/stores/v1/products/query', array(
          'method'      => 'POST',
          'headers'     => array('Content-Type' => 'application/json', 'Authorization' => $tokens['accessToken']['value']),
          'body'        => $slug ? '{"query": {"filter": "{\"slug\": \"'.$slug.'\"}"}}' : '',
          'data_format' => 'body',
        ));

        if (!is_wp_error($response) && $response['response']['code'] === 200) {
          $body = wp_remote_retrieve_body($response);
          return json_decode($body, true);
        } else {
          error_log('Failed to get products, request ID: '.get_wix_request_id($response).' full response: '.json_encode($response));
          throw new \RuntimeException('Failed to get products');
        }
      }
    }
    ```

    The `getProducts()` function makes an authorized call to the Wix Stores API. It queries all products that exist in your headless project's CMS.


## Create a template to display your products

Next, create a WordPress template file to display your product list:

1. In `plugin/templates`, create a new file named `product-list.php`.
2. In `product-list.php`, add the following code:

    ```php
    <?php

    if (!defined('ABSPATH')) {
      exit;
    }

    /** @var array $products */
    $buy_now_url = rest_url() . 'wix-headless-example/v1/buy-now?productSlug=';
    ?>
    <?php if (empty($products)) : ?>
      <p>No products found.</p>
    <?php else : ?>
      <ul>
        <?php foreach ($products as $product) : ?>
          <li><?php echo esc_html($product['name']); ?></li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
    ```

    This code creates the template for displaying a dynamic list of products.

### Render the list of products on your WordPress site

Now that the products have been queried, and a template exists for displaying them, all that is left is to display them on your site.

1. In `plugin/wix-headless-example.php`, add the following code:


    ```php
    <?php
    namespace HeadlessExample;

    class WixHeadlessPlugin
    {
      public function __construct() {
        // ...
        add_shortcode('wixwp_products', array($this, 'wix_headless_render_product_list'));
      }

      // ...

      public static function wix_headless_render_product_list($attrs) {
      $product_list = WixStoresProducts::getProducts();
      $products = $product_list['products'];
      $attrs = shortcode_atts(array(
          'template' => '',
        ), $attrs);

      $templates = array( $attrs['template'], 'templates/product-list.php');

      $template_file = locate_template( $templates, true, true );

        // If it isn't defined in the WordPress theme or attribute, use the plugin template
        if (!file_exists($template_file)) {
          $template_file = plugin_dir_path(__FILE__).'templates/product-list.php';
        }

        extract($products);
        ob_start();

        if (file_exists($template_file)) {
          include $template_file;
        } else {
          echo 'Template file not found!';
        }

        return ob_get_clean();
      }
    }

    $WixHeadlessPlugin = new WixHeadlessPlugin();
    ```

    This `wix_headless_render_product_list()` function queries the existing products and uses the `product-list` template file to render the products on the screen. It also registers this function for the `wixwp_products` shortcode.

    > **Note:** The `locate_template()` function allows the theme to override the existing template.


2. Finally, on your WordPress site, add a shortcode block with the `[wixwp_products]` shortcode. View your page to see the list of products.

## Step 6: Add a secured checkout functionality

The second Wix eCommerce functionality you will implement is the Wix secured checkout. This involves implementing a dynamic "Buy Now" route for each product. When clicked, the route takes your visitor to a secured checkout page where they can complete their purchase.

> **Note:** As its name suggests, the "Buy Now" functionality takes your visitor directly to a checkout page, without taking them through a product page and a shopping cart first. This means that product variants or options are not supported in this implementation. For a full eCommerce implementation, see the [Wix Headless eCommerce tutorial](https://dev.wix.com/docs/go-headless/self-managed-headless/self-managed-tutorials/java-script-sdk-tutorials/e-commerce-quick-start.md).

### Add URL slugs for the queried products

To create a dynamic checkout page for each product, queried each product must first be identified with a unique, dynamic URL. In `plugin/services/wix-products.php`, update the value of the request body to include a dynamic slug:

```php
<?php
namespace HeadlessExample\Services;

class WixStoresProducts
{
  public static function getProducts(string $slug = null): array {
    // ...
    $response = wp_remote_post('https://www.wixapis.com/stores/v1/products/query', array(
    // ...
    'body' => $slug ? '{"query": {"filter": "{\"slug\": \"'.$slug.'\"}"}}' : '',
    // ...
    ));
    // ...
  }
}
```

Now, when making a call to the Wix Stores API, the request body includes a unique URL slug for each product.

### Create the checkout service using Wix eCommerce API

Wix Headless offers a secured checkout service that can be dynamically populated with each product's details.

Use the Wix eCommerce API to create a secured checkout service:

1. In `plugin/services`, create a new file named `wix-checkout.php`.
2. Add to it the following code:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class CheckoutServices {
      public static function createCheckout($productId, $quantity) {
        $tokens = Auth::getTokens();

        if (! $tokens['accessToken']) {
          throw new \RuntimeException('No access token');
        }

        $item = [
          'quantity' => $quantity,
          'catalogReference' => [
            'catalogItemId' => $productId,
            'appId' => '215238eb-22a5-4c36-9e7b-e7c08025e04e',
          ],
        ];

        $lineItems = [$item];
        $channelType = "WEB";

        $data = [
          "lineItems" => $lineItems,
          "channelType" => $channelType
        ];

        $response = wp_remote_post('https://www.wixapis.com/ecom/v1/checkouts', array(
          'method'      => 'POST',
          'headers'     => array('Content-Type' => 'application/json', 'Authorization' => $tokens['accessToken']['value']),
          'body'        => json_encode($data),
          'data_format' => 'body',
        ));

        if (!is_wp_error($response) && $response['response']['code'] === 200) {
          $body = wp_remote_retrieve_body($response);
          return json_decode($body, true);
        } else {
          error_log('Failed to create checkout, request ID: '.get_wix_request_id($response).' full response: '.json_encode($response));
          throw new \RuntimeException('Failed to create checkout');
        }
      }
    }
    ```

    The [`createCheckout()` function](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/checkout/checkout/create-checkout.md) makes a call to the [Wix eCommerce API](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/checkout/checkout/create-checkout.md) with the details of the product that was clicked. The function returns a new checkout object used to render the Wix Checkout page on your WordPress site.


### Create the redirect session

Now, whenever a product is clicked, a checkout page dynamically loads with that product's details. However, the checkout page itself is a Wix page, which means it isn't hosted on your WordPress site, but rather on Wix's servers. Therefore, your visitor still needs to be redirected there to complete their purchase, and back to your WordPress site once they are done.

To redirect your visitor from your WordPress site to the Wix checkout page, and then return them to your site once they have completed their purchase, you need to use the [Wix Redirect Session API](https://dev.wix.com/docs/api-reference/business-management/headless/redirects/introduction.md).

Create a redirection service to handle redirecting your visitor to, and back from, the Wix checkout page:

1. Still in `plugin/services/wix-checkout.php`, add the following code:

    ```php
    <?php
    namespace HeadlessExample\Services;

    class CheckoutServices {
      // ...

      public static function createCallbackUrls(): array {
        $baseUrl = get_site_url();

        return [
          "baseUrl" => $baseUrl,
          "postFlowUrl" => $baseUrl,
        ];
      }

      public static function createCheckoutRedirectSession($checkoutId) {
        $tokens = Auth::getTokens();

        if (! $tokens['accessToken']) {
          throw new \RuntimeException('No access token');
        }

        $data = [
          "ecomCheckout" => ["checkoutId" => $checkoutId],
          "callbacks" => CheckoutServices::createCallbackUrls()
        ];

        $response = wp_remote_post('https://www.wixapis.com/_api/redirects-api/v1/redirect-session', array(
          'method' => 'POST',
          'headers'     => array('Content-Type' => 'application/json', 'Authorization' => $tokens['accessToken']['value']),
          'body' => json_encode($data),
          'data_format' => 'body',
        ));

        if (!is_wp_error($response) && $response['response']['code'] === 200) {
            $body = wp_remote_retrieve_body($response);
            return json_decode($body, true);
        } else {
            error_log('Failed to create redirect session, request ID: '.get_wix_request_id($response).' full response: '.json_encode($response));
          throw new \RuntimeException('Failed to create redirect session for checkout');
        }
      }
    }
    ```

    The [`createCheckoutRedirectSession()` function](https://dev.wix.com/docs/api-reference/business-management/headless/redirects/create-redirect-session.md) makes an authorized call to the Wix Redirect Sessions API. The `postFlowUrl` value included in the call specifies where your visitor returns upon completing their purchase. The function then returns the processed redirect session to the calling router.


### Create a router to handle the "Buy Now" flow

The redirection functionality is now configured, but it is not integrated into your page. You now need to create a routing service that manages the entire "Buy Now" redirection and checkout flow.

Create the routing service:

1. In `plugin/utils`, create a new file named `routes.php`.
2. In `routes.php`, write the following code:

    ```php
    <?php
    use HeadlessExample\Services\CheckoutServices;
    use HeadlessExample\Services\WixStoresProducts;

    function wix_headless_buy_now_endpoint(): void
    {
      register_rest_route('wix-headless-example/v1', '/buy-now', array(
        'methods' => 'GET',
        'callback' => 'wix_headless_buy_now_callback',
        'permission_callback' => '__return_true',
        'args' => array(
          'productSlug' => array(
            'required' => true,
          ),
          'quantity' => array(
            'required' => false,
          ),
        ),
      ));
    }

    function wix_headless_buy_now_callback($request)
    {
      error_log('wix_headless_buy_now_callback');
      $product_slug = $request->get_param('productSlug');
      $quantity = intval($request->get_param('quantity') ?? '1', 10);
      $products = WixStoresProducts::getProducts($product_slug);
      $product = (object)($products['products'][0]);

      $checkout = CheckoutServices::createCheckout($product->id, $quantity);

      $redirect_session = CheckoutServices::createCheckoutRedirectSession($checkout['checkout']['id']);

      $response = rest_ensure_response(null);
      $response->set_status(302); // Set the HTTP status code to 302 (Found/Temporary Redirect)
      $response->header('Location', $redirect_session['redirectSession']['fullUrl']);

      return $response;
    }
    ```

    The `wix_headless_buy_now_endpoint()` specifies which Wix REST endpoint must be called whenever a product is clicked. Its callback function, `wix_headless_buy_now_callback()`, creates both the dynamic checkout page with the clicked product's details, and the necessary redirection functionality.


#### Make the business services accessible to your plugin

The product list, checkout, and redirect services have been set up. You now need to let your main plugin logic know that they are available and where it can find them. Your WordPress site also needs to be aware of the Wix REST endpoints used by these services.

1. Bring the router into the scope of your plugin. In `plugin/wix-headless-example.php`, add the following lines:

    ```php
    <?php
    namespace HeadlessExample;

    use HeadlessExample\Services\Auth;
    use HeadlessExample\Services\WixStoresProducts;
    defined( 'ABSPATH' ) || exit;

    require_once plugin_dir_path(__FILE__) . 'utils/wix-request-id.php';
    require_once plugin_dir_path(__FILE__) . 'services/wix-auth.php';
    require_once plugin_dir_path(__FILE__) . 'services/wix-products.php';
    require_once plugin_dir_path(__FILE__) . 'services/wix-checkout.php';
    require_once plugin_dir_path(__FILE__) . 'utils/routes.php';

    class WixHeadlessPlugin
    {
      // ...
    }
    ```

    The `use .../WixStoresProducts` statement makes the product list, checkout, and redirection functionalities available to the functions in the current file. The various `require_once` statements act as safeguards to make sure that files already brought into scope won't be brought in again.

2. Finally, register the "Buy Now" endpoint to your WordPress site. In `plugin/wix-headless-example.php`, add the following line:

    ```php
    <?php
    namespace HeadlessExample;
    //...
    require_once plugin_dir_path(__FILE__) . 'services/wix-checkout.php';
    require_once plugin_dir_path(__FILE__) . 'utils/routes.php';

    class WixHeadlessPlugin
    {
      public function __construct() {
        // ...

        add_action('rest_api_init', 'wix_headless_buy_now_endpoint');
      }

      // ...
    }

    $WixHeadlessPlugin = new WixHeadlessPlugin();
    ```

    The `add_action()` WordPress function registers `wix_headless_buy_now_endpoint()` as the callback function to be called whenever the `rest_api_init` hook fires. Whenever your WordPress site initializes its REST API functionality, the `wix_headless_buy_now_endpoint()` function runs and begins the "Buy Now" flow.


### Add the "Buy Now" option to products

Finally, embed the "Buy Now" option in the list of products on your WordPress site. In `templates/product-list.php`, add the following line to your code:

```php
<?php

// ...

<?php if (empty($products)) : ?>
  // ...
<?php else : ?>
  <ul>
      <?php foreach ($products as $product) : ?>
        <li>
          <a href="<?php echo $buy_now_url.$product['slug'] ?>"><?php echo esc_html($product['name']); ?></a> // Add the "Buy Now" functionality
        </li>
      <?php endforeach; ?>
  </ul>
<?php endif; ?>
```

When a visitor clicks a product, they are redirected to the checkout page to complete their purchase, and redirected back to your site once they have completed their purchase.

## Conclusion

Well done! In this tutorial you created from scratch a WordPress plugin that integrates a limited Wix Headless eCommerce user flow with your WordPress site. It was done using server-side code only.

You can find the full source code [here](https://github.com/wix-incubator/headless-tutorial-wordpress-plugin).

However, You can expand the existing implementation to include other business services, such as product pages and a cart, by adding client-side code. For a sample implementation, see the [Wix Headless eCommerce tutorial](https://dev.wix.com/docs/go-headless/self-managed-headless/self-managed-tutorials/java-script-sdk-tutorials/e-commerce-quick-start.md).