report_order((int) $order_id); } public function on_paid($order_id) { $this->report_order((int) $order_id); } public function on_cancelled($order_id) { $this->void_order((int) $order_id); } /** * Report an order as a confirmed sale (once). Reads the attribution captured * onto the order at checkout; falls back to the live cookie if absent. */ private function report_order($order_id) { if ($order_id <= 0) { return; } $order = wc_get_order($order_id); if (!$order) { return; } // Dedupe: only report once per order from the plugin side. if ($order->get_meta(self::REPORTED_META) === 'yes') { return; } $attr = $this->order_attribution($order); if (empty($attr['t'])) { // No affiliate attribution on this order — nothing to record. Mark it // so we don't re-evaluate on every status change. $order->update_meta_data(self::REPORTED_META, 'yes'); $order->save(); return; } $payload = array( 'site_url' => home_url(), 'order_id' => (string) $order->get_id(), 'order_number' => (string) $order->get_order_number(), 'total_amount' => (float) $order->get_total(), 'currency' => $order->get_currency(), 'voided' => false, 'attribution' => array_filter(array( 't' => $attr['t'], 'd' => $attr['d'], 'cid' => $attr['cid'], ), function ($v) { return $v !== '' && $v !== null; }), 'customer_email' => $order->get_billing_email(), 'landing_site' => $attr['landing'], ); $res = Adverships_Affiliate_Client::post_signed('/api/wordpress/order_webhook.php', $payload, true); // Mark reported unless the call hard-failed (transport error) — in which // case leave it unflagged so a later status transition retries. if (!is_wp_error($res)) { $order->update_meta_data(self::REPORTED_META, 'yes'); } $order->save(); } /** Void a previously-reported order (cancellation). */ private function void_order($order_id) { if ($order_id <= 0) { return; } $order = wc_get_order($order_id); if (!$order) { return; } $attr = $this->order_attribution($order); if (empty($attr['t'])) { return; // Was never attributed; nothing to void. } $payload = array( 'site_url' => home_url(), 'order_id' => (string) $order->get_id(), 'voided' => true, 'attribution' => array('t' => $attr['t']), ); Adverships_Affiliate_Client::post_signed('/api/wordpress/order_webhook.php', $payload, true); } /** * Resolve attribution for an order: prefer the meta captured at checkout, * fall back to the current request cookie. * @param WC_Order $order * @return array ['t','d','cid','landing'] */ private function order_attribution($order) { $t = (string) $order->get_meta('_adverships_t'); $d = (string) $order->get_meta('_adverships_d'); $cid = (string) $order->get_meta('_adverships_cid'); $landing = (string) $order->get_meta('_adverships_landing'); if ($t === '') { $cookie = Adverships_Affiliate_Tracking::read_cookie_attribution(); $t = $cookie['t']; $d = $cookie['d']; $cid = $cookie['cid']; if ($landing === '') { $landing = $cookie['landing']; } } return array('t' => $t, 'd' => $d, 'cid' => $cid, 'landing' => $landing); } }