cart || WC()->cart->is_empty() ) { return $passed; } $adding_plan = self::is_subscription( wc_get_product( $product_id ) ); $cart_plan = false; foreach ( WC()->cart->get_cart() as $item ) { $cart_plan = $cart_plan || self::is_subscription( $item['data'] ); } if ( $adding_plan || $cart_plan ) { wc_add_notice( __( 'A subscription is bought on its own. Complete or empty your cart first.', 'agentaos-payments' ), 'error' ); return false; } return true; } /** * @param WC_Order $order Order. * @return WC_Product|null The subscription product when the order is a single AgentaOS subscription. */ public static function order_plan( WC_Order $order ) { $items = $order->get_items(); if ( 1 !== count( $items ) ) { return null; } $item = reset( $items ); $product = $item instanceof WC_Order_Item_Product ? $item->get_product() : null; return self::is_subscription( $product ) ? $product : null; } /** * @param WC_Product|false $product Product. * @return bool */ public static function is_subscription( $product ) { return $product instanceof WC_Product && 'yes' === $product->get_meta( self::META_ENABLED ) && '' !== (string) $product->get_meta( self::META_LINK_ID ); } /** * The merchant's Subscriptions setting. It only stops new subscriptions: renewals, status updates * and cancels for existing subscribers keep working when it is off. * * @return bool */ public static function enabled() { $settings = get_option( 'woocommerce_agentaos_settings', array() ); return ! isset( $settings['subscriptions'] ) || 'yes' === $settings['subscriptions']; } public static function product_fields() { if ( ! self::enabled() ) { return; } echo '
'; } /** * @param WC_Product $product Product being saved (not yet written). */ public static function save_product( WC_Product $product ) { if ( ! self::enabled() ) { return; } // phpcs:disable WordPress.Security.NonceVerification.Missing -- WooCommerce verifies the product edit nonce before this hook. $enabled = isset( $_POST[ self::META_ENABLED ] ) ? 'yes' : 'no'; $interval = isset( $_POST[ self::META_INTERVAL ] ) && 'year' === $_POST[ self::META_INTERVAL ] ? 'year' : 'month'; $trial = isset( $_POST[ self::META_TRIAL ] ) ? min( 730, absint( wp_unslash( $_POST[ self::META_TRIAL ] ) ) ) : 0; // phpcs:enable $product->update_meta_data( self::META_ENABLED, $enabled ); $product->update_meta_data( self::META_INTERVAL, $interval ); $product->update_meta_data( self::META_TRIAL, $trial ); if ( 'yes' === $enabled ) { self::sync( $product ); } } /** * Make sure an AgentaOS subscription product exists for the current price and terms. * * @param WC_Product $product Product. */ public static function sync( WC_Product $product ) { $gateway = self::gateway(); if ( ! $gateway ) { WC_Admin_Meta_Boxes::add_error( __( 'Set up the AgentaOS payment method (keys and currency) before selling subscriptions.', 'agentaos-payments' ) ); return; } if ( ! ( $product->is_virtual() || $product->is_downloadable() ) ) { WC_Admin_Meta_Boxes::add_error( __( 'AgentaOS subscriptions are for digital products and services: mark the product Virtual or Downloadable.', 'agentaos-payments' ) ); return; } $charge = $gateway->settlement( (string) $product->get_regular_price() ); if ( ! $charge || (float) $charge['amount'] <= 0 ) { WC_Admin_Meta_Boxes::add_error( __( 'Set a regular price above zero for the AgentaOS subscription.', 'agentaos-payments' ) ); return; } $interval = (string) $product->get_meta( self::META_INTERVAL ); $trial = (int) $product->get_meta( self::META_TRIAL ); $fingerprint = self::fingerprint( $product, $charge, $gateway ); if ( $fingerprint === $product->get_meta( self::META_LINK_FP ) ) { return; } $body = array( 'name' => $product->get_name(), 'amount' => (float) $charge['amount'], 'currency' => $charge['currency'], 'type' => 'subscription', 'billingInterval' => $interval, 'webhookUrl' => AgentaOS_Webhook::url(), 'metadata' => array( 'source' => 'woocommerce', 'wc_product_id' => (string) $product->get_id(), ), ); if ( $trial > 0 ) { $body['trialPeriodDays'] = $trial; } try { $link = $gateway->api()->create_product( $body, 'wc-product-' . $product->get_id() . '-' . md5( $fingerprint ) ); } catch ( Exception $e ) { /* translators: %s: error from AgentaOS */ WC_Admin_Meta_Boxes::add_error( sprintf( __( 'AgentaOS could not create the subscription product: %s', 'agentaos-payments' ), $e->getMessage() ) ); return; } $product->update_meta_data( self::META_LINK_ID, sanitize_text_field( $link['id'] ) ); $product->update_meta_data( self::META_LINK_FP, $fingerprint ); } /** * @param WC_Product $product Product. * @param array $charge What AgentaOS charges for the regular price. * @param AgentaOS_Gateway $gateway Gateway. * @return string The terms an AgentaOS plan was built for. */ private static function fingerprint( WC_Product $product, array $charge, AgentaOS_Gateway $gateway ) { return implode( '|', array( $charge['amount'], $charge['currency'], $product->get_meta( self::META_INTERVAL ), (int) $product->get_meta( self::META_TRIAL ), $gateway->get_option( 'mode' ) ) ); } /** * A plan may be checked out only when its AgentaOS price is what this order charges and it was built * for the current mode, currency and rate. * * @param WC_Product $plan Subscription product. * @param array $charge What this order charges. * @param AgentaOS_Gateway $gateway Gateway. * @return bool */ public static function plan_matches( WC_Product $plan, array $charge, AgentaOS_Gateway $gateway ) { $regular = $gateway->settlement( (string) $plan->get_regular_price() ); return $regular && $regular['amount'] === $charge['amount'] && self::fingerprint( $plan, $regular, $gateway ) === (string) $plan->get_meta( self::META_LINK_FP ); } /** * A renewal charge arrives as its own checkout.session.completed, without the store's metadata. * It becomes a new paid order linked to the subscription's first order. Safe to receive twice. * * @param array $data Event data. * @param string $event_id Event id, "evt_" + the charge's transaction id. * @param AgentaOS_Gateway $gateway Gateway. */ public static function renewal( array $data, $event_id, AgentaOS_Gateway $gateway ) { $session_id = isset( $data['session_id'] ) ? sanitize_text_field( (string) $data['session_id'] ) : ''; $parent = self::first_order( isset( $data['metadata']['subscriptionId'] ) ? (string) $data['metadata']['subscriptionId'] : '' ); if ( ! $parent || '' === $session_id || self::find( AgentaOS_Gateway::META_SESSION_ID, $session_id ) ) { return; } // Two deliveries of the same charge can arrive at once. add_option() is atomic, so only one of // them creates the order; a lock left by a crashed request expires after five minutes. $lock = 'agentaos_renewal_' . md5( $session_id ); if ( ! add_option( $lock, time(), '', false ) ) { if ( (int) get_option( $lock ) > time() - 300 ) { return; } update_option( $lock, time(), false ); } self::create_renewal( $parent, $data, $session_id, $event_id, $gateway ); delete_option( $lock ); } /** * @param WC_Order $first The order that started the subscription. * @param array $data Event data. * @param string $session_id The renewal's checkout id. * @param string $event_id Event id, "evt_" + the charge's transaction id. * @param AgentaOS_Gateway $gateway Gateway. */ private static function create_renewal( WC_Order $first, array $data, $session_id, $event_id, AgentaOS_Gateway $gateway ) { $paid = isset( $data['amount'] ) ? wc_format_decimal( $data['amount'], 2 ) : '0'; $currency = AgentaOS_Currency::fiat( isset( $data['currency'] ) ? (string) $data['currency'] : '' ); $renewal = wc_create_order( array( 'customer_id' => $first->get_customer_id(), 'created_via' => 'agentaos-renewal', ) ); $renewal->set_address( $first->get_address( 'billing' ), 'billing' ); foreach ( $first->get_items() as $item ) { $product = $item instanceof WC_Order_Item_Product ? $item->get_product() : null; if ( $product ) { $renewal->add_product( $product, $item->get_quantity(), array( 'subtotal' => $item->get_subtotal(), 'total' => $item->get_total(), ) ); } } if ( ! $renewal->get_items() ) { // The plan product was deleted: record the renewal as a fee so the order is still a paid order. $fee = new WC_Order_Item_Fee(); $fee->set_name( __( 'AgentaOS subscription renewal', 'agentaos-payments' ) ); $fee->set_total( $first->get_total() ); $renewal->add_item( $fee ); } $renewal->set_currency( $first->get_currency() ); $renewal->set_payment_method( 'agentaos' ); $renewal->set_payment_method_title( $first->get_payment_method_title() ); $renewal->calculate_totals( false ); $renewal->update_meta_data( '_agentaos_parent_order', (string) $first->get_id() ); $renewal->update_meta_data( self::META_SUB_ID, $first->get_meta( self::META_SUB_ID ) ); $renewal->update_meta_data( AgentaOS_Gateway::META_SESSION_ID, $session_id ); $renewal->update_meta_data( AgentaOS_Gateway::META_AMOUNT, $paid ); $renewal->update_meta_data( AgentaOS_Gateway::META_CURRENCY, $currency ); if ( 0 === strpos( $event_id, 'evt_' ) ) { $renewal->update_meta_data( AgentaOS_Gateway::META_TRANSACTION_ID, sanitize_text_field( substr( $event_id, 4 ) ) ); } $renewal->save(); /* translators: 1: parent order number, 2: amount, 3: currency, 4: checkout id */ $gateway->complete_order( $renewal, $session_id, sprintf( __( 'Subscription renewal of order #%1$s: paid %2$s %3$s on AgentaOS, checkout %4$s.', 'agentaos-payments' ), $first->get_order_number(), $paid, $currency, $session_id ) ); /** * A subscription renewal was charged and recorded as a new paid order. * * @param WC_Order $renewal The new paid renewal order. * @param WC_Order $first The order that started the subscription. * @param array $data The AgentaOS event data. */ do_action( 'agentaos_renewal_created', $renewal, $first, $data ); } /** * subscription.* events: keep the first order's view of the subscription current. * * @param string $type Event type. * @param array $data Event data. */ public static function sync_status( $type, array $data ) { $order = self::first_order( isset( $data['id'] ) ? (string) $data['id'] : '' ); if ( ! $order ) { return; } $status = isset( $data['status'] ) ? sanitize_text_field( (string) $data['status'] ) : ''; $previous = (string) $order->get_meta( '_agentaos_subscription_status' ); $order->update_meta_data( '_agentaos_subscription_status', $status ); $order->update_meta_data( '_agentaos_period_end', isset( $data['current_period_end'] ) ? sanitize_text_field( (string) $data['current_period_end'] ) : '' ); $order->update_meta_data( '_agentaos_cancel_at_period_end', empty( $data['cancel_at_period_end'] ) ? 'no' : 'yes' ); $order->save(); if ( $status === $previous ) { return; } if ( 'subscription.payment_failed' === $type ) { $order->add_order_note( __( 'A subscription renewal payment failed. AgentaOS asks the subscriber to update their card.', 'agentaos-payments' ) ); } elseif ( 'subscription.canceled' === $type ) { $order->add_order_note( __( 'The AgentaOS subscription has ended.', 'agentaos-payments' ) ); } } /** * @param string $subscription_id AgentaOS subscription id. * @return WC_Order|null The order that started the subscription. */ public static function first_order( $subscription_id ) { if ( '' === $subscription_id ) { return null; } $orders = wc_get_orders( array( 'limit' => 1, 'payment_method' => 'agentaos', 'orderby' => 'date', 'order' => 'ASC', 'meta_key' => self::META_SUB_ID, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => sanitize_text_field( $subscription_id ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value ) ); return $orders ? $orders[0] : null; } /** * @param string $key Meta key. * @param string $value Meta value. * @return bool True when an order with this meta value exists. */ private static function find( $key, $value ) { return (bool) wc_get_orders( array( 'limit' => 1, 'return' => 'ids', 'meta_key' => $key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $value, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value ) ); } /** * @return AgentaOS_Gateway|null */ private static function gateway() { $gateways = WC()->payment_gateways() ? WC()->payment_gateways()->payment_gateways() : array(); return isset( $gateways['agentaos'] ) && $gateways['agentaos']->is_ready() ? $gateways['agentaos'] : null; } }