array( 'GET', 'POST' ), 'callback' => array( __CLASS__, 'handle' ), // Authenticated by the HMAC signature below, not by a WordPress user. 'permission_callback' => '__return_true', ) ); } ); } /** * @return string Public URL of the webhook endpoint. */ public static function url() { return rest_url( self::ROUTE_NAMESPACE . self::ROUTE ); } /** * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public static function handle( WP_REST_Request $request ) { if ( 'GET' === $request->get_method() ) { return new WP_REST_Response( array( 'status' => 'ok' ), 200 ); } $gateway = self::gateway(); if ( ! $gateway ) { return new WP_REST_Response( array( 'error' => 'gateway not available' ), 503 ); } $raw_body = $request->get_body(); if ( ! AgentaOS_Signature::is_valid( $raw_body, (string) $request->get_header( 'x_agentaos_signature' ), $gateway->webhook_secret ) ) { $gateway->log( 'Webhook rejected: bad or expired signature.' ); return new WP_REST_Response( array( 'error' => 'invalid signature' ), 401 ); } $event = json_decode( $raw_body, true ); $type = is_array( $event ) && isset( $event['type'] ) ? (string) $event['type'] : ''; $data = is_array( $event ) && isset( $event['data'] ) && is_array( $event['data'] ) ? $event['data'] : array(); $event_id = isset( $event['id'] ) ? (string) $event['id'] : ''; // A renewal carries the subscription id but not the store's order id. The first charge after a free // trial may come without the subscriptionCycle flag, so the missing order id decides too. $renewal = ! empty( $data['metadata']['subscriptionCycle'] ) || ( ! empty( $data['metadata']['subscriptionId'] ) && empty( $data['metadata']['wc_order_id'] ) ); if ( 'checkout.session.completed' === $type && $renewal ) { AgentaOS_Subscriptions::renewal( $data, $event_id, $gateway ); } elseif ( 'checkout.session.completed' === $type ) { self::checkout_completed( $data, $event_id, $gateway ); } elseif ( 0 === strpos( $type, 'subscription.' ) ) { AgentaOS_Subscriptions::sync_status( $type, $data ); } elseif ( 'dispute.created' === $type ) { self::dispute_opened( $data ); } elseif ( 'dispute.closed' === $type ) { self::dispute_won( $data ); } // A verified event is always acknowledged, including webhook.test and events this plugin ignores. return new WP_REST_Response( array( 'received' => true ), 200 ); } /** * @param array $data Event data. * @param string $event_id Event id, "evt_" + the sale's transaction id. * @param AgentaOS_Gateway $gateway Gateway. */ private static function checkout_completed( array $data, $event_id, AgentaOS_Gateway $gateway ) { $metadata = isset( $data['metadata'] ) && is_array( $data['metadata'] ) ? $data['metadata'] : array(); $order = isset( $metadata['wc_order_id'] ) ? wc_get_order( absint( $metadata['wc_order_id'] ) ) : false; if ( ! $order || 'agentaos' !== $order->get_payment_method() ) { return; // Not one of this store's orders, for example a sale from a buyer link. } $session_id = isset( $data['session_id'] ) ? (string) $data['session_id'] : ''; $order_key = isset( $metadata['wc_order_key'] ) ? (string) $metadata['wc_order_key'] : ''; if ( ! hash_equals( $order->get_order_key(), $order_key ) || ! AgentaOS_Gateway::is_order_session( $order, $session_id ) ) { $gateway->log( 'Webhook for order ' . $order->get_id() . ' ignored: order key or checkout does not match.' ); return; } // The buyer paid an earlier checkout of this order: it is now the one that counts (invoice, refunds). if ( $session_id !== (string) $order->get_meta( AgentaOS_Gateway::META_SESSION_ID ) ) { $order->update_meta_data( AgentaOS_Gateway::META_SESSION_ID, sanitize_text_field( $session_id ) ); $order->save(); } // A sale that was already recorded and then charged back, refunded or cancelled is never revived by // a re-delivered payment event. if ( AgentaOS_Gateway::is_closed_sale( $order ) ) { return; } // The sale's transaction id lets disputes and refund requests find this order later. A free trial // charges nothing: its event carries the subscription id instead, which is not a sale. if ( 0 === strpos( $event_id, 'evt_' ) && empty( $data['trial'] ) ) { $order->update_meta_data( AgentaOS_Gateway::META_TRANSACTION_ID, sanitize_text_field( substr( $event_id, 4 ) ) ); $order->save(); } // A subscription's first checkout tells us its id; renewals are matched through it later. if ( ! empty( $metadata['subscriptionId'] ) ) { $order->update_meta_data( AgentaOS_Subscriptions::META_SUB_ID, sanitize_text_field( (string) $metadata['subscriptionId'] ) ); $order->save(); } $trial = ! empty( $data['trial'] ); $paid = isset( $data['amount'] ) ? (float) $data['amount'] : 0.0; $currency = AgentaOS_Currency::fiat( isset( $data['currency'] ) ? (string) $data['currency'] : '' ); if ( ! $gateway->payment_matches( $order, $paid, $currency, $trial ) ) { return; } if ( $trial ) { $ends = isset( $data['trial_end'] ) ? date_i18n( get_option( 'date_format' ), strtotime( (string) $data['trial_end'] ) ) : ''; /* translators: %s: trial end date */ $gateway->complete_order( $order, $session_id, sprintf( __( 'Free trial started on AgentaOS; the first charge is due %s.', 'agentaos-payments' ), $ends ) ); return; } $mode = empty( $data['livemode'] ) ? __( 'test', 'agentaos-payments' ) : __( 'live', 'agentaos-payments' ); $rail = isset( $data['rail'] ) ? sanitize_text_field( (string) $data['rail'] ) : 'card'; $gateway->complete_order( $order, $session_id, /* translators: 1: amount, 2: currency, 3: payment rail, 4: test or live, 5: checkout ID */ sprintf( __( 'Paid %1$s %2$s by %3$s on AgentaOS (%4$s mode), checkout %5$s.', 'agentaos-payments' ), wc_format_decimal( $paid, 2 ), $currency, $rail, $mode, $session_id ) ); } /** * A buyer's bank opened a chargeback: hold the order so it is not fulfilled further. * * @param array $data Event data. */ private static function dispute_opened( array $data ) { $order = self::order_by_transaction( $data ); $dispute_id = isset( $data['dispute_id'] ) ? sanitize_text_field( (string) $data['dispute_id'] ) : ''; if ( ! $order || $dispute_id === $order->get_meta( '_agentaos_dispute_id' ) ) { return; } if ( '' === (string) $order->get_meta( '_agentaos_dispute_id' ) ) { $order->update_meta_data( '_agentaos_status_before_dispute', $order->get_status() ); } $order->update_meta_data( '_agentaos_dispute_id', $dispute_id ); $order->update_status( 'on-hold', /* translators: %s: dispute id */ sprintf( __( 'The buyer\'s bank opened a dispute (%s). AgentaOS answers the bank as merchant of record; reply to its dispute email with your evidence.', 'agentaos-payments' ), $dispute_id ) ); } /** * A dispute closed in the seller's favour: put the order back where it was. * * @param array $data Event data. */ private static function dispute_won( array $data ) { $order = self::order_by_transaction( $data ); if ( ! $order || '' === (string) $order->get_meta( '_agentaos_dispute_id' ) ) { return; } $previous = (string) $order->get_meta( '_agentaos_status_before_dispute' ); $order->delete_meta_data( '_agentaos_dispute_id' ); $order->delete_meta_data( '_agentaos_status_before_dispute' ); $order->update_status( '' !== $previous ? $previous : 'processing', __( 'The dispute was closed in your favour.', 'agentaos-payments' ) ); } /** * @param array $data Event data with transaction_id. * @return WC_Order|null */ private static function order_by_transaction( array $data ) { $transaction_id = isset( $data['transaction_id'] ) ? sanitize_text_field( (string) $data['transaction_id'] ) : ''; if ( '' === $transaction_id ) { return null; } $orders = wc_get_orders( array( 'limit' => 1, 'meta_key' => AgentaOS_Gateway::META_TRANSACTION_ID, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $transaction_id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value ) ); return $orders ? $orders[0] : null; } /** * @return AgentaOS_Gateway|null */ private static function gateway() { if ( ! function_exists( 'WC' ) || ! WC()->payment_gateways() ) { return null; } $gateways = WC()->payment_gateways()->payment_gateways(); return isset( $gateways['agentaos'] ) && $gateways['agentaos'] instanceof AgentaOS_Gateway ? $gateways['agentaos'] : null; } }