For your web developer

Online Purchase Integration Guide

This page explains how to connect your online store to Perk Miner so member purchases are recorded and cash back is paid correctly.

Sale amounts are verified. A purchase only counts when the amount is sent by your store's server (or by Shopify) and signed with your private Sales Key. The amount can never come from the shopper's browser, which protects you from inflated sales and unexpected advertising fees.

Your connection details

To see your Business ID and Sales Key, log in to your business account and open this page again. The code below uses the placeholders YOUR_BUSINESS_ID and YOUR_SALES_KEY.

1. How the flow works

  1. A Perk Miner member clicks “Shop on this business's website” and lands on your site with a perk_token in the URL.
  2. Script A (every page) saves that token for 24 hours.
  3. When the customer places an order, your server keeps the token with the order. When the order is paid, your server tells Perk Miner the order number and total, signed with your Sales Key (WooCommerce and custom sites), or Shopify does it for you with its signed “Order payment” webhook.
  4. Perk Miner LLC records the sale once (re-sending the same order is safe), pays cash back, and bills your advertising fee (10%, or 2% on the 2% Ad Fee plan).
  5. Optional: Script B on your order confirmation page sends the customer to their Perk Miner receipt.

2 Script A — add to every page of your site (inside <head>)

Saves the token so it is still available at checkout. Required for every platform.

<script>
(function () {
  try {
    var t = new URLSearchParams(window.location.search || "").get("perk_token");
    if (!t) return;
    localStorage.setItem("perk_token", JSON.stringify({ t: t, at: Date.now() }));
    document.cookie = "perk_token=" + encodeURIComponent(t) + "; path=/; max-age=86400; SameSite=Lax; Secure";
  } catch (e) {}
})();
</script>

3 Report the paid order from your server

Choose the one that matches your store. The order number and total must come from your own database / order object, never from the browser.

A) WooCommerce (WordPress)

1) Add these two lines to wp-config.php (above the “That's all, stop editing” line):

define('PERKMINER_BUSINESS_ID', 'YOUR_BUSINESS_ID');
define('PERKMINER_SALES_KEY',  'YOUR_SALES_KEY');

2) Add this to your theme's functions.php (or a code-snippets plugin):

// Sends a signed request to Perk Miner
function perkminer_post($path, $payload) {
  $body = wp_json_encode($payload);
  $ts   = (string) time();
  $sig  = hash_hmac('sha256', $ts . '.' . $body, PERKMINER_SALES_KEY);
  return wp_remote_post('https://www.perkminer.com' . $path, array(
    'timeout' => 15,
    'headers' => array(
      'Content-Type'          => 'application/json',
      'X-PerkMiner-Business'  => PERKMINER_BUSINESS_ID,
      'X-PerkMiner-Timestamp' => $ts,
      'X-PerkMiner-Signature' => $sig,
    ),
    'body' => $body,
  ));
}

// 1) at checkout: keep the member's token with the order
add_action('woocommerce_checkout_create_order', function ($order) {
  if (!empty($_COOKIE['perk_token'])) {
    $order->update_meta_data('_perk_token', sanitize_text_field(wp_unslash($_COOKIE['perk_token'])));
  }
});

// 2) when the order is paid: report the REAL total from the order
function perkminer_report_order($order_id) {
  $order = wc_get_order($order_id);
  if (!$order || $order->get_meta('_perk_reported')) return;
  $token = $order->get_meta('_perk_token');
  if (!$token || $order->get_currency() !== 'USD') return;   // not a Perk Miner customer / not US dollars
  $res = perkminer_post('/api/external_sale/confirm', array(
    'perk_token' => $token,
    'order_id'   => (string) $order->get_id(),
    'amount'     => round((float) $order->get_total(), 2),
  ));
  if (!is_wp_error($res) && in_array(wp_remote_retrieve_response_code($res), array(200, 409), true)) {
    $order->update_meta_data('_perk_reported', '1');
    $order->save();
  }
}
add_action('woocommerce_order_status_processing', 'perkminer_report_order');
add_action('woocommerce_order_status_completed',  'perkminer_report_order');

// 3) connection test: while logged in as an admin, open  https://YOURSITE.com/?perkminer_test=1
add_action('init', function () {
  if (isset($_GET['perkminer_test']) && current_user_can('manage_woocommerce')) {
    $r = perkminer_post('/api/ecommerce/verify-beacon', array('ping' => true));
    wp_die('Perk Miner replied: ' . esc_html(is_wp_error($r) ? $r->get_error_message() : wp_remote_retrieve_body($r)));
  }
});

B) Custom website — PHP

Save $_COOKIE['perk_token'] in your orders table when the order is created, then call this when the order is paid:

function perkminer_report_sale($perkToken, $orderId, $total) {
  $body = json_encode(array('perk_token' => $perkToken, 'order_id' => (string)$orderId, 'amount' => round((float)$total, 2)));
  $ts   = (string) time();
  $sig  = hash_hmac('sha256', $ts . '.' . $body, 'YOUR_SALES_KEY');
  $ch = curl_init('https://www.perkminer.com/api/external_sale/confirm');
  curl_setopt_array($ch, array(
    CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15,
    CURLOPT_HTTPHEADER => array('Content-Type: application/json',
      'X-PerkMiner-Business: YOUR_BUSINESS_ID', 'X-PerkMiner-Timestamp: ' . $ts, 'X-PerkMiner-Signature: ' . $sig),
  ));
  $response = curl_exec($ch);
  $status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  return array($status, $response);   // 200 = recorded (or already recorded). 402 = add funds, then retry.
}

C) Custom website — Node.js (18 or newer)

const crypto = require("crypto");

async function perkminerReportSale(perkToken, orderId, total) {
  const body = JSON.stringify({ perk_token: perkToken, order_id: String(orderId), amount: Math.round(Number(total) * 100) / 100 });
  const ts = String(Math.floor(Date.now() / 1000));
  const sig = crypto.createHmac("sha256", process.env.PERKMINER_SALES_KEY).update(ts + "." + body).digest("hex");
  const res = await fetch("https://www.perkminer.com/api/external_sale/confirm", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-PerkMiner-Business": process.env.PERKMINER_BUSINESS_ID,
      "X-PerkMiner-Timestamp": ts,
      "X-PerkMiner-Signature": sig
    },
    body
  });
  return { status: res.status, body: await res.json() };   // 200 = recorded (or already recorded). 402 = add funds, then retry.
}

D) Shopify

Shopify no longer allows custom scripts on its Thank-you page, so Shopify tells Perk Miner about the sale itself with a signed webhook. No code is needed except one small snippet that attaches the member's token to the cart.
  1. Add Script A (above) to your theme (theme.liquid, inside <head>).
  2. Right below it add this snippet, which attaches the token to the cart so it appears on the order:
<script>
(function () {
  try {
    var s = JSON.parse(localStorage.getItem("perk_token") || "null");
    if (!s || !s.t || Date.now() - s.at > 86400000) return;
    if (sessionStorage.getItem("perk_cart_attr") === s.t) return;
    fetch("/cart/update.js", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ attributes: { perk_token: s.t } })
    }).then(function (r) { if (r.ok) sessionStorage.setItem("perk_cart_attr", s.t); });
  } catch (e) {}
})();
</script>
  1. In Shopify admin go to Settings → Notifications → Webhooks → Create webhook. Event: Order payment. Format: JSON. URL: https://www.perkminer.com/api/external_sale/shopify/YOUR_BUSINESS_ID
  2. At the bottom of that Webhooks page Shopify shows “Your webhooks will be signed with …”. Copy that code and paste it below.

Log in as your business to save the Shopify signing secret.

4 Script B (optional) — send customers to their Perk Miner receipt

Add to your order confirmation (“thank you”) page on custom sites and WooCommerce. It sends no amount; it only waits until Perk Miner LLC has recorded the sale (usually a few seconds) and then opens the member's receipt. Not available on Shopify, where members see their cash back in their Perk Miner account.

<script>
(function () {
  function getToken() {
    var u = new URLSearchParams(window.location.search || "").get("perk_token");
    if (u) return u;
    try {
      var s = JSON.parse(localStorage.getItem("perk_token") || "null");
      if (s && s.t && Date.now() - s.at < 86400000) return s.t;
    } catch (e) {}
    var m = document.cookie.match(/(?:^|; )perk_token=([^;]*)/);
    return m ? decodeURIComponent(m[1]) : null;
  }
  var token = getToken();
  if (!token) return;                         // not a Perk Miner customer
  var tries = 0;
  function check() {
    fetch("https://www.perkminer.com/api/record_external_sale", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ perk_token: token })
    })
    .then(function (r) { return r.json(); })
    .then(function (d) {
      if (d && d.status === "ok") {
        try { localStorage.removeItem("perk_token"); } catch (e) {}
        document.cookie = "perk_token=; path=/; max-age=0";
        if (d.receipt_url) window.location.href = d.receipt_url;
      } else if (d && d.status === "pending" && ++tries < 8) {
        setTimeout(check, 2500);
      }
    })
    .catch(function () {});
  }
  setTimeout(check, 1500);
})();
</script>

5 Test your connection

Perk Miner LLC's team confirms your store by seeing a signed test ping from it. Send one after installing:

KEY="YOUR_SALES_KEY"; BIZ="YOUR_BUSINESS_ID"
TS=$(date +%s); BODY='{"ping":true}'
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$KEY" | awk '{print $NF}')
curl -s -X POST https://www.perkminer.com/api/ecommerce/verify-beacon \
  -H "Content-Type: application/json" -H "X-PerkMiner-Business: $BIZ" \
  -H "X-PerkMiner-Timestamp: $TS" -H "X-PerkMiner-Signature: $SIG" -d "$BODY"

Replies: {"ok":true} = connected. bad signature = wrong Sales Key or the body was changed after signing. timestamp too old = your server clock is off by more than 5 minutes.

What the server replies

Important terms and compliance

For questions or help with installation, please contact support@perkminer.com.