' . esc_html__( 'Okel needs WooCommerce to be active.', 'okel-sync' ) . '

'; } ); return; } if ( get_option( 'okelsync_db_version' ) !== Okelsync_Store::DB_VER ) { Okelsync_Store::install(); } add_action( 'okelsync_run_job', array( 'Okelsync_Store', 'run_job' ) ); add_action( 'okelsync_recurring', 'okelsync_recurring' ); add_action( 'init', 'okelsync_schedule_recurring' ); add_action( 'rest_api_init', 'okelsync_rest' ); add_action( 'admin_post_okelsync_oauth', 'okelsync_oauth_callback' ); // --- WooCommerce -> TikTok triggers (standalone) / pings (cloud) --- add_action( 'woocommerce_product_set_stock', 'okelsync_on_stock' ); add_action( 'woocommerce_variation_set_stock', 'okelsync_on_stock' ); add_action( 'woocommerce_update_product', 'okelsync_on_product_save', 20 ); add_action( 'woocommerce_order_status_completed', 'okelsync_on_order_change' ); add_action( 'woocommerce_process_shop_order_meta', 'okelsync_on_order_change', 50 ); add_action( 'updated_post_meta', 'okelsync_on_tracking_meta', 10, 3 ); Okelsync_Admin::init(); } function okelsync_deactivate() { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( '', array(), Okelsync_Store::AS_GROUP ); } } function okelsync_standalone() { return 'standalone' === Okelsync_Store::get( 'mode' ) && ! empty( Okelsync_Store::shop()['access_token'] ); } function okelsync_schedule_recurring() { if ( function_exists( 'as_has_scheduled_action' ) && ! as_has_scheduled_action( 'okelsync_recurring', array(), Okelsync_Store::AS_GROUP ) ) { as_schedule_recurring_action( time() + 60, 5 * MINUTE_IN_SECONDS, 'okelsync_recurring', array(), Okelsync_Store::AS_GROUP ); } } /** Every 5 minutes: poll orders, every 15: stock check, daily: token refresh, housekeeping. */ function okelsync_recurring() { if ( ! okelsync_standalone() ) { return; } Okelsync_Store::enqueue( 'orders.poll', array(), 'orders.poll' ); if ( time() - (int) get_option( 'okelsync_last_reconcile', 0 ) > 15 * MINUTE_IN_SECONDS ) { update_option( 'okelsync_last_reconcile', time(), false ); Okelsync_Store::enqueue( 'stock.reconcile', array(), 'stock.reconcile' ); } $shop = Okelsync_Store::shop(); if ( ! empty( $shop['expires_at'] ) && $shop['expires_at'] - time() < 2 * DAY_IN_SECONDS ) { Okelsync_Store::enqueue( 'token.refresh', array(), 'token.refresh' ); } global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}okelsync_logs WHERE created_at < %s", gmdate( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ) ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}okelsync_jobs WHERE status = 'done' AND updated_at < %s", gmdate( 'Y-m-d H:i:s', time() - 3 * DAY_IN_SECONDS ) ) ); } function okelsync_parent_id( $product ) { $p = $product instanceof WC_Product ? $product : wc_get_product( $product ); if ( ! $p ) { return 0; } return $p->get_parent_id() ? $p->get_parent_id() : $p->get_id(); } function okelsync_on_stock( $product ) { $id = okelsync_parent_id( $product ); if ( ! $id ) { return; } if ( okelsync_standalone() ) { if ( get_post_meta( $id, '_okelsync_tiktok_id', true ) ) { Okelsync_Store::enqueue( 'product.push', array( 'id' => $id, 'only' => array( 'stock' ) ), 'product.push:' . $id, 2 ); } } else { okelsync_cloud_ping( $id ); } } function okelsync_on_product_save( $product_id ) { if ( okelsync_standalone() && Okelsync_Store::get( 'sync_products' ) && get_post_meta( $product_id, '_okelsync_tiktok_id', true ) ) { Okelsync_Store::enqueue( 'product.push', array( 'id' => $product_id ), 'product.push:' . $product_id, 5 ); } } function okelsync_on_order_change( $order_id ) { $order = wc_get_order( $order_id ); if ( $order && $order->get_meta( '_okelsync_order_id' ) && okelsync_standalone() && Okelsync_Sync::tracking_of( $order ) ) { Okelsync_Store::enqueue( 'fulfillment.push', array( 'id' => $order_id ), 'fulfillment.push:' . $order_id, 2 ); } } /** Advanced Shipment Tracking / WooCommerce Shipment Tracking save their own meta. */ function okelsync_on_tracking_meta( $meta_id, $object_id, $key ) { if ( '_wc_shipment_tracking_items' === $key ) { okelsync_on_order_change( $object_id ); } } /** Cloud (companion) mode: tell the Okel app that stock changed outside REST webhooks. */ function okelsync_cloud_ping( $product_id ) { $s = Okelsync_Store::get(); if ( 'cloud' !== $s['mode'] || ! $s['cloud_endpoint'] || ! $s['cloud_token'] ) { return; } $body = wp_json_encode( array( 'product_id' => (int) $product_id ) ); wp_remote_post( $s['cloud_endpoint'], array( 'blocking' => false, 'timeout' => 3, 'headers' => array( 'content-type' => 'application/json', 'x-okelsync-signature' => hash_hmac( 'sha256', $body, Okelsync_Store::decrypt( $s['cloud_token'] ) ) ), 'body' => $body, ) ); } // ---------------- REST: TikTok webhooks ---------------- function okelsync_rest() { register_rest_route( 'okelsync/v1', '/webhook', array( 'methods' => 'POST', 'permission_callback' => '__return_true', 'callback' => 'okelsync_webhook', ) ); } function okelsync_webhook( WP_REST_Request $req ) { $s = Okelsync_Store::get(); $raw = $req->get_body(); $secret = ( 'standalone' === $s['mode'] && ! empty( $s['app_secret'] ) ) ? (string) Okelsync_Store::decrypt( $s['app_secret'] ) : ''; // without a configured app key and a readable secret nothing can be verified: refuse instead of checking an empty-key HMAC if ( '' === $secret || empty( $s['app_key'] ) ) { return new WP_REST_Response( array( 'error' => 'webhooks are not configured' ), 403 ); } if ( ! Okelsync_TikTok::verify_webhook( $raw, $req->get_header( 'authorization' ), $s['app_key'], $secret ) ) { return new WP_REST_Response( array( 'error' => 'bad signature' ), 401 ); } $ev = json_decode( $raw, true ); $eid = isset( $ev['tts_notification_id'] ) ? $ev['tts_notification_id'] : md5( $raw ); if ( get_transient( 'okelsync_evt_' . md5( $eid ) ) ) { return array( 'code' => 0, 'duplicate' => true ); } set_transient( 'okelsync_evt_' . md5( $eid ), 1, DAY_IN_SECONDS ); $type = isset( $ev['type'] ) ? (int) $ev['type'] : 0; if ( ! empty( $ev['data']['order_id'] ) && in_array( $type, array( 1, 2, 11, 12 ), true ) ) { Okelsync_Store::enqueue( 'order.ingest', array( 'id' => (string) $ev['data']['order_id'] ), 'order.ingest:' . $ev['data']['order_id'] ); } elseif ( in_array( $type, array( 6, 7 ), true ) ) { $shop = Okelsync_Store::shop(); $shop['status'] = 'reauth_required'; Okelsync_Store::save_shop( $shop ); } return array( 'code' => 0 ); } // ---------------- TikTok OAuth (standalone) ---------------- function okelsync_oauth_url() { return admin_url( 'admin-post.php?action=okelsync_oauth' ); } function okelsync_oauth_callback() { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You do not have permission to connect TikTok.', 'okel-sync' ) ); } $back = admin_url( 'admin.php?page=okelsync&tab=settings' ); $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification if ( ! $code || ! $state || get_transient( 'okelsync_state_' . get_current_user_id() ) !== $state ) { wp_safe_redirect( add_query_arg( 'okelsync_error', rawurlencode( 'TikTok connect link expired. Try again.' ), $back ) ); exit; } delete_transient( 'okelsync_state_' . get_current_user_id() ); try { $client = Okelsync_Store::client(); $t = $client->token_get( $code ); $shops = $client->request( 'GET', '/authorization/202309/shops', array(), null, array( 'token' => $t['access_token'], 'cipher' => '' ) ); $shop = isset( $shops['shops'][0] ) ? $shops['shops'][0] : null; if ( ! $shop ) { throw new Okelsync_Fix_Required( esc_html( 'No TikTok shop on this account' ), 'Sign in to TikTok with the seller account that owns the shop.' ); } $currencies = array( 'GB' => 'GBP', 'US' => 'USD', 'DE' => 'EUR', 'FR' => 'EUR', 'IT' => 'EUR', 'ES' => 'EUR', 'IE' => 'EUR', 'MY' => 'MYR', 'SG' => 'SGD', 'PH' => 'PHP', 'TH' => 'THB', 'VN' => 'VND', 'ID' => 'IDR', 'MX' => 'MXN', 'JP' => 'JPY' ); Okelsync_Store::save_shop( array( 'id' => $shop['id'], 'name' => $shop['name'], 'region' => $shop['region'], 'seller_type' => $shop['seller_type'], 'cipher' => $shop['cipher'], 'currency' => isset( $currencies[ $shop['region'] ] ) ? $currencies[ $shop['region'] ] : get_woocommerce_currency(), 'access_token' => Okelsync_Store::encrypt( $t['access_token'] ), 'refresh_token' => Okelsync_Store::encrypt( $t['refresh_token'] ), 'expires_at' => (int) $t['access_token_expire_in'], 'status' => 'connected', ) ); Okelsync_Store::log( 'system', 'auth', null, 'success', 'Connected TikTok Shop ' . $shop['name'] . ' (' . $shop['region'] . ')' ); Okelsync_Store::enqueue( 'mapping.suggest', array(), 'mapping.suggest' ); $target = add_query_arg( 'okelsync_ok', 'tiktok', $back ); } catch ( Exception $e ) { $hint = isset( $e->hint ) ? $e->hint : ''; $target = add_query_arg( 'okelsync_error', rawurlencode( $e->getMessage() . '. ' . $hint ), $back ); } wp_safe_redirect( $target ); exit; }