0,
'program_id' => 0,
'merchant_id' => 0,
'api_public_key' => '',
'api_secret_key' => '',
'test_token' => '',
'enable_browser' => 1,
'enable_s2s' => 1,
];
$saved = get_option(self::OPTION_KEY, []);
return is_array($saved) ? array_merge($defaults, $saved) : $defaults;
}
public function adminMenu(): void
{
add_options_page(
'Affillo Tracking',
'Affillo Tracking',
'manage_options',
'affillo-tracking',
[$this, 'renderSettingsPage']
);
}
public function settingsLink(array $links): array
{
$url = admin_url('options-general.php?page=affillo-tracking');
array_unshift($links, '' . esc_html__('Settings', 'affillo-tracking-for-woocommerce') . '');
return $links;
}
public function registerSettings(): void
{
register_setting('affillo_tracking', self::OPTION_KEY, [
'type' => 'array',
'sanitize_callback' => [$this, 'sanitizeSettings'],
]);
}
/**
* @param mixed $input
*/
public function sanitizeSettings($input): array
{
$current = $this->settings();
$input = is_array($input) ? $input : [];
$clean = [
'enable_tracking' => !empty($input['enable_tracking']) ? 1 : 0,
'program_id' => max(0, (int) ($input['program_id'] ?? 0)),
'merchant_id' => max(0, (int) ($input['merchant_id'] ?? 0)),
'api_public_key' => sanitize_text_field((string) ($input['api_public_key'] ?? '')),
'test_token' => sanitize_text_field((string) ($input['test_token'] ?? '')),
'enable_browser' => !empty($input['enable_browser']) ? 1 : 0,
'enable_s2s' => !empty($input['enable_s2s']) ? 1 : 0,
];
/*
* Secret key: the form field is always blank on render (never echo the
* secret back into HTML). An empty submission keeps the stored value.
*/
$newSecret = trim((string) ($input['api_secret_key'] ?? ''));
$clean['api_secret_key'] = $newSecret !== ''
? sanitize_text_field($newSecret)
: (string) $current['api_secret_key'];
return $clean;
}
public function renderSettingsPage(): void
{
if (!current_user_can('manage_options')) {
return;
}
$s = $this->settings();
$hasSecret = $s['api_secret_key'] !== '';
?>
Affillo Tracking for WooCommerce
Enter the details from your Affillo merchant portal (Tracking page),
then switch tracking on. Tracking is off by default -
until you enable it below, this plugin loads nothing on your site and
sends no data anywhere. The secret key is stored server-side only and
is never exposed to visitors.
settings();
return (int) $s['enable_tracking'] === 1 && (int) $s['program_id'] > 0;
}
public function enqueueTracking(): void
{
if (!$this->trackingActive()) {
return;
}
$s = $this->settings();
wp_enqueue_script('affillo-tracking', self::SCRIPT_URL, [], '6', false);
/*
* Order thank-you page: queue the browser conversion event through
* the tracker's async queue (window.Affillo.push) - the queue pattern
* is order-independent, so 'before' placement is safe alongside the
* deferred external script.
*/
if ((int) $s['enable_browser'] !== 1) {
return;
}
$order = $this->orderFromReceivedEndpoint();
if (!$order) {
return;
}
$payload = [
'event' => 'conversion',
'orderRef' => (string) $order->get_order_number(),
'amount' => (float) $order->get_total(),
'currency' => (string) $order->get_currency(),
'coupon' => implode(',', $order->get_coupon_codes()),
'items' => $this->orderItems($order),
'meta' => ['source' => 'woocommerce_thank_you'],
];
wp_add_inline_script(
'affillo-tracking',
'window.Affillo = window.Affillo || []; window.Affillo.push(' . wp_json_encode($payload) . ');',
'before'
);
}
/**
* The tracker script is attribute-configured, so its enqueued tag needs
* the data-* attributes (and defer) added back.
*/
public function filterScriptTag(string $tag, string $handle): string
{
if ($handle !== 'affillo-tracking') {
return $tag;
}
$s = $this->settings();
$attrs = ' defer data-program="' . esc_attr((string) (int) $s['program_id']) . '"';
if ($s['test_token'] !== '') {
$attrs .= ' data-test-token="' . esc_attr($s['test_token']) . '"';
}
$attrs .= ' data-source="atm" data-transport="auto" data-mirror="0" data-pixel="0" data-pixel-conversion="0"';
return str_replace(' src=', $attrs . ' src=', $tag);
}
/**
* The order on the order-received endpoint, verified against the order
* key in the URL so totals are only exposed to the customer who owns
* the order.
*
* @return \WC_Order|null
*/
private function orderFromReceivedEndpoint()
{
if (!function_exists('is_wc_endpoint_url') || !is_wc_endpoint_url('order-received') || !function_exists('wc_get_order')) {
return null;
}
global $wp;
$orderId = absint($wp->query_vars['order-received'] ?? 0);
if ($orderId <= 0) {
return null;
}
$order = wc_get_order($orderId);
if (!$order) {
return null;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only key comparison on a WooCommerce endpoint.
$key = isset($_GET['key']) ? sanitize_text_field(wp_unslash((string) $_GET['key'])) : '';
if ($key === '' || !hash_equals($order->get_order_key(), $key)) {
return null;
}
return $order;
}
// ------------------------------------------------------------------
// Attribution capture at checkout
// ------------------------------------------------------------------
/**
* Cookies exist only in the CUSTOMER's checkout request. By the time the
* order is marked Completed (admin/cron context) they are gone - so we
* snapshot them onto the order now and replay them in the S2S call.
*
* @param \WC_Order $order
*/
public function captureAttributionOnOrder($order): void
{
if (!$this->trackingActive()) {
return;
}
if (!is_object($order) || !method_exists($order, 'update_meta_data')) {
return;
}
$map = [
'aff_click_id' => '_affillo_click_id',
'aff_sid' => '_affillo_sid',
'aff_coupon' => '_affillo_coupon',
'aff_dev_fp' => '_affillo_device_fp',
];
foreach ($map as $cookie => $metaKey) {
if (!empty($_COOKIE[$cookie])) {
$order->update_meta_data(
$metaKey,
sanitize_text_field(wp_unslash((string) $_COOKIE[$cookie]))
);
}
}
}
/**
* Blocks (Store API) checkout variant - receives the order object or id.
*
* @param mixed $order
*/
public function captureAttributionOnOrderById($order): void
{
if (is_numeric($order) && function_exists('wc_get_order')) {
$order = wc_get_order((int) $order);
}
if ($order && is_object($order) && method_exists($order, 'save')) {
$this->captureAttributionOnOrder($order);
$order->save();
}
}
// ------------------------------------------------------------------
// S2S conversion (signed)
// ------------------------------------------------------------------
/**
* @param int|string $order_id
*/
public function queueS2SConversion($order_id): void
{
$s = $this->settings();
if (!$this->trackingActive() || (int) $s['enable_s2s'] !== 1) {
return;
}
// Send inline; on transport failure a retry is scheduled.
$this->sendS2SConversion((int) $order_id);
}
public function sendS2SConversion(int $order_id): void
{
$s = $this->settings();
if (
!$this->trackingActive()
|| (int) $s['enable_s2s'] !== 1
|| (int) $s['program_id'] <= 0
|| $s['api_public_key'] === ''
|| $s['api_secret_key'] === ''
|| !function_exists('wc_get_order')
) {
return;
}
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// Never double-send.
if ($order->get_meta('_affillo_s2s_sent_at')) {
return;
}
$attempts = (int) $order->get_meta('_affillo_s2s_attempts');
$orderRef = (string) $order->get_order_number();
$amount = (float) $order->get_total();
$currency = strtoupper((string) $order->get_currency());
$occurredAt = gmdate('c');
/*
* The canonical string must byte-match the server side, which signs
* with the merchant id - so it is a required setting (shown next to
* the API keys in the Affillo portal).
*/
$merchantId = (int) $s['merchant_id'];
if ($merchantId <= 0) {
$order->add_order_note('Affillo: S2S conversion skipped - Merchant ID missing in Settings > Affillo Tracking.');
return;
}
$canonical = implode('|', [
(string) $merchantId,
$orderRef,
(string) $amount,
$currency,
'sale',
$occurredAt,
]);
$signature = hash_hmac('sha256', $canonical, (string) $s['api_secret_key']);
$emailHash = '';
$billing = strtolower(trim((string) $order->get_billing_email()));
if ($billing !== '') {
$emailHash = hash('sha256', $billing);
}
$payload = [
'program_id' => (int) $s['program_id'],
'merchant_id' => $merchantId,
'order_id' => $orderRef,
'amount' => $amount,
'currency' => $currency,
'event_type' => 'sale',
'occurred_at' => $occurredAt,
'source' => 's2s',
'coupon' => implode(',', $order->get_coupon_codes())
?: (string) $order->get_meta('_affillo_coupon'),
'items' => $this->orderItems($order),
];
$clickId = (int) $order->get_meta('_affillo_click_id');
if ($clickId > 0) {
$payload['click_id'] = $clickId;
}
$sid = (string) $order->get_meta('_affillo_sid');
if ($sid !== '') {
$payload['sid'] = $sid;
}
$deviceFp = (string) $order->get_meta('_affillo_device_fp');
if ($deviceFp !== '') {
$payload['device_fingerprint'] = $deviceFp;
}
if ($emailHash !== '') {
$payload['identity'] = ['email_sha256' => $emailHash];
}
$response = wp_remote_post(self::S2S_ENDPOINT, [
'timeout' => 15,
'headers' => [
'Content-Type' => 'application/json',
'X-Affillo-Key' => (string) $s['api_public_key'],
'X-Affillo-Signature' => $signature,
],
'body' => wp_json_encode($payload),
'sslverify' => true,
]);
if (is_wp_error($response)) {
$this->scheduleRetry($order, $attempts, $response->get_error_message());
return;
}
$code = (int) wp_remote_retrieve_response_code($response);
$body = (string) wp_remote_retrieve_body($response);
if ($code >= 200 && $code < 300) {
$order->update_meta_data('_affillo_s2s_sent_at', gmdate('c'));
$order->delete_meta_data('_affillo_s2s_attempts');
$order->save();
$order->add_order_note('Affillo: conversion sent via signed S2S postback.');
return;
}
/*
* 4xx = our request is wrong (bad keys/signature) - retrying will not
* help, so surface it in an order note instead of looping.
*/
if ($code >= 400 && $code < 500) {
$order->add_order_note(
'Affillo: S2S conversion rejected (HTTP ' . $code . '). Check the API keys in Settings > Affillo Tracking. Response: '
. substr(wp_strip_all_tags($body), 0, 200)
);
$order->update_meta_data('_affillo_s2s_attempts', self::MAX_RETRIES);
$order->save();
return;
}
$this->scheduleRetry($order, $attempts, 'HTTP ' . $code);
}
private function scheduleRetry(\WC_Order $order, int $attempts, string $reason): void
{
$attempts++;
$order->update_meta_data('_affillo_s2s_attempts', $attempts);
$order->save();
if ($attempts >= self::MAX_RETRIES) {
$order->add_order_note('Affillo: S2S conversion failed after ' . $attempts . ' attempts (' . esc_html($reason) . ').');
return;
}
wp_schedule_single_event(time() + 300 * $attempts, 'affillo_tracking_send_s2s', [$order->get_id()]);
}
// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------
/**
* @param \WC_Order $order
*/
private function orderItems($order): array
{
$items = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$qty = max(1, (int) $item->get_quantity());
$lineTotal = (float) $item->get_total();
$items[] = [
'item_id' => $product && $product->get_sku() ? $product->get_sku() : (string) $item->get_product_id(),
'item_name' => (string) $item->get_name(),
'price' => $qty > 0 ? round($lineTotal / $qty, 2) : 0,
'quantity' => $qty,
];
}
return $items;
}
}
Affillo_Tracking::instance();