do_snapshot( $order ); } public function snapshot_block( $order ) { $this->do_snapshot( $order ); if ( is_a( $order, 'WC_Order' ) ) { $order->save_meta_data(); } } private function do_snapshot( $order ) { if ( ! is_a( $order, 'WC_Order' ) ) { return; } if ( class_exists( 'AIEO_Session_Tracker' ) && method_exists( 'AIEO_Session_Tracker', 'is_marketing_consent_blocking' ) && AIEO_Session_Tracker::is_marketing_consent_blocking() ) { return; } $gclid = $this->gclid_from_cookie(); if ( '' === $gclid ) { $gclid = $this->gclid_from_session( $order ); } if ( '' !== $gclid ) { $order->update_meta_data( self::GCLID_META, $gclid ); } } private function gclid_from_cookie() { if ( ! empty( $_COOKIE['_gcl_aw'] ) ) { $raw = sanitize_text_field( wp_unslash( $_COOKIE['_gcl_aw'] ) ); $parts = explode( '.', $raw ); if ( count( $parts ) >= 3 ) { return implode( '.', array_slice( $parts, 2 ) ); } } if ( ! empty( $_GET['gclid'] ) ) { return sanitize_text_field( wp_unslash( $_GET['gclid'] ) ); } return ''; } private function gclid_from_session( $order ) { global $wpdb; $sid = ''; foreach ( array( 'aieo_attr_sid', 'aieo_session_id' ) as $ck ) { if ( ! empty( $_COOKIE[ $ck ] ) ) { $sid = self::visitor_id_of( wp_unslash( $_COOKIE[ $ck ] ) ); if ( '' !== $sid ) { break; } } } if ( '' === $sid ) { return ''; } $statics = $wpdb->prefix . 'aieo_sessions_statics'; $row = $wpdb->get_row( $wpdb->prepare( "SELECT entry_click_id, entry_channel FROM `{$statics}` WHERE session_id = %s LIMIT 1", $sid ), ARRAY_A ); if ( $row && ! empty( $row['entry_click_id'] ) && 'paid_google' === ( $row['entry_channel'] ?? '' ) ) { return (string) $row['entry_click_id']; } return ''; } public function maybe_send( $order_id ) { $order_id = (int) $order_id; if ( $order_id <= 0 || ! function_exists( 'wc_get_order' ) ) { return; } $config = self::config(); $outbox = class_exists( 'AIEO_Outbox', false ) && AIEO_Outbox::on(); if ( ! self::enabled( $config ) || ( ! $outbox && self::consent_blocks() ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order || $order->get_meta( self::SENT_META ) ) { return; } if ( '' === (string) $order->get_meta( self::GCLID_META ) ) { return; } if ( $outbox ) { AIEO_Outbox::put_purchase( 'google_ads', $order ); return; } if ( isset( self::$enqueued[ $order_id ] ) ) { return; } self::$enqueued[ $order_id ] = true; if ( function_exists( 'aieo_server_event_dispatch' ) ) { aieo_server_event_dispatch( self::ASYNC_HOOK, $order_id ); } elseif ( function_exists( 'as_enqueue_async_action' ) ) { as_enqueue_async_action( self::ASYNC_HOOK, array( $order_id ), 'aieo-server-events' ); } else { wp_schedule_single_event( time() + 1, self::ASYNC_HOOK, array( $order_id ) ); } } public function send_conversion( $order_id, $outbox = false ) { $order_id = (int) $order_id; $outbox = true === $outbox; $off = array( 'code' => 0, 'verdict' => 'dead', 'error' => 'off', 'tried' => false ); $gone = array( 'code' => 0, 'verdict' => 'dead', 'error' => 'gone', 'tried' => false ); if ( $order_id <= 0 || ! function_exists( 'wc_get_order' ) ) { return $gone; } $config = self::config(); if ( ! self::enabled( $config ) || ( ! $outbox && self::consent_blocks() ) ) { return $off; } $order = wc_get_order( $order_id ); if ( ! $order ) { return $gone; } $gclid = (string) $order->get_meta( self::GCLID_META ); if ( '' === $gclid ) { return $gone; } if ( $outbox && $order->get_meta( self::SENT_META ) ) { return array( 'code' => 0, 'verdict' => 'sent', 'error' => '', 'tried' => false ); } $token = $this->access_token( $config ); if ( '' === $token ) { $this->log( $order, 'failed', 0, 'OAuth token request failed' ); if ( $this->token_status >= 400 && $this->token_status < 500 ) { return array( 'code' => $this->token_status, 'verdict' => 'pause', 'error' => 'credential' ); } return array( 'code' => $this->token_status, 'verdict' => 'failed', 'error' => 'token' ); } $payload = $this->build_payload( $order, $gclid, $config ); $customer_id = preg_replace( '/[^0-9]/', '', (string) $config['ads_customer_id'] ); $url = self::API_BASE . '/customers/' . $customer_id . ':uploadClickConversions'; $headers = array( 'Authorization' => 'Bearer ' . $token, 'developer-token' => (string) $config['ads_developer_token'], 'Content-Type' => 'application/json', ); if ( ! empty( $config['ads_login_customer_id'] ) ) { $headers['login-customer-id'] = preg_replace( '/[^0-9]/', '', (string) $config['ads_login_customer_id'] ); } $blocking = (bool) apply_filters( 'aieo_server_event_blocking', true, 'google_ads' ); $resp = wp_remote_post( $url, array( 'timeout' => 6, 'blocking' => $blocking, 'headers' => $headers, 'body' => wp_json_encode( $payload ), ) ); if ( ! $blocking ) { if ( function_exists( 'aieo_server_event_log_dispatched' ) ) { aieo_server_event_log_dispatched( 'google_ads', 'conversion', $order, (string) $order->get_id() ); } return array( 'code' => 0, 'verdict' => 'sent', 'error' => 'unconfirmed' ); } if ( is_wp_error( $resp ) ) { $this->log( $order, 'failed', 0, $resp->get_error_message() ); return array( 'code' => 0 ); } $code = (int) wp_remote_retrieve_response_code( $resp ); $body = (string) wp_remote_retrieve_body( $resp ); $status = ( $code >= 200 && $code < 300 && false === strpos( $body, 'partialFailureError' ) ) ? 'sent' : 'failed'; $this->log( $order, $status, $code, $body ); if ( 'sent' === $status ) { $order->update_meta_data( self::SENT_META, 1 ); $order->save(); } if ( 'sent' !== $status && $code >= 200 && $code < 300 ) { return array( 'code' => $code, 'verdict' => 'failed', 'error' => 'refused' ); } if ( 400 === $code && ( false !== strpos( $body, 'authenticationError' ) || false !== strpos( $body, 'authorizationError' ) ) ) { return array( 'code' => $code, 'verdict' => 'pause', 'error' => 'credential' ); } return array( 'code' => $code ); } private function access_token( array $c ) { $this->token_status = 0; $resp = wp_remote_post( self::TOKEN_ENDPOINT, array( 'timeout' => 10, 'body' => array( 'client_id' => (string) $c['ads_oauth_client_id'], 'client_secret' => (string) $c['ads_oauth_client_secret'], 'refresh_token' => (string) $c['ads_oauth_refresh_token'], 'grant_type' => 'refresh_token', ), ) ); if ( is_wp_error( $resp ) ) { return ''; } $this->token_status = (int) wp_remote_retrieve_response_code( $resp ); $data = json_decode( (string) wp_remote_retrieve_body( $resp ), true ); return ( is_array( $data ) && ! empty( $data['access_token'] ) ) ? (string) $data['access_token'] : ''; } public function build_payload( $order, $gclid, array $c ) { $customer_id = preg_replace( '/[^0-9]/', '', (string) $c['ads_customer_id'] ); $action_id = preg_replace( '/[^0-9]/', '', (string) $c['ads_conversion_action_id'] ); $dt = $order->get_date_created(); $when = $dt ? $dt->format( 'Y-m-d H:i:sP' ) : gmdate( 'Y-m-d H:i:s+00:00' ); $ids = class_exists( 'AIEO_PII_Hasher' ) ? AIEO_PII_Hasher::google_ads_user_identifiers( $order ) : array(); $conversion = array( 'gclid' => $gclid, 'conversionAction' => 'customers/' . $customer_id . '/conversionActions/' . $action_id, 'conversionDateTime' => $when, 'conversionValue' => (float) $order->get_total(), 'currencyCode' => (string) $order->get_currency(), 'orderId' => (string) $order->get_id(), ); if ( ! empty( $ids ) ) { $conversion['userIdentifiers'] = $ids; } if ( class_exists( 'AIEO_Consent' ) ) { $cs = AIEO_Consent::ads_consent_for_order( $order ); $map = array( 'granted' => 'GRANTED', 'denied' => 'DENIED', 'unspecified' => 'UNSPECIFIED' ); $cv = isset( $map[ $cs ] ) ? $map[ $cs ] : 'UNSPECIFIED'; $conversion['consent'] = array( 'adUserData' => $cv, 'adPersonalization' => $cv, ); } return array( 'conversions' => array( $conversion ), 'partialFailure' => true, ); } private function log( $order, $status, $http_code, $response ) { global $wpdb; if ( ! function_exists( 'aieo_server_events_log_table' ) ) { return; } $t = aieo_server_events_log_table(); if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) { return; } $resp = (string) $response; $now = current_time( 'mysql', true ); $wpdb->query( $wpdb->prepare( "INSERT INTO `{$t}` (event_id, platform, event_name, order_id, status, http_code, attempts, response_body, error_message, value, currency, created_at, sent_at) VALUES (%s, %s, 'conversion', %d, %s, %d, 1, %s, %s, %f, %s, %s, %s) ON DUPLICATE KEY UPDATE status = VALUES(status), http_code = VALUES(http_code), attempts = attempts + 1, response_body = VALUES(response_body), error_message = VALUES(error_message), sent_at = VALUES(sent_at)", (string) $order->get_id(), self::PLATFORM, (int) $order->get_id(), $status, (int) $http_code, mb_substr( $resp, 0, 2000 ), ( 'sent' !== $status ) ? mb_substr( $resp, 0, 255 ) : '', (float) $order->get_total(), (string) $order->get_currency(), $now, $now ) ); } }