id = 'agentaos';
$this->icon = AGENTAOS_PAYMENTS_URL . 'assets/images/agentaos-mark.png';
$this->has_fields = false;
$this->method_title = __( 'AgentaOS', 'agentaos-payments' );
$this->method_description = __( 'Card, Apple Pay and Google Pay. AgentaOS is the merchant of record: VAT, invoices and payouts handled.', 'agentaos-payments' );
$this->supports = array( 'products' );
$this->init_form_fields();
$this->init_settings();
$this->migrate_single_key();
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$mode = 'live' === $this->get_option( 'mode' ) ? 'live' : 'test';
$this->api_key = trim( (string) $this->get_option( $mode . '_api_key' ) );
$this->webhook_secret = trim( (string) $this->get_option( $mode . '_webhook_secret' ) );
$this->debug = 'yes' === $this->get_option( 'debug' );
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'confirm_on_return' ), 5 );
}
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable', 'agentaos-payments' ),
'type' => 'checkbox',
'label' => __( 'Take payments with AgentaOS', 'agentaos-payments' ),
'default' => 'no',
),
'title' => array(
'title' => __( 'Title', 'agentaos-payments' ),
'type' => 'text',
'description' => __( 'What buyers see at checkout.', 'agentaos-payments' ),
'default' => __( 'Card, Apple Pay or Google Pay', 'agentaos-payments' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Description', 'agentaos-payments' ),
'type' => 'textarea',
'default' => __( 'You will pay on a secure AgentaOS checkout. Your VAT or sales tax is added there.', 'agentaos-payments' ),
),
'mode' => array(
'title' => __( 'Mode', 'agentaos-payments' ),
'type' => 'select',
'options' => array(
'test' => __( 'Test (no real money)', 'agentaos-payments' ),
'live' => __( 'Live', 'agentaos-payments' ),
),
'default' => 'test',
/* translators: %s: webhook URL of this store */
'description' => '' . esc_html__( 'Get your API keys', 'agentaos-payments' ) . '
'
/* translators: %s: webhook URL of this store */
. sprintf( __( 'In AgentaOS, open Settings, Developers. Copy a secret key from API Keys. Under Webhooks, set the webhook URL to %s, click Reveal signing secret and paste the whsec_... value below.', 'agentaos-payments' ), '' . esc_html( AgentaOS_Webhook::url() ) . '' ),
),
'test_api_key' => array(
'title' => __( 'Test secret key', 'agentaos-payments' ),
'type' => 'password',
'default' => '',
'placeholder' => 'sk_test_...',
),
'test_webhook_secret' => array(
'title' => __( 'Test webhook signing secret', 'agentaos-payments' ),
'type' => 'password',
'default' => '',
'placeholder' => 'whsec_...',
),
'live_api_key' => array(
'title' => __( 'Live secret key', 'agentaos-payments' ),
'type' => 'password',
'default' => '',
'placeholder' => 'sk_live_...',
),
'live_webhook_secret' => array(
'title' => __( 'Live webhook signing secret', 'agentaos-payments' ),
'type' => 'password',
'default' => '',
'placeholder' => 'whsec_...',
),
'subscriptions' => array(
'title' => __( 'Subscriptions', 'agentaos-payments' ),
'type' => 'checkbox',
'label' => __( 'Sell products as subscriptions billed by AgentaOS (adds an "AgentaOS subscription" option to each product). Turning this off keeps existing subscribers renewing and able to cancel.', 'agentaos-payments' ),
'default' => 'yes',
),
'checkout_style' => array(
'title' => __( 'Checkout style', 'agentaos-payments' ),
'type' => 'select',
'options' => array(
'redirect' => __( 'AgentaOS checkout page', 'agentaos-payments' ),
'overlay' => __( 'Over your store (buyers stay on your site)', 'agentaos-payments' ),
),
'default' => 'redirect',
'description' => __( 'For the overlay, add your site under Settings, Developers, Approved sites in the AgentaOS dashboard. Until then buyers are sent to the checkout page.', 'agentaos-payments' ),
),
'buy_now' => array(
'title' => __( 'Buy now button', 'agentaos-payments' ),
'type' => 'checkbox',
'label' => __( 'Show a Buy now button on digital product pages that goes straight to checkout', 'agentaos-payments' ),
'default' => 'no',
),
'powered_by' => array(
'title' => __( 'Powered by AgentaOS', 'agentaos-payments' ),
'type' => 'checkbox',
'label' => __( 'Show "Powered by AgentaOS" with a link to agentaos.ai under this payment method at checkout', 'agentaos-payments' ),
'default' => 'no',
),
'debug' => array(
'title' => __( 'Debug log', 'agentaos-payments' ),
'type' => 'checkbox',
'label' => __( 'Log checkout and webhook events (WooCommerce, Status, Logs). Keys are never logged.', 'agentaos-payments' ),
'default' => 'no',
),
);
// The exchange rate only matters for stores priced in MKD, RSD or ALL.
if ( in_array( get_woocommerce_currency(), AgentaOS_Currency::MERCHANT_RATE, true ) ) {
$this->form_fields = array_merge(
array_slice( $this->form_fields, 0, 8, true ),
array(
'settlement_currency' => array(
'title' => __( 'Charge in', 'agentaos-payments' ),
'type' => 'select',
'options' => array(
'EUR' => 'EUR',
'USD' => 'USD',
),
'default' => 'EUR',
'description' => __( 'The currency buyers are charged in. Your store prices are converted with the exchange rate below.', 'agentaos-payments' ),
),
'rate' => array(
'title' => __( 'Exchange rate', 'agentaos-payments' ),
'type' => 'text',
'default' => '',
'placeholder' => '61.5',
'description' => __( 'For MKD, RSD or ALL stores: how many units of your store currency equal 1 EUR (or 1 USD). Check it at least monthly; after 90 days without an update the payment method hides until you save a new rate.', 'agentaos-payments' ),
),
),
array_slice( $this->form_fields, 8, null, true )
);
}
}
/**
* Only offer the method when it is configured, the store sells in EUR or USD, and the cart holds
* only virtual or downloadable products. AgentaOS sells digital products and digital services;
* physical or shipped goods are not allowed under its terms.
*
* @return bool
*/
public function is_available() {
if ( ! $this->is_ready() ) {
return false;
}
// On the "Pay for order" page (orders created by the store, bookings, auctions) the cart is empty:
// check the order instead.
if ( function_exists( 'is_checkout_pay_page' ) && is_checkout_pay_page() ) {
$order = wc_get_order( absint( get_query_var( 'order-pay' ) ) );
return $order && self::order_is_digital( $order );
}
// Older WooCommerce asks block payment methods early, before the cart is loaded.
if ( did_action( 'wp_loaded' ) && function_exists( 'WC' ) && WC()->cart && ! self::cart_is_digital( WC()->cart ) ) {
return false;
}
return true;
}
/**
* Checks the products themselves rather than needs_shipping(), which is false whenever the store
* has shipping turned off.
*
* @param WC_Cart $cart Cart.
* @return bool True when the cart is empty or every product is virtual or downloadable.
*/
public static function cart_is_digital( WC_Cart $cart ) {
foreach ( $cart->get_cart() as $item ) {
$product = isset( $item['data'] ) ? $item['data'] : null;
if ( ! $product instanceof WC_Product || ! ( $product->is_virtual() || $product->is_downloadable() ) ) {
return false;
}
}
return true;
}
/**
* @return bool True when the method is enabled, has keys for its mode and the currency is supported.
*/
public function is_ready() {
return parent::is_available() && '' !== $this->api_key && '' !== $this->webhook_secret && $this->currency_supported();
}
/**
* @return bool True when AgentaOS can charge in the store currency right now.
*/
public function currency_supported() {
return null !== $this->settlement( '1' );
}
/**
* @param string $total Amount in the store currency.
* @return array{amount:string,currency:string}|null What AgentaOS will charge, or null when it cannot.
*/
public function settlement( $total, $currency = null ) {
return AgentaOS_Currency::settlement(
(string) $total,
null === $currency ? get_woocommerce_currency() : (string) $currency,
(string) $this->get_option( 'settlement_currency', 'EUR' ),
(float) str_replace( ',', '.', (string) $this->get_option( 'rate' ) ),
(int) $this->get_option( 'rate_saved_at', 0 ),
time()
);
}
/**
* Remember when the exchange rate was last confirmed: every save with a rate restarts the 90-day clock.
*
* @return bool
*/
public function process_admin_options() {
$saved = parent::process_admin_options();
if ( '' !== trim( (string) $this->get_option( 'rate' ) ) ) {
$this->update_option( 'rate_saved_at', time() );
}
return $saved;
}
/**
* Classic checkout: description plus the exact amount when the store currency is converted.
*/
/**
* @return string[] The AgentaOS mark and the card brands, as image URLs.
*/
public function icon_urls() {
return array(
'AgentaOS' => AGENTAOS_PAYMENTS_URL . 'assets/images/agentaos-mark.png',
'Visa' => WC()->plugin_url() . '/assets/images/icons/credit-cards/visa.svg',
'Mastercard' => WC()->plugin_url() . '/assets/images/icons/credit-cards/mastercard.svg',
);
}
/**
* @return string
*/
public function get_icon() {
$html = '';
foreach ( $this->icon_urls() as $alt => $url ) {
$html .= '';
}
return apply_filters( 'woocommerce_gateway_icon', $html, $this->id ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own filter for gateway icons.
}
/**
* @return string The opt-in credit line, or '' when the merchant has not turned it on.
*/
public function powered_by() {
if ( 'yes' !== $this->get_option( 'powered_by' ) ) {
return '';
}
return sprintf(
/* translators: %s: link to agentaos.ai */
esc_html__( 'Powered by %s', 'agentaos-payments' ),
'AgentaOS'
);
}
public function payment_fields() {
parent::payment_fields();
$total = WC()->cart ? WC()->cart->get_total( 'edit' ) : null;
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$order = wc_get_order( absint( get_query_var( 'order-pay' ) ) );
$total = $order ? $order->get_total() : null;
}
$notice = $this->conversion_notice( $total );
if ( '' !== $notice ) {
echo '
' . esc_html( $notice ) . '
'; } $powered = $this->powered_by(); if ( '' !== $powered ) { echo '' . wp_kses( $powered, array( 'a' => array( 'href' => true, 'target' => true, 'rel' => true, ), ) ) . '
'; } } /** * @param string|null $total Store-currency total, or null to describe the rate only (block checkout). * @return string Empty for EUR and USD stores. */ public function conversion_notice( $total = null ) { $store = get_woocommerce_currency(); if ( in_array( $store, AgentaOS_Currency::DIRECT, true ) ) { return ''; } $unit = $this->settlement( '1' ); if ( ! $unit ) { return ''; } if ( null !== $total ) { $charge = $this->settlement( $total ); /* translators: 1: amount, 2: currency */ return sprintf( __( 'You will be charged %1$s %2$s, plus any VAT for your country.', 'agentaos-payments' ), $charge['amount'], $charge['currency'] ); } $rate = 'BAM' === $store ? AgentaOS_Currency::BAM_PER_EUR : (float) str_replace( ',', '.', (string) $this->get_option( 'rate' ) ); /* translators: 1: settlement currency, 2: rate, 3: store currency */ return sprintf( __( 'Charged in %1$s at 1 %1$s = %2$s %3$s, plus any VAT for your country.', 'agentaos-payments' ), $unit['currency'], $rate, $store ); } /** * @param WC_Order $order Order. * @return bool True when every line item is a virtual or downloadable product. */ public static function order_is_digital( WC_Order $order ) { foreach ( $order->get_items() as $item ) { $product = $item instanceof WC_Order_Item_Product ? $item->get_product() : null; if ( ! $product || ! ( $product->is_virtual() || $product->is_downloadable() ) ) { return false; } } return count( $order->get_items() ) > 0; } /** * Settings from 1.x had one key and one secret: move them to the slot their prefix names. */ private function migrate_single_key() { $old_key = isset( $this->settings['api_key'] ) ? trim( (string) $this->settings['api_key'] ) : ''; if ( '' === $old_key ) { return; } $mode = 0 === strpos( $old_key, 'sk_live_' ) ? 'live' : 'test'; $this->settings['mode'] = $mode; $this->settings[ $mode . '_api_key' ] = $old_key; $this->settings[ $mode . '_webhook_secret' ] = isset( $this->settings['webhook_secret'] ) ? $this->settings['webhook_secret'] : ''; unset( $this->settings['api_key'], $this->settings['webhook_secret'] ); update_option( $this->get_option_key(), $this->settings, 'yes' ); } /** * AJAX: checks the active key against the AgentaOS API. */ public static function ajax_test_connection() { check_ajax_referer( 'agentaos_test_connection' ); if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_send_json_error( __( 'Not allowed.', 'agentaos-payments' ), 403 ); } $gateway = new self(); if ( '' === $gateway->api_key ) { wp_send_json_error( __( 'Save a secret key for the selected mode first.', 'agentaos-payments' ) ); } try { $gateway->api()->ping(); } catch ( Exception $e ) { wp_send_json_error( $e->getMessage() ); } $mode = 0 === strpos( $gateway->api_key, 'sk_live_' ) ? __( 'live', 'agentaos-payments' ) : __( 'test', 'agentaos-payments' ); /* translators: %s: test or live */ wp_send_json_success( sprintf( __( 'Connected to AgentaOS in %s mode.', 'agentaos-payments' ), $mode ) ); } /** * Show a warning in the settings when something blocks the method from appearing. */ public function admin_options() { $mode = 'live' === $this->get_option( 'mode' ) ? 'live' : 'test'; if ( '' !== $this->api_key && 0 !== strpos( $this->api_key, 'sk_' . $mode . '_' ) ) { /* translators: %s: sk_test_ or sk_live_ */ echo '' . esc_html( sprintf( __( 'The key for this mode should start with %s.', 'agentaos-payments' ), 'sk_' . $mode . '_' ) ) . '
' . esc_html__( 'Your store address starts with http://. AgentaOS only sends buyers back to secure (https://) addresses, so payments cannot start. Turn on HTTPS (an SSL certificate) for your site; most hosts do this for free.', 'agentaos-payments' ) . '
' . esc_html__( 'AgentaOS charges in EUR or USD. Stores in MKD, RSD, ALL or BAM are converted; other store currencies are not supported.', 'agentaos-payments' ) . '
' . esc_html__( 'Enter an exchange rate (or update it: rates expire after 90 days) so the payment method shows at checkout.', 'agentaos-payments' ) . '
' . esc_html__( 'Your exchange rate is over 30 days old. Update it so buyers are charged the right amount.', 'agentaos-payments' ) . '
' . esc_html__( 'WooCommerce taxes are turned on. AgentaOS adds the buyer\'s VAT or sales tax at its checkout, so turn off taxes in WooCommerce, Settings, General, or buyers pay tax twice.', 'agentaos-payments' ) . '
' . esc_html__( 'AgentaOS sells digital products and digital services, such as software, downloads, courses, memberships and productized service packages. This method only appears when every product in the cart is virtual or downloadable; physical or shipped goods are not allowed.', 'agentaos-payments' ) . '
' . esc_html__( 'Test mode: payments are not real. Use card 4242 4242 4242 4242, any future expiry, any CVC.', 'agentaos-payments' ) . '
agent_panel(); } /** * "Connect your AI agent": how to connect the merchant's assistant to the AgentaOS MCP server. */ private function agent_panel() { $clients = array( __( 'Claude: Customize, Connectors, Add custom connector, then paste the address.', 'agentaos-payments' ), __( 'ChatGPT: Settings, Connectors, Create, then paste the address.', 'agentaos-payments' ), __( 'Cursor: Settings, MCP, Add server, with this address as the server URL.', 'agentaos-payments' ), __( 'Claude Code: run claude plugins marketplace add AgentaOS/agentaos, then claude plugins install agentaos@agentaos.', 'agentaos-payments' ), ); $prompts = array( __( 'How many active subscribers do I have, and who cancels at the end of this month?', 'agentaos-payments' ), __( 'Send the receipt for my last sale to the buyer again.', 'agentaos-payments' ), __( 'Which customers paid me this week?', 'agentaos-payments' ), ); ?> wp_create_nonce( 'agentaos_test_connection' ), 'checking' => __( 'Checking...', 'agentaos-payments' ), 'copied' => __( 'Copied', 'agentaos-payments' ), ); wp_register_script( 'agentaos-admin', '', array(), AGENTAOS_PAYMENTS_VERSION, true ); wp_enqueue_script( 'agentaos-admin' ); wp_add_inline_script( 'agentaos-admin', 'var agentaosAdmin = ' . wp_json_encode( $text ) . '; document.getElementById( "agentaos-test-connection" ).addEventListener( "click", function () { var out = document.getElementById( "agentaos-test-result" ); out.textContent = agentaosAdmin.checking; var body = new URLSearchParams( { action: "agentaos_test_connection", _ajax_nonce: agentaosAdmin.nonce } ); fetch( ajaxurl, { method: "POST", credentials: "same-origin", body: body } ) .then( function ( r ) { return r.json(); } ) .then( function ( r ) { out.textContent = r.data; out.style.color = r.success ? "#008a20" : "#d63638"; } ); } ); var agentaosMode = document.getElementById( "woocommerce_agentaos_mode" ); function agentaosShowModeKeys() { var live = "live" === agentaosMode.value; [ "test_api_key", "test_webhook_secret" ].forEach( function ( key ) { document.getElementById( "woocommerce_agentaos_" + key ).closest( "tr" ).style.display = live ? "none" : ""; } ); [ "live_api_key", "live_webhook_secret" ].forEach( function ( key ) { document.getElementById( "woocommerce_agentaos_" + key ).closest( "tr" ).style.display = live ? "" : "none"; } ); } agentaosMode.addEventListener( "change", agentaosShowModeKeys ); agentaosShowModeKeys(); document.getElementById( "agentaos-mcp-url" ).addEventListener( "focus", function () { this.select(); } ); document.getElementById( "agentaos-copy-mcp" ).addEventListener( "click", function () { var button = this; navigator.clipboard.writeText( document.getElementById( "agentaos-mcp-url" ).value ).then( function () { button.textContent = agentaosAdmin.copied; } ); } );' ); } /** * Create an AgentaOS checkout for the order and send the buyer to it. * * @param int $order_id Order ID. * @return array */ public function process_payment( $order_id ) { $order = wc_get_order( $order_id ); $attempt = (int) $order->get_meta( self::META_ATTEMPT ) + 1; if ( ! self::order_is_digital( $order ) ) { wc_add_notice( __( 'This payment method is for digital products and digital services only. Please choose another method.', 'agentaos-payments' ), 'error' ); return array( 'result' => 'failure' ); } $charge = $this->settlement( $order->get_total(), $order->get_currency() ); if ( ! $charge ) { wc_add_notice( __( 'This payment method is not available for this order. Please choose another method.', 'agentaos-payments' ), 'error' ); return array( 'result' => 'failure' ); } // A plan charges its AgentaOS price. Refuse when that is not what the order shows (sale price, // coupon) or when the plan was built for another mode, currency or rate. $plan = AgentaOS_Subscriptions::order_plan( $order ); if ( $plan && ! AgentaOS_Subscriptions::enabled() ) { wc_add_notice( __( 'This store is not selling subscriptions right now. Please contact the store.', 'agentaos-payments' ), 'error' ); return array( 'result' => 'failure' ); } if ( $plan && ! AgentaOS_Subscriptions::plan_matches( $plan, $charge, $this ) ) { $this->log( 'Plan checkout refused for order ' . $order->get_id() . ': the order price differs from the plan, or the plan is out of date (re-save the product).' ); wc_add_notice( __( 'This subscription cannot be bought right now: its price does not match the store (for example a sale price or coupon). Please contact the store.', 'agentaos-payments' ), 'error' ); return array( 'result' => 'failure' ); } $body = $this->checkout_body( $order, $charge ); try { // The key covers the whole request: a retry of the same request returns the same checkout, and a // changed cart or buyer after a lost response gets a new one. $checkout = $this->api()->create_checkout( $body, 'wc-' . $order->get_id() . '-' . $attempt . '-' . md5( wp_json_encode( $body ) ) ); } catch ( Exception $e ) { $this->log( 'Checkout creation failed for order ' . $order->get_id() . ': ' . $e->getMessage() ); wc_add_notice( __( 'We could not start the payment. Please try again or contact the store.', 'agentaos-payments' ), 'error' ); return array( 'result' => 'failure' ); } $order->update_meta_data( self::META_ATTEMPT, $attempt ); $order->delete_meta_data( self::META_TRANSACTION_ID ); // A new checkout is a new sale. // A buyer who clicks Place order again gets a new checkout; the earlier one stays payable for a // while, so remember it and accept its payment too. $previous = (string) $order->get_meta( self::META_SESSION_ID ); if ( '' !== $previous && $previous !== $checkout['session_id'] ) { $order->add_meta_data( self::META_OLD_SESSIONS, $previous ); } $order->update_meta_data( self::META_SESSION_ID, sanitize_text_field( $checkout['session_id'] ) ); $order->update_meta_data( self::META_AMOUNT, $charge['amount'] ); $order->update_meta_data( self::META_CURRENCY, $charge['currency'] ); if ( $charge['currency'] !== $order->get_currency() ) { /* translators: 1: charged amount, 2: charged currency, 3: order total, 4: store currency */ $order->add_order_note( sprintf( __( 'AgentaOS checkout for %1$s %2$s (order total %3$s %4$s converted).', 'agentaos-payments' ), $charge['amount'], $charge['currency'], wc_format_decimal( $order->get_total(), 2 ), $order->get_currency() ) ); } $order->save(); $this->log( 'Checkout ' . $checkout['session_id'] . ' created for order ' . $order->get_id() ); return array( 'result' => 'success', 'redirect' => esc_url_raw( AgentaOS_Embedded_Checkout::enabled() ? AgentaOS_Embedded_Checkout::redirect_url( $order, $checkout['checkoutUrl'] ) : $checkout['checkoutUrl'] ), ); } /** * @param WC_Order $order Order. * @param array $charge Amount and currency AgentaOS charges. * @return array Request body for POST /gateway/sessions. */ private function checkout_body( WC_Order $order, array $charge ) { $plan = AgentaOS_Subscriptions::order_plan( $order ); $body = $plan // A plan's price, currency and interval come from its AgentaOS product. ? array( 'linkId' => (string) $plan->get_meta( AgentaOS_Subscriptions::META_LINK_ID ) ) : array( 'amount' => (float) $charge['amount'], 'currency' => $charge['currency'], /* translators: 1: order number, 2: store name */ 'description' => sprintf( __( 'Order %1$s from %2$s', 'agentaos-payments' ), $order->get_order_number(), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ), ); $body += array( 'successUrl' => $this->get_return_url( $order ), 'cancelUrl' => $order->get_cancel_order_url_raw(), 'webhookUrl' => AgentaOS_Webhook::url(), 'metadata' => array( 'source' => 'woocommerce', 'wc_order_id' => (string) $order->get_id(), 'wc_order_key' => $order->get_order_key(), ), ); $optional = array( 'buyerEmail' => $order->get_billing_email(), 'buyerName' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ), 'buyerCompany' => $order->get_billing_company(), 'buyerCountry' => $order->get_billing_country(), ); foreach ( $optional as $key => $value ) { if ( '' !== (string) $value ) { $body[ $key ] = $value; } } /** * Change the request that creates the AgentaOS checkout, for example to add your own metadata. * * @param array $body Request body for POST /gateway/sessions. * @param WC_Order $order The order being paid. */ return apply_filters( 'agentaos_checkout_body', $body, $order ); } /** * When the buyer comes back to the thank-you page before the webhook arrives, ask AgentaOS for the * checkout's status and complete the order if it is paid. The webhook stays the main confirmation. * * @param int $order_id Order ID. */ public function confirm_on_return( $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order || ( ! $order->needs_payment() && ! $order->has_status( 'cancelled' ) ) || self::is_closed_sale( $order ) ) { return; } $session_id = (string) $order->get_meta( self::META_SESSION_ID ); if ( '' === $session_id ) { return; } try { $checkout = $this->api()->get_checkout( $session_id ); } catch ( Exception $e ) { $this->log( 'Status check failed for order ' . $order_id . ': ' . $e->getMessage() ); return; } if ( ! isset( $checkout['status'] ) || 'completed' !== $checkout['status'] ) { return; } if ( ! $this->payment_matches( $order, isset( $checkout['amount'] ) ? $checkout['amount'] : 0, isset( $checkout['currency'] ) ? $checkout['currency'] : '' ) ) { return; } // Keep the ids the webhook would have saved, so refunds, disputes and renewals still find this // order when the webhook is late or never arrives. foreach ( isset( $checkout['transactions'] ) && is_array( $checkout['transactions'] ) ? $checkout['transactions'] : array() as $sale ) { if ( isset( $sale['id'], $sale['direction'] ) && 'inbound' === $sale['direction'] ) { $order->update_meta_data( self::META_TRANSACTION_ID, sanitize_text_field( (string) $sale['id'] ) ); break; } } if ( ! empty( $checkout['metadata']['subscriptionId'] ) ) { $order->update_meta_data( AgentaOS_Subscriptions::META_SUB_ID, sanitize_text_field( (string) $checkout['metadata']['subscriptionId'] ) ); } $order->save(); $this->complete_order( $order, $session_id, __( 'AgentaOS checkout completed (confirmed on return).', 'agentaos-payments' ) ); } /** * @param WC_Order $order Order. * @param string $session_id AgentaOS checkout id. * @return bool True when the checkout was created for this order, now or on an earlier attempt. */ public static function is_order_session( WC_Order $order, $session_id ) { if ( '' === $session_id ) { return false; } $sessions = array( (string) $order->get_meta( self::META_SESSION_ID ) ); foreach ( $order->get_meta( self::META_OLD_SESSIONS, false ) as $meta ) { $sessions[] = (string) $meta->value; } return in_array( $session_id, $sessions, true ); } /** * @param WC_Order $order Order. * @return bool True when this order's sale was recorded and later charged back, refunded or cancelled. */ public static function is_closed_sale( WC_Order $order ) { return '' !== (string) $order->get_meta( self::META_TRANSACTION_ID ) && $order->has_status( array( 'failed', 'refunded', 'cancelled' ) ); } /** * AgentaOS adds the buyer's VAT or sales tax on top of the amount we asked for, so the amount paid may * be higher than the order total. It must never be lower and the currency must match; otherwise the * order is held for the merchant to check. A free trial starts with nothing charged. * * @param WC_Order $order Order. * @param float|string $paid Amount AgentaOS reports, before tax. * @param string $currency Currency AgentaOS reports (EURC and USDC count as EUR and USD). * @param bool $trial True when the checkout started a free trial. * @return bool True when the payment matches the order. */ public function payment_matches( WC_Order $order, $paid, $currency, $trial = false ) { $requested = (string) $order->get_meta( self::META_AMOUNT ); $requested = $trial ? 0.0 : ( '' === $requested ? (float) $order->get_total() : (float) $requested ); $expected = (string) $order->get_meta( self::META_CURRENCY ); $expected = '' === $expected ? $order->get_currency() : $expected; $currency = AgentaOS_Currency::fiat( (string) $currency ); if ( (float) $paid + 0.01 >= $requested && $currency === $expected ) { return true; } if ( $order->needs_payment() || $order->has_status( 'cancelled' ) ) { $order->update_status( 'on-hold', /* translators: 1: amount paid, 2: currency */ sprintf( __( 'AgentaOS reported a payment of %1$s %2$s, less than the order total or in another currency. Check the sale in your AgentaOS dashboard.', 'agentaos-payments' ), wc_format_decimal( $paid, 2 ), $currency ) ); } return false; } /** * Mark an order paid once. Safe to call from both the webhook and the return page. * * @param WC_Order $order Order. * @param string $session_id AgentaOS session ID. * @param string $note Order note. */ public function complete_order( WC_Order $order, $session_id, $note ) { if ( ! $order->needs_payment() && ! $order->has_status( 'cancelled' ) ) { return; } // The webhook and the buyer's return page can arrive in the same second, each holding its own copy // of the unpaid order. add_option() is atomic, so only the first completes this checkout; the marker // is removed after a day by the scheduled check. if ( ! add_option( self::COMPLETED_PREFIX . md5( $session_id ), time(), '', false ) ) { return; } if ( $order->has_status( 'cancelled' ) ) { // Paid after WooCommerce cancelled the order (unpaid order time limit, an old browser tab). $order->set_transaction_id( $session_id ); $order->update_status( 'on-hold', $note . ' ' . __( 'The order had been cancelled before this payment arrived, for example by the unpaid order time limit. Check the stock, then process the order or refund the buyer.', 'agentaos-payments' ) ); $this->log( 'Order ' . $order->get_id() . ' was paid after it was cancelled; put on hold, checkout ' . $session_id ); return; } $order->add_order_note( $note ); $order->payment_complete( $session_id ); $this->log( 'Order ' . $order->get_id() . ' paid, checkout ' . $session_id ); /** * AgentaOS confirmed the payment and the order is marked paid (first orders and renewals). * * @param WC_Order $order The paid order. * @param string $session_id The AgentaOS checkout id. */ do_action( 'agentaos_payment_confirmed', $order, $session_id ); } /** * @return AgentaOS_API */ public function api() { return new AgentaOS_API( $this->api_key ); } /** * @param string $message Message without secrets. */ public function log( $message ) { if ( $this->debug && function_exists( 'wc_get_logger' ) ) { wc_get_logger()->info( $message, array( 'source' => 'agentaos-payments' ) ); } } }