# WooCommerce

> The OTP.ps plugin for WooCommerce, which confirms the customer's number before you ship a cash-on-delivery order, plus a minimal example.

## The plugin

**[Download OTP.ps for WooCommerce](https://otp.ps/downloads/otp-ps-for-woocommerce.zip)** (WordPress 6.2+, WooCommerce 7+, PHP 7.4+).

Two ways for customers to confirm, chosen in **WooCommerce → Settings → OTP.ps**:

| | How | Checkouts |
|---|---|---|
| **After the order** (default) | The order waits **on hold**. The customer confirms through a [verification link](/docs/verification-links), texted to them or shown on the thank-you page. The order then moves to **processing** by itself, with a note | Every checkout, including the block checkout |
| **At checkout** | A code box under the phone field; the order can't be placed until the number is confirmed | Classic (shortcode) checkout |

Setup:

1. **Plugins → Add New → Upload Plugin**, choose the zip, activate.
2. Put your key in `wp-config.php`: `define('OTP_PS_API_KEY', 'otp_test_…');`. You can also enter it on the settings tab, but wp-config.php keeps it out of the database.
3. **WooCommerce → Settings → OTP.ps**: choose the mode and which payment methods need a confirmed number (cash on delivery by default), then press **Connect** under "Instant updates" to set up [webhooks](/docs/webhooks) automatically.
4. Test with the number `0599000001` and a test key (nothing is sent; on a code page the code is `1234`), then switch to a live key.

If the webhook can't reach the store, the order is still confirmed when the customer comes back to the thank-you page: the plugin asks OTP.ps; it never trusts the address alone. Orders not confirmed in time get a note so your team can call the customer.

The plugin is tested against the OTP.ps API with a stand-in for WordPress (holding the order, the texted link, forged and genuine webhooks, the thank-you page). Try it on a staging site before your live shop.

## A minimal example

If you'd rather write your own, the file below is the classic-checkout version in one file.

What it does: on the checkout page, under the billing details, the customer can send a code to their billing phone and confirm it. A **cash-on-delivery** order is refused unless the billing phone matches the number confirmed in this session. Other payment methods are not affected.

Setup:

1. Add the key to `wp-config.php` (not to the database or the theme): `define('OTP_PS_API_KEY', 'otp_test_…');`
2. Save the file as `wp-content/plugins/otp-ps-cod/otp-ps-cod.php` and activate **OTP.ps — verify the phone on cash-on-delivery orders**.
3. Test with the sandbox number `0599000001` (code `1234`), then switch to a live key.

Limits of this example: it supports the **classic (shortcode) checkout**. The block-based Checkout needs a different integration (a Store API extension), not covered yet. The file is syntax-checked on every change; it hasn't been run inside a WordPress installation in OTP.ps's tests, so try it on a staging site first.

```php title="examples/woocommerce/otp-ps-cod.php"
<?php
/**
 * Plugin Name: OTP.ps — verify the phone on cash-on-delivery orders
 * Description: Customers paying cash on delivery confirm their mobile number with an OTP.ps code before the order is placed. Classic (shortcode) checkout.
 * Version: 1.0.0
 * Requires PHP: 7.4
 *
 * Setup: put the key in wp-config.php (never in the database or theme files):
 *   define('OTP_PS_API_KEY', 'otp_test_…');   // a live key once tested
 * Then copy this file to wp-content/plugins/otp-ps-cod/otp-ps-cod.php and activate it.
 */

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

const OTP_PS_COD_BASE = 'https://otp.ps';

/** Same rules as the API: +9705(9|6)XXXXXXX, or null. */
function otp_ps_cod_normalize(string $raw): ?string
{
    $d = preg_replace('/\D/', '', strtr($raw, ['٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4', '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9']));
    if (strpos($d, '00') === 0) $d = substr($d, 2);
    if (strlen($d) === 12 && (strpos($d, '970') === 0 || strpos($d, '972') === 0)) $d = substr($d, 3);
    if (strlen($d) === 10 && $d[0] === '0') $d = substr($d, 1);
    return preg_match('/^5[96]\d{7}$/', $d) ? '+970' . $d : null;
}

function otp_ps_cod_api(string $path, array $body, array $headers = []): array
{
    $res = wp_remote_post(OTP_PS_COD_BASE . '/api/v1' . $path, [
        'timeout' => 15,
        'headers' => array_merge(['Authorization' => 'Bearer ' . OTP_PS_API_KEY, 'Content-Type' => 'application/json'], $headers),
        'body' => wp_json_encode($body),
    ]);
    if (is_wp_error($res)) {
        return ['ok' => false, 'data' => ['error' => 'unavailable']];
    }
    $code = wp_remote_retrieve_response_code($res);
    return ['ok' => $code < 400, 'data' => json_decode(wp_remote_retrieve_body($res), true) ?: []];
}

// AJAX: send a code to the billing phone.
function otp_ps_cod_send(): void
{
    check_ajax_referer('otp_ps_cod', 'nonce');
    $phone = otp_ps_cod_normalize((string) ($_POST['phone'] ?? ''));
    if (!$phone) {
        wp_send_json_error(['error' => 'invalid_phone']);
    }
    $sends = array_filter((array) WC()->session->get('otp_ps_sends', []), fn($t) => $t > time() - 900);
    if (count($sends) >= 5) {
        wp_send_json_error(['error' => 'rate_limited']); // your own limit per visitor
    }
    $sends[] = time();
    WC()->session->set('otp_ps_sends', $sends);
    $locale = strpos(get_locale(), 'ar') === 0 ? 'ar' : 'en';
    $r = otp_ps_cod_api('/verify/send', ['phone' => $phone, 'purpose' => 'order', 'locale' => $locale]);
    if (!$r['ok']) {
        wp_send_json_error(['error' => $r['data']['error'] ?? 'unavailable', 'retryAfter' => $r['data']['retry_after'] ?? null]);
    }
    WC()->session->set('otp_ps_pending', ['id' => $r['data']['id'], 'phone' => $phone]);
    wp_send_json_success(['to' => $r['data']['to']]);
}
add_action('wp_ajax_otp_ps_cod_send', 'otp_ps_cod_send');
add_action('wp_ajax_nopriv_otp_ps_cod_send', 'otp_ps_cod_send');

// AJAX: check the code.
function otp_ps_cod_check(): void
{
    check_ajax_referer('otp_ps_cod', 'nonce');
    $pending = WC()->session->get('otp_ps_pending');
    if (!$pending) {
        wp_send_json_error(['error' => 'no_code']);
    }
    $r = otp_ps_cod_api('/verify/check', ['id' => $pending['id'], 'code' => sanitize_text_field((string) ($_POST['code'] ?? ''))]);
    if ($r['ok'] && ($r['data']['valid'] ?? false) === true) {
        WC()->session->set('otp_ps_pending', null);
        WC()->session->set('otp_ps_verified_phone', $pending['phone']);
        wp_send_json_success(['verified' => true]);
    }
    if (($r['data']['status'] ?? '') !== 'pending') {
        WC()->session->set('otp_ps_pending', null);
    }
    wp_send_json_error(['status' => $r['data']['status'] ?? null, 'attemptsLeft' => $r['data']['attempts_left'] ?? null]);
}
add_action('wp_ajax_otp_ps_cod_check', 'otp_ps_cod_check');
add_action('wp_ajax_nopriv_otp_ps_cod_check', 'otp_ps_cod_check');

// The order is refused unless the billing phone was verified in this session.
add_action('woocommerce_checkout_process', function () {
    if (($_POST['payment_method'] ?? '') !== 'cod') {
        return;
    }
    $phone = otp_ps_cod_normalize((string) ($_POST['billing_phone'] ?? ''));
    if (!$phone || WC()->session->get('otp_ps_verified_phone') !== $phone) {
        wc_add_notice(__('Please confirm your mobile number with the code we send you before placing a cash-on-delivery order.', 'otp-ps-cod'), 'error');
    }
});

// The code box under the billing phone, and its script.
add_action('woocommerce_after_checkout_billing_form', function () {
    echo '<div id="otp-ps-cod" style="margin:1em 0">'
        . '<button type="button" class="button" id="otp-ps-send">' . esc_html__('Send verification code', 'otp-ps-cod') . '</button> '
        . '<input type="text" id="otp-ps-code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" style="width:8em" placeholder="' . esc_attr__('Code', 'otp-ps-cod') . '" dir="ltr"> '
        . '<button type="button" class="button" id="otp-ps-check">' . esc_html__('Confirm', 'otp-ps-cod') . '</button>'
        . '<p id="otp-ps-msg" role="status"></p></div>';
});

add_action('wp_enqueue_scripts', function () {
    if (!function_exists('is_checkout') || !is_checkout()) {
        return;
    }
    wp_register_script('otp-ps-cod', '', ['jquery'], '1.0.0', true);
    wp_enqueue_script('otp-ps-cod');
    wp_localize_script('otp-ps-cod', 'otpPsCod', [
        'ajax' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('otp_ps_cod'),
        'sent' => __('Code sent to', 'otp-ps-cod'),
        'ok' => __('Number confirmed ✓', 'otp-ps-cod'),
        'wrong' => __('Wrong code. Tries left:', 'otp-ps-cod'),
        'again' => __('Please ask for a new code.', 'otp-ps-cod'),
        'error' => __('Could not send the code. Check the number and try again.', 'otp-ps-cod'),
    ]);
    wp_add_inline_script('otp-ps-cod', <<<'JS'
jQuery(function ($) {
  var busy = false, msg = function (t) { $('#otp-ps-msg').text(t); };
  $(document).on('click', '#otp-ps-send', function () {
    if (busy) return; busy = true; var b = $(this).prop('disabled', true);
    $.post(otpPsCod.ajax, { action: 'otp_ps_cod_send', nonce: otpPsCod.nonce, phone: $('#billing_phone').val() })
      .done(function (r) { msg(r.success ? otpPsCod.sent + ' ' + r.data.to : otpPsCod.error); })
      .always(function () { busy = false; setTimeout(function () { b.prop('disabled', false); }, 30000); });
  });
  $(document).on('click', '#otp-ps-check', function () {
    if (busy) return; busy = true;
    $.post(otpPsCod.ajax, { action: 'otp_ps_cod_check', nonce: otpPsCod.nonce, code: $('#otp-ps-code').val() })
      .done(function (r) {
        if (r.success) msg(otpPsCod.ok);
        else if (r.data && r.data.status === 'pending') msg(otpPsCod.wrong + ' ' + r.data.attemptsLeft);
        else msg(otpPsCod.again);
      })
      .always(function () { busy = false; });
  });
});
JS
    );
});
```
