request( $method, $path, $query, $body, Okelsync_Store::shop_auth(), $multipart ); } private static function currency() { $shop = Okelsync_Store::shop(); return ! empty( $shop['currency'] ) ? $shop['currency'] : get_woocommerce_currency(); } public static function to_minor( $amount ) { return (int) round( (float) $amount * 100 ); } private static function from_minor( $minor ) { return number_format( $minor / 100, 2, '.', '' ); } public static function cached( $key, $ttl, $loader ) { $shop = Okelsync_Store::shop(); $k = 'okelsync_' . md5( $key . ( isset( $shop['id'] ) ? $shop['id'] : '' ) ); $v = get_transient( $k ); if ( false !== $v ) { return $v; } $v = call_user_func( $loader ); set_transient( $k, $v, $ttl ); return $v; } public static function categories() { return self::cached( 'categories', WEEK_IN_SECONDS, function () { $d = self::api( 'GET', '/product/202309/categories' ); return isset( $d['categories'] ) ? $d['categories'] : array(); } ); } public static function leaf_paths() { $cats = self::categories(); $by = array(); foreach ( $cats as $c ) { $by[ $c['id'] ] = $c; } $out = array(); foreach ( $cats as $c ) { // TikTok marks some categories as unavailable in a region or invite-only (e.g. UK Seat Cushions) if ( empty( $c['is_leaf'] ) || ( ! empty( $c['permission_statuses'] ) && ! in_array( 'AVAILABLE', (array) $c['permission_statuses'], true ) ) ) { continue; } $parts = array(); $cur = $c; for ( $i = 0; $cur && $i < 8; $i++ ) { array_unshift( $parts, $cur['local_name'] ); $cur = isset( $by[ $cur['parent_id'] ] ) ? $by[ $cur['parent_id'] ] : null; } $out[] = array( 'id' => $c['id'], 'name' => $c['local_name'], 'path' => implode( ' > ', $parts ) ); } return $out; } public static function attributes( $category_id ) { return self::cached( 'attrs' . $category_id, WEEK_IN_SECONDS, function () use ( $category_id ) { $d = self::api( 'GET', '/product/202309/categories/' . $category_id . '/attributes' ); return isset( $d['attributes'] ) ? $d['attributes'] : array(); } ); } private static function warehouse_id() { $wh = Okelsync_Store::get( 'warehouse_id' ); if ( $wh ) { return $wh; } $list = self::cached( 'warehouses', DAY_IN_SECONDS, function () { $d = self::api( 'GET', '/logistics/202309/warehouses' ); return isset( $d['warehouses'] ) ? $d['warehouses'] : array(); } ); foreach ( $list as $w ) { if ( 'SALES_WAREHOUSE' === $w['type'] && ! empty( $w['is_default'] ) ) { Okelsync_Store::update( array( 'warehouse_id' => $w['id'] ) ); return $w['id']; } } throw new Okelsync_Fix_Required( esc_html( 'No TikTok sales warehouse' ), 'Create a sales warehouse in TikTok Seller Center › Logistics, then choose it in Okel › Settings.' ); } private static function set_status( $product_id, $status, $error = '', $hint = '' ) { update_post_meta( $product_id, '_okelsync_status', $status ); update_post_meta( $product_id, '_okelsync_error', $error ); update_post_meta( $product_id, '_okelsync_hint', $hint ); } // ======================= mapping & pricing ======================= private static function tokens( $s ) { $s = strtolower( preg_replace( '/[^a-z0-9\s-]/i', ' ', $s ) ); $syn = array( 'tee' => 'shirt', 'tees' => 'shirt', 't-shirt' => 'shirt', 't-shirts' => 'shirt', 'jumper' => 'sweater', 'trousers' => 'pants', 'perfume' => 'fragrance' ); $out = array(); foreach ( preg_split( '/\s+/', $s ) as $w ) { $w = isset( $syn[ $w ] ) ? $syn[ $w ] : $w; $w = preg_replace( '/(es|s)$/', '', preg_replace( '/ies$/', 'y', $w ) ); if ( strlen( $w ) > 1 && ! in_array( $w, array( 'and', 'the', 'for', 'of', 'with', 'other', 'accessory', 'supply' ), true ) ) { $out[ $w ] = true; } } return $out; } public static function similarity( $woo, $path, $leaf ) { $a = self::tokens( $woo ); if ( ! $a ) { return 0; } $l = self::tokens( $leaf ); $p = self::tokens( $path ); $score = 0; foreach ( $a as $t => $_ ) { $score += isset( $l[ $t ] ) ? 1 : ( isset( $p[ $t ] ) ? 0.4 : 0 ); } return (int) round( min( 1, $score / count( $a ) ) * 100 ); } public static function suggest_categories() { $paths = self::leaf_paths(); $map = Okelsync_Store::get( 'category_map' ); $terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => true ) ); foreach ( (array) $terms as $term ) { $id = (string) $term->term_id; if ( isset( $map[ $id ] ) && 'suggested' !== $map[ $id ]['source'] ) { continue; } $best = array( 'id' => '', 'path' => '', 'score' => 0 ); foreach ( $paths as $c ) { $s = self::similarity( $term->name, $c['path'], $c['name'] ); if ( $s > $best['score'] ) { $best = array( 'id' => $c['id'], 'path' => $c['path'], 'score' => $s ); } } if ( $best['score'] < 60 ) { $sample = get_posts( array( 'post_type' => 'product', 'numberposts' => 1, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'terms' => $term->term_id ) ) ) ); if ( $sample ) { try { $rec = self::api( 'POST', '/product/202309/categories/recommend', array(), array( 'product_title' => $sample[0]->post_title ) ); foreach ( $paths as $c ) { if ( $c['id'] === $rec['leaf_category_id'] ) { $best = array( 'id' => $c['id'], 'path' => $c['path'], 'score' => max( $best['score'], 75 ) ); } } } catch ( Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement } } } if ( $best['id'] ) { $map[ $id ] = array( 'tiktok_id' => $best['id'], 'name' => $best['path'], 'confidence' => $best['score'], 'source' => 'suggested', 'woo_name' => $term->name ); } } Okelsync_Store::update( array( 'category_map' => $map ) ); } private static function category_for( WC_Product $p ) { $override = get_post_meta( $p->get_id(), '_okelsync_category', true ); if ( $override ) { return array( $override, null ); } $map = Okelsync_Store::get( 'category_map' ); $first = null; foreach ( $p->get_category_ids() as $cid ) { $term = get_term( $cid ); $first = $first ? $first : ( $term ? $term->name : 'Uncategorised' ); $m = isset( $map[ (string) $cid ] ) ? $map[ (string) $cid ] : null; if ( $m && $m['tiktok_id'] && ( 'suggested' !== $m['source'] || $m['confidence'] >= 80 ) ) { return array( $m['tiktok_id'], null ); } } return array( null, $first ? $first : 'Uncategorised' ); } private static function product_attributes( WC_Product $p, $category_id, &$missing ) { $defaults = Okelsync_Store::get( 'attr_defaults' ); $defaults = isset( $defaults[ $category_id ] ) ? $defaults[ $category_id ] : array(); $out = array(); foreach ( self::attributes( $category_id ) as $def ) { if ( 'PRODUCT_PROPERTY' !== $def['type'] ) { continue; } $raw = $p->get_attribute( $def['name'] ); $val = null; if ( $raw ) { $raw = trim( explode( ',', $raw )[0] ); foreach ( isset( $def['values'] ) ? $def['values'] : array() as $v ) { if ( strtolower( $v['name'] ) === strtolower( $raw ) ) { $val = array( 'id' => $v['id'] ); } } if ( ! $val && ( ! isset( $def['is_customizable'] ) || $def['is_customizable'] ) ) { $val = array( 'name' => $raw ); } } if ( ! $val && ! empty( $defaults[ $def['id'] ] ) ) { $d = $defaults[ $def['id'] ]; $val = ctype_digit( (string) $d ) ? array( 'id' => (string) $d ) : array( 'name' => $d ); } if ( $val ) { $out[] = array( 'id' => $def['id'], 'values' => array( $val ) ); } elseif ( ! empty( $def['is_requried'] ) || ! empty( $def['is_required'] ) ) { $missing[] = $def['name']; } } return $out; } /** Pricing rule priority: product override > product > tag > category > global. */ public static function resolve_price( WC_Product $parent, $base_minor ) { $override = (float) get_post_meta( $parent->get_id(), '_okelsync_price', true ); if ( $override > 0 ) { return array( self::to_minor( $override ), null ); } $rules = Okelsync_Store::get( 'pricing_rules' ); $tags = wp_get_post_terms( $parent->get_id(), 'product_tag', array( 'fields' => 'slugs' ) ); $cats = array_map( 'strval', $parent->get_category_ids() ); $rule = null; foreach ( array( 'product', 'tag', 'category', 'global' ) as $scope ) { $best = null; foreach ( (array) $rules as $r ) { if ( empty( $r['enabled'] ) || $r['scope'] !== $scope ) { continue; } $ok = 'global' === $scope || ( 'product' === $scope && (string) $parent->get_id() === (string) $r['scope_value'] ) || ( 'tag' === $scope && in_array( $r['scope_value'], (array) $tags, true ) ) || ( 'category' === $scope && in_array( (string) $r['scope_value'], $cats, true ) ); if ( $ok && ( ! $best || $r['priority'] > $best['priority'] ) ) { $best = $r; } } if ( $best ) { $rule = $best; break; } } if ( ! $rule ) { return array( $base_minor, null ); } $price = (float) $base_minor; if ( 'pct' === $rule['type'] ) { $price *= 1 + $rule['value'] / 100; } elseif ( 'fixed_add' === $rule['type'] ) { $price += self::to_minor( $rule['value'] ); } elseif ( 'fixed_price' === $rule['type'] ) { $price = self::to_minor( $rule['value'] ); } elseif ( 'fx' === $rule['type'] ) { $price *= (float) $rule['fx_rate'] * ( 1 + $rule['value'] / 100 ); } if ( '99' === $rule['rounding'] ) { $price = ceil( $price / 100 ) * 100 - 1; } elseif ( '95' === $rule['rounding'] ) { $price = ceil( $price / 100 ) * 100 - 5; } elseif ( 'whole' === $rule['rounding'] ) { $price = round( $price / 100 ) * 100; } $price = (int) round( $price ); $cost = (float) get_post_meta( $parent->get_id(), '_okelsync_cost', true ); if ( ! $cost ) { $cost = (float) get_post_meta( $parent->get_id(), '_wc_cog_cost', true ); } if ( '' !== (string) $rule['min_margin'] && $cost > 0 && $price > 0 ) { $margin = ( $price - self::to_minor( $cost ) ) / $price * 100; if ( $margin < (float) $rule['min_margin'] ) { return array( $price, sprintf( 'Margin %.1f%% is below your minimum of %s%%', $margin, $rule['min_margin'] ) ); } } return array( $price, null ); } // ======================= product push ======================= public static function stock_of( WC_Product $p, WC_Product $parent ) { if ( Okelsync_Store::get( 'zero_stock_inactive' ) && 'publish' !== $parent->get_status() ) { return 0; } if ( $p->managing_stock() ) { $q = (int) $p->get_stock_quantity(); } else { $q = 'outofstock' === $p->get_stock_status() ? 0 : self::UNMANAGED_STOCK; } return max( 0, min( 99999, $q - (int) Okelsync_Store::get( 'stock_buffer' ) ) ); } /** Supplier and marketplace text TikTok reviewers reject. */ const SUPPLIER_TEXT = '/aliexpress|alibaba|1688\\.com|dhgate|temu|wholesale|drop-?ship|made in china|factory direct|\\b5[- ]?star\\b|five[- ]star|leave (us )?a review|good review/i'; /** Removes paragraphs/list items/sentences that mention suppliers or ask for reviews. */ public static function scrub_supplier_text( $html ) { $html = preg_replace_callback( '/<(p|li|h[1-6])[^>]*>[\\s\\S]*?<\\/\\1>/i', function ( $m ) { return preg_match( self::SUPPLIER_TEXT, $m[0] ) ? '' : $m[0]; }, (string) $html ); $sentences = preg_split( '/(?<=[.!?])\\s+/', $html ); return implode( ' ', array_filter( $sentences, function ( $x ) { return ! preg_match( self::SUPPLIER_TEXT, wp_strip_all_tags( $x ) ); } ) ); } /** Required certificates for a TikTok category (cached a week). */ public static function required_certifications( $category_id ) { $rules = self::cached( 'rules' . $category_id, WEEK_IN_SECONDS, function () use ( $category_id ) { return self::api( 'GET', '/product/202309/categories/' . rawurlencode( $category_id ) . '/rules' ); } ); $out = array(); foreach ( isset( $rules['product_certifications'] ) ? (array) $rules['product_certifications'] : array() as $c ) { if ( ! empty( $c['is_required'] ) ) { $out[] = $c['name']; } } return $out; } public static function allowed_html( $html, $fallback ) { $html = self::scrub_supplier_text( strip_shortcodes( (string) $html ) ); $html = wp_kses( $html, array( 'p' => array(), 'br' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'strong' => array(), 'b' => array(), 'em' => array(), 'i' => array(), 'u' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array() ) ); $html = trim( wpautop( $html ) ); return $html ? substr( $html, 0, 10000 ) : '
' . esc_html( $fallback ) . '
'; } /** What TikTok should show. Returns [snapshot|null, issues[], product_attributes, approval tips[]]. */ public static function build_desired( WC_Product $p ) { $issues = array(); $warnings = array(); list( $cat, $missing_woo ) = self::category_for( $p ); if ( ! $cat ) { // still show the listing-quality tips so the merchant can fix everything in one go $title_now = get_post_meta( $p->get_id(), '_okelsync_title', true ); $desc_now = Okelsync_Quality::fill_description( $p, self::allowed_html( $p->get_description() ? $p->get_description() : $p->get_short_description(), $p->get_name() ) ); list( $q_issues, $q_warnings ) = Okelsync_Quality::check_text( $p, $title_now ? $title_now : $p->get_name(), $desc_now ); $issues = array_merge( array( array( 'unmapped', sprintf( 'No TikTok category for "%s"', $missing_woo ), sprintf( 'Open Okel › Mapping and pick a TikTok category for "%s".', $missing_woo ) ) ), $q_issues ); return array( null, $issues, array(), $q_warnings ); } // documents TikTok demands for this category (UK: electrical labelling, toy labelling, cosmetics reports) try { $needed = self::required_certifications( $cat ); if ( $needed ) { $issues[] = array( 'failed', 'This TikTok category requires: ' . implode( ', ', $needed ), 'TikTok won’t approve the listing without these documents/photos. If you don’t have them, pick another category on Mapping or exclude the product.' ); } } catch ( Exception $e ) { unset( $e ); // rules are advisory; the push itself reports any hard error } $risk = $p->get_name() . ' ' . implode( ' ', wp_get_post_terms( $p->get_id(), 'product_cat', array( 'fields' => 'names' ) ) ); if ( preg_match( '/\\b(usb|rechargeable|battery|batteries|electric|electronic|charger|charging|led|heater|heated|massager|power ?bank|blender|bluetooth|wireless)\\b/i', $risk ) ) { $warnings[] = 'Looks electrical: in the UK TikTok asks for a photo of the CE/UKCA mark, WEEE label and Responsible Person, plus conformity documents. List it only if you have them.'; } if ( preg_match( '/\\b(toy|toys|plush|puzzle|doll|kids? game)\\b/i', $risk ) ) { $warnings[] = 'Looks like a toy: TikTok asks for toy labelling (CE mark photo). Baby products are sometimes mis-suggested as toys; check the category.'; } if ( preg_match( '/\\b(cosmetic|mascara|lash|lipstick|serum|cream|skincare|makeup|wax)\\b/i', $risk ) ) { $warnings[] = 'Cosmetics may need a CPSR report and a UK Responsible Person before TikTok approves them.'; } $missing = array(); $attrs = self::product_attributes( $p, $cat, $missing ); if ( $missing ) { $issues[] = array( 'failed', 'Missing required attributes: ' . implode( ', ', $missing ), 'Open Okel › Mapping › Attributes and set a default for: ' . implode( ', ', $missing ) . '.' ); } $title = get_post_meta( $p->get_id(), '_okelsync_title', true ); $title = $title ? $title : $p->get_name(); $images = array(); foreach ( array_merge( array( $p->get_image_id() ), $p->get_gallery_image_ids() ) as $img ) { if ( $img && ( $url = wp_get_attachment_url( $img ) ) ) { $images[] = $url; } } $images = array_slice( array_values( array_unique( $images ) ), 0, 9 ); if ( ! $images ) { $issues[] = array( 'failed', 'Product has no images', 'Add a product image (JPG/PNG, 600×600 px or larger).' ); } elseif ( count( $images ) < 5 ) { $warnings[] = sprintf( 'Only %d image%s: listings with 5–9 clear images (main image on a plain background) get approved and sell better.', count( $images ), count( $images ) > 1 ? 's' : '' ); } if ( ! (float) $p->get_weight() ) { $issues[] = array( 'failed', 'Product has no weight', 'Add a weight in Product data › Shipping.' ); } $skus = array(); $rows = $p->is_type( 'variable' ) ? array_filter( array_map( 'wc_get_product', $p->get_children() ) ) : array( $p ); foreach ( $rows as $v ) { list( $price, $blocked ) = self::resolve_price( $p, self::to_minor( $v->get_price() ) ); if ( $blocked ) { $issues[] = array( 'failed', 'Price blocked: ' . $blocked, 'Adjust the pricing rule or minimum margin in Okel › Pricing.' ); } if ( $price <= 0 ) { $issues[] = array( 'failed', 'Price is zero', 'Set a regular price in WooCommerce.' ); } $attrs_v = array(); if ( $v->is_type( 'variation' ) ) { foreach ( $v->get_variation_attributes() as $k => $val ) { $tax = str_replace( 'attribute_', '', $k ); if ( taxonomy_exists( $tax ) ) { $term = get_term_by( 'slug', $val, $tax ); $val = $term ? $term->name : $val; } $attrs_v[ wc_attribute_label( $tax, $p ) ] = $val; } } // every TikTok SKU needs a seller SKU that maps back to WooCommerce $seller_sku = $v->get_sku() ? $v->get_sku() : ( $v->is_type( 'variation' ) ? 'WC-' . $p->get_id() . '-' . $v->get_id() : 'WC-' . $p->get_id() ); $skus[] = array( 'key' => 'v' . $v->get_id(), 'id' => $v->get_id(), 'sku' => $seller_sku, 'attrs' => $attrs_v, 'price' => $price, 'stock' => self::stock_of( $v, $p ) ); } if ( ! $skus ) { $issues[] = array( 'failed', 'Variable product has no variations', 'Create at least one variation.' ); } $description = self::allowed_html( $p->get_description() ? $p->get_description() : $p->get_short_description(), $title ); $description = Okelsync_Quality::fill_description( $p, $description ); list( $text_issues, $text_warnings ) = Okelsync_Quality::check_text( $p, $title, $description ); $issues = array_merge( $issues, $text_issues ); $warnings = array_merge( $warnings, $text_warnings ); $text_length = strlen( trim( wp_strip_all_tags( $description ) ) ); if ( $text_length < 500 ) { $warnings[] = sprintf( 'Description is %d characters: TikTok flags descriptions under 500. Add a problem hook, 5–7 benefit bullets, who it’s for, a safety line and “Includes: …”.', $text_length ); } $snap = array( 'title' => $title, 'description' => $description, 'images' => $images, 'category' => $cat, 'skus' => $skus, ); return array( $snap, $issues, $attrs, $warnings ); } private static function diff( $prev, $next ) { if ( ! $prev ) { return self::PROTECTABLE; } $c = array(); foreach ( array( 'title', 'description', 'images' ) as $f ) { if ( wp_json_encode( $prev[ $f ] ) !== wp_json_encode( $next[ $f ] ) ) { $c[] = $f; } } $shape = function ( $s ) { return wp_json_encode( array( $s['category'], array_map( function ( $k ) { return array( $k['key'], $k['sku'], $k['attrs'] ); }, $s['skus'] ) ) ); }; if ( $shape( $prev ) !== $shape( $next ) ) { $c[] = 'variants'; } foreach ( array( 'price', 'stock' ) as $f ) { $a = wp_json_encode( array_map( function ( $k ) use ( $f ) { return array( $k['key'], $k[ $f ] ); }, $prev['skus'] ) ); $b = wp_json_encode( array_map( function ( $k ) use ( $f ) { return array( $k['key'], $k[ $f ] ); }, $next['skus'] ) ); if ( $a !== $b ) { $c[] = $f; } } return $c; } private static function queue_approval( $product_id, $field, $old, $new ) { global $wpdb; $t = $wpdb->prefix . 'okelsync_approvals'; $nv = wp_json_encode( $new ); $last = $wpdb->get_row( $wpdb->prepare( "SELECT status, new_value FROM %i WHERE product_id = %d AND field = %s AND status IN ('pending','rejected') ORDER BY id DESC LIMIT 1", $t, $product_id, $field ), ARRAY_A ); if ( $last && $last['new_value'] === $nv ) { return; } $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'superseded' WHERE product_id = %d AND field = %s AND status = 'pending'", $t, $product_id, $field ) ); $wpdb->insert( $t, array( 'product_id' => $product_id, 'field' => $field, 'old_value' => wp_json_encode( $old ), 'new_value' => $nv, 'status' => 'pending', 'created_at' => current_time( 'mysql', true ) ) ); } private static function upload_images( array $urls ) { $cache = get_option( 'okelsync_image_cache', array() ); $out = array(); foreach ( $urls as $url ) { $k = md5( $url ); if ( isset( $cache[ $k ] ) ) { $out[] = array( 'uri' => $cache[ $k ] ); continue; } $res = wp_remote_get( $url, array( 'timeout' => 30 ) ); if ( is_wp_error( $res ) || 200 !== wp_remote_retrieve_response_code( $res ) ) { throw new Okelsync_Fix_Required( esc_html( 'Could not download image ' . $url ), 'Make sure product images are publicly reachable (hotlink protection off).' ); } $bytes = wp_remote_retrieve_body( $res ); if ( strlen( $bytes ) > 5 * MB_IN_BYTES ) { throw new Okelsync_Fix_Required( esc_html( 'Image larger than 5 MB: ' . $url ), 'Compress the image below 5 MB.' ); } list( $bytes, $suffix ) = Okelsync_Quality::square_pad( $bytes ); $dims = function_exists( 'getimagesizefromstring' ) ? @getimagesizefromstring( $bytes ) : false; // phpcs:ignore WordPress.PHP.NoSilencedErrors if ( $dims && ( $dims[0] < Okelsync_Quality::MIN_SIDE || $dims[1] < Okelsync_Quality::MIN_SIDE ) ) { throw new Okelsync_Fix_Required( esc_html( sprintf( 'Image %s is %d×%d px', basename( (string) wp_parse_url( $url, PHP_URL_PATH ) ), $dims[0], $dims[1] ) ), 'TikTok needs images of at least 600×600 px. Replace it in WooCommerce with a larger, square image on a plain background, or switch on "Square-pad images" in Okel › Settings.' ); } $filename = basename( (string) wp_parse_url( $url, PHP_URL_PATH ) ); $filename = $suffix ? preg_replace( '/\\.[a-z0-9]+$/i', '', $filename ) . $suffix : $filename; $payload = array( 'data' => array( 'filename' => $filename, 'bytes' => $bytes ), 'use_case' => 'MAIN_IMAGE' ); try { $up = self::api( 'POST', '/product/202309/images/upload', array(), null, $payload ); } catch ( Okelsync_Api_Exception $e ) { if ( ! $e->retryable ) { throw $e; } // TikTok image uploads stall now and then; one retry clears most of them. sleep( 2 ); $up = self::api( 'POST', '/product/202309/images/upload', array(), null, $payload ); } $cache[ $k ] = $up['uri']; $out[] = array( 'uri' => $up['uri'] ); } update_option( 'okelsync_image_cache', $cache, false ); return $out; } private static function region_units() { $shop = Okelsync_Store::shop(); return ( isset( $shop['region'] ) && 'US' === $shop['region'] ) ? array( 'POUND', 'INCH' ) : array( 'KILOGRAM', 'CENTIMETER' ); } private static function to_input( WC_Product $p, $snap, $attrs, $sku_ids = array() ) { list( $wu, $du ) = self::region_units(); $currency = self::currency(); $wh = self::warehouse_id(); $kg = wc_get_weight( (float) $p->get_weight(), 'kg' ); $input = array( 'title' => $snap['title'], 'description' => $snap['description'], 'category_id' => $snap['category'], 'main_images' => self::upload_images( $snap['images'] ), 'package_weight' => array( 'value' => (string) round( 'POUND' === $wu ? $kg / 0.453592 : $kg, 3 ), 'unit' => $wu ), 'product_attributes' => $attrs, 'skus' => array(), ); if ( $p->get_length() && $p->get_width() && $p->get_height() ) { $conv = function ( $v ) use ( $du ) { $cm = wc_get_dimension( (float) $v, 'cm' ); return (string) max( 1, round( 'INCH' === $du ? $cm / 2.54 : $cm ) ); }; $input['package_dimensions'] = array( 'length' => $conv( $p->get_length() ), 'width' => $conv( $p->get_width() ), 'height' => $conv( $p->get_height() ), 'unit' => $du ); } foreach ( $snap['skus'] as $s ) { $sku = array( 'seller_sku' => $s['sku'], 'sales_attributes' => array(), 'price' => array( 'amount' => self::from_minor( $s['price'] ), 'currency' => $currency ), 'inventory' => array( array( 'warehouse_id' => $wh, 'quantity' => $s['stock'] ) ), ); foreach ( $s['attrs'] as $name => $val ) { $sku['sales_attributes'][] = array( 'name' => $name, 'value_name' => $val ); } if ( ! empty( $sku_ids[ $s['key'] ] ) ) { $sku['id'] = $sku_ids[ $s['key'] ]; } $input['skus'][] = $sku; } return $input; } private static function save_sku_ids( $snap, $returned ) { foreach ( $snap['skus'] as $i => $s ) { $match = null; foreach ( (array) $returned as $r ) { if ( $s['sku'] && isset( $r['seller_sku'] ) && $r['seller_sku'] === $s['sku'] ) { $match = $r; } } if ( ! $match && isset( $returned[ $i ] ) ) { $match = $returned[ $i ]; } if ( $match ) { update_post_meta( $s['id'], '_okelsync_sku_id', $match['id'] ); } } } private static function sku_ids( $snap ) { $ids = array(); foreach ( $snap['skus'] as $s ) { $ids[ $s['key'] ] = get_post_meta( $s['id'], '_okelsync_sku_id', true ); } return $ids; } public static function push_product( $product_id, array $approved = array(), array $only = array() ) { $p = wc_get_product( $product_id ); if ( ! $p || $p->is_type( 'variation' ) ) { return; } if ( 'yes' === get_post_meta( $product_id, '_okelsync_exclude', true ) ) { self::set_status( $product_id, 'excluded' ); return; } list( $snap, $issues, $attrs ) = self::build_desired( $p ); if ( ! $snap || $issues ) { self::set_status( $product_id, $issues[0][0], implode( '; ', wp_list_pluck( $issues, 1 ) ), implode( ' ', wp_list_pluck( $issues, 2 ) ) ); Okelsync_Store::log( 'woo_to_tiktok', 'product', $product_id, 'error', $p->get_name() . ': ' . $issues[0][1], $issues[0][2] ); return; } $s = Okelsync_Store::get(); $approved = in_array( 'all', $approved, true ) ? self::PROTECTABLE : $approved; $tiktok_id = get_post_meta( $product_id, '_okelsync_tiktok_id', true ); $prev = json_decode( (string) get_post_meta( $product_id, '_okelsync_last_pushed', true ), true ); if ( ! $tiktok_id ) { if ( ! $approved && ( ! $s['auto_new'] || 'woo_to_tiktok' !== $s['direction'] ) ) { self::queue_approval( $product_id, 'create', null, array( 'title' => $snap['title'], 'skus' => count( $snap['skus'] ), 'images' => count( $snap['images'] ) ) ); self::set_status( $product_id, 'awaiting_approval' ); return; } $r = self::api( 'POST', '/product/202309/products', array(), self::to_input( $p, $snap, $attrs ) ); update_post_meta( $product_id, '_okelsync_tiktok_id', $r['product_id'] ); update_post_meta( $product_id, '_okelsync_last_pushed', wp_json_encode( $snap ) ); update_post_meta( $product_id, '_okelsync_synced_at', time() ); self::save_sku_ids( $snap, $r['skus'] ); self::set_status( $product_id, 'synced' ); self::mark_approved( $product_id, array( 'create' ) ); Okelsync_Store::log( 'woo_to_tiktok', 'product', $product_id, 'success', sprintf( '%s: listed on TikTok (%d SKU)', $p->get_name(), count( $snap['skus'] ) ) ); return; } $changed = self::diff( $prev, $snap ); if ( $only ) { $changed = array_values( array_intersect( $changed, $only ) ); } // TikTok is the catalogue master: WooCommerce edits never overwrite the listing, only stock still flows if ( 'tiktok_to_woo' === $s['direction'] && ! $approved ) { $changed = array_values( array_intersect( $changed, array( 'stock' ) ) ); } if ( ! $s['sync_prices'] ) { $changed = array_values( array_diff( $changed, array( 'price' ) ) ); } if ( ! $s['sync_inventory'] || 'tiktok' === $s['inventory_source'] ) { $changed = array_values( array_diff( $changed, array( 'stock' ) ) ); } if ( ! $changed ) { self::set_status( $product_id, 'synced' ); return; } $allowed = array(); foreach ( $changed as $f ) { if ( in_array( $f, $approved, true ) || ! empty( $s[ 'auto_' . $f ] ) ) { $allowed[] = $f; } else { self::queue_approval( $product_id, $f, self::field_value( $prev, $f ), self::field_value( $snap, $f ) ); } } if ( ! $allowed ) { return; } // unapproved fields keep what TikTok already has $target = $snap; foreach ( array( 'title', 'description', 'images' ) as $f ) { if ( ! in_array( $f, $allowed, true ) ) { $target[ $f ] = $prev[ $f ]; } } if ( ! in_array( 'variants', $allowed, true ) ) { $target['skus'] = $prev['skus']; $target['category'] = $prev['category']; } foreach ( $target['skus'] as &$k ) { foreach ( array( 'price', 'stock' ) as $f ) { $src = in_array( $f, $allowed, true ) ? $snap : $prev; foreach ( $src['skus'] as $x ) { if ( $x['key'] === $k['key'] ) { $k[ $f ] = $x[ $f ]; } } } } unset( $k ); $ids = self::sku_ids( $target ); $full = array_intersect( $allowed, array( 'title', 'description', 'images', 'variants' ) ); if ( $full ) { $r = self::api( 'PUT', '/product/202309/products/' . $tiktok_id, array(), self::to_input( $p, $target, $attrs, $ids ) ); self::save_sku_ids( $target, $r['skus'] ); } else { $currency = self::currency(); $wh = self::warehouse_id(); if ( in_array( 'price', $allowed, true ) ) { $body = array(); foreach ( $target['skus'] as $k ) { if ( ! empty( $ids[ $k['key'] ] ) ) { $body[] = array( 'id' => $ids[ $k['key'] ], 'price' => array( 'amount' => self::from_minor( $k['price'] ), 'currency' => $currency ) ); } } self::api( 'POST', '/product/202309/products/' . $tiktok_id . '/prices/update', array(), array( 'skus' => $body ) ); } if ( in_array( 'stock', $allowed, true ) ) { $body = array(); foreach ( $target['skus'] as $k ) { if ( ! empty( $ids[ $k['key'] ] ) ) { $body[] = array( 'id' => $ids[ $k['key'] ], 'inventory' => array( array( 'warehouse_id' => $wh, 'quantity' => $k['stock'] ) ) ); } } self::api( 'POST', '/product/202309/products/' . $tiktok_id . '/inventory/update', array(), array( 'skus' => $body ) ); } } update_post_meta( $product_id, '_okelsync_last_pushed', wp_json_encode( $target ) ); update_post_meta( $product_id, '_okelsync_synced_at', time() ); self::set_status( $product_id, 'synced' ); self::mark_approved( $product_id, $allowed ); Okelsync_Store::log( 'woo_to_tiktok', 'product', $product_id, 'success', sprintf( '%s: updated on TikTok (%s)', $p->get_name(), implode( ', ', $allowed ) ) ); } private static function field_value( $snap, $f ) { if ( ! $snap ) { return null; } if ( in_array( $f, array( 'price', 'stock' ), true ) ) { return array_map( function ( $k ) use ( $f ) { return array( 'sku' => $k['sku'] ? $k['sku'] : $k['key'], $f => $k[ $f ] ); }, $snap['skus'] ); } if ( 'variants' === $f ) { return array_map( function ( $k ) { return array( 'sku' => $k['sku'], 'attrs' => $k['attrs'] ); }, $snap['skus'] ); } return $snap[ $f ]; } private static function mark_approved( $product_id, $fields ) { global $wpdb; foreach ( $fields as $f ) { $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}okelsync_approvals SET status = 'approved' WHERE product_id = %d AND field = %s AND status = 'pending'", $product_id, $f ) ); } } // ======================= orders ======================= private static function find_wc_product( $sku_id, $seller_sku ) { global $wpdb; $pid = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_okelsync_sku_id' AND meta_value = %s LIMIT 1", $sku_id ) ); if ( ! $pid && $seller_sku ) { $pid = wc_get_product_id_by_sku( $seller_sku ); } // fallback seller SKUs Okel generates for products without a WooCommerce SKU: WC-{product}[-{variation}] if ( ! $pid && $seller_sku && preg_match( '/^WC-(\\d+)(?:-(\\d+))?$/', $seller_sku, $m ) ) { $pid = ! empty( $m[2] ) ? (int) $m[2] : (int) $m[1]; } return $pid ? wc_get_product( $pid ) : null; } private static function map_status( $tiktok, $refunded = false ) { if ( $refunded ) { return 'refunded'; } $map = array( 'UNPAID' => 'pending', 'ON_HOLD' => 'on-hold', 'AWAITING_SHIPMENT' => 'processing', 'PARTIALLY_SHIPPING' => 'processing', 'AWAITING_COLLECTION' => 'processing', 'IN_TRANSIT' => Okelsync_Store::get( 'shipped_status' ), 'DELIVERED' => Okelsync_Store::get( 'shipped_status' ), 'COMPLETED' => 'completed', 'CANCELLED' => 'cancelled' ); return isset( $map[ $tiktok ] ) ? $map[ $tiktok ] : 'processing'; } public static function find_order( $tiktok_id ) { $orders = wc_get_orders( array( 'limit' => 1, 'meta_key' => '_okelsync_order_id', 'meta_value' => $tiktok_id ) ); // phpcs:ignore WordPress.DB.SlowDBQuery return $orders ? $orders[0] : null; } public static function ingest_order( $tiktok_id ) { if ( ! Okelsync_Store::get( 'sync_orders' ) ) { return; } $d = self::api( 'GET', '/order/202309/orders', array( 'ids' => $tiktok_id ) ); if ( empty( $d['orders'][0] ) ) { throw new Okelsync_Fix_Required( esc_html( 'TikTok order ' . $tiktok_id . ' not found' ), 'It may belong to another shop.' ); } $o = $d['orders'][0]; $refunded = 'CANCELLED' === $o['status'] && ! empty( $o['cancel_reason'] ) && preg_match( '/refund|return/i', $o['cancel_reason'] ); $status = self::map_status( $o['status'], $refunded ); $existing = self::find_order( $o['id'] ); $rank = array( 'pending' => 0, 'on-hold' => 1, 'processing' => 2, 'completed' => 3, 'cancelled' => 4, 'refunded' => 5 ); if ( $existing ) { $cur = $existing->get_status(); if ( $cur !== $status && ( isset( $rank[ $cur ] ) ? $rank[ $cur ] : 0 ) <= $rank[ $status ] ) { $existing->update_status( $status, sprintf( 'Okel: TikTok status is now %s.', $o['status'] ) ); Okelsync_Store::log( 'tiktok_to_woo', 'order', $o['id'], 'success', sprintf( 'Order #%d → %s (TikTok %s)', $existing->get_id(), $status, $o['status'] ) ); } return; } if ( in_array( $o['status'], array( 'UNPAID', 'CANCELLED' ), true ) ) { Okelsync_Store::log( 'tiktok_to_woo', 'order', $o['id'], 'skipped', sprintf( 'Order %s is %s; it will be created once paid', $o['id'], $o['status'] ) ); return; } $order = wc_create_order( array( 'status' => 'pending' ) ); $groups = array(); foreach ( $o['line_items'] as $li ) { $k = $li['sku_id']; if ( ! isset( $groups[ $k ] ) ) { $groups[ $k ] = array( 'li' => $li, 'qty' => 0 ); } $groups[ $k ]['qty']++; } $unmatched = array(); foreach ( $groups as $g ) { $li = $g['li']; $product = self::find_wc_product( $li['sku_id'], isset( $li['seller_sku'] ) ? $li['seller_sku'] : '' ); $total = (float) $li['sale_price'] * $g['qty']; if ( $product ) { self::deduct_snapshot( $product, $g['qty'] ); $order->add_product( $product, $g['qty'], array( 'subtotal' => $total, 'total' => $total ) ); } else { $unmatched[] = isset( $li['seller_sku'] ) ? $li['seller_sku'] : $li['sku_id']; $item = new WC_Order_Item_Product(); $item->set_props( array( 'name' => $li['product_name'], 'quantity' => $g['qty'], 'subtotal' => $total, 'total' => $total ) ); $order->add_item( $item ); } } $a = isset( $o['recipient_address'] ) ? $o['recipient_address'] : array(); $name = explode( ' ', isset( $a['name'] ) ? $a['name'] : '', 2 ); $addr = array( 'first_name' => isset( $a['first_name'] ) ? $a['first_name'] : $name[0], 'last_name' => isset( $a['last_name'] ) ? $a['last_name'] : ( isset( $name[1] ) ? $name[1] : '' ), 'address_1' => isset( $a['address_line1'] ) ? $a['address_line1'] : ( isset( $a['full_address'] ) ? $a['full_address'] : '' ), 'address_2' => isset( $a['address_line2'] ) ? $a['address_line2'] : '', 'postcode' => isset( $a['postal_code'] ) ? $a['postal_code'] : '', 'country' => isset( $a['region_code'] ) ? $a['region_code'] : '', 'phone' => isset( $a['phone_number'] ) ? $a['phone_number'] : '', ); foreach ( isset( $a['district_info'] ) ? $a['district_info'] : array() as $di ) { if ( preg_match( '/city|town/i', $di['address_level_name'] ) ) { $addr['city'] = $di['address_name']; } } $order->set_address( $addr, 'shipping' ); $order->set_address( array_merge( $addr, array( 'email' => isset( $o['buyer_email'] ) ? $o['buyer_email'] : '' ) ), 'billing' ); $ship = new WC_Order_Item_Shipping(); $ship->set_props( array( 'method_title' => 'TikTok Shop', 'method_id' => 'tiktok_shop', 'total' => isset( $o['payment']['shipping_fee'] ) ? $o['payment']['shipping_fee'] : 0 ) ); $order->add_item( $ship ); $order->set_currency( $o['payment']['currency'] ); $order->set_payment_method( 'tiktok_shop' ); $order->set_payment_method_title( 'TikTok Shop' ); $order->set_customer_note( isset( $o['buyer_message'] ) ? $o['buyer_message'] : '' ); $order->update_meta_data( '_okelsync_order_id', $o['id'] ); $order->update_meta_data( '_okelsync_shipping_type', isset( $o['shipping_type'] ) ? $o['shipping_type'] : 'SELLER' ); $order->update_meta_data( '_okelsync_line_items', wp_json_encode( wp_list_pluck( $o['line_items'], 'id' ) ) ); $order->update_meta_data( '_okelsync_package_id', isset( $o['packages'][0]['id'] ) ? $o['packages'][0]['id'] : '' ); $order->update_meta_data( '_okelsync_delivery_option', isset( $o['delivery_option_id'] ) ? $o['delivery_option_id'] : '' ); if ( isset( $o['fulfillment_type'] ) && 'FULFILLMENT_BY_TIKTOK' === $o['fulfillment_type'] ) { $order->get_data_store()->set_stock_reduced( $order->get_id(), true ); } $order->calculate_totals( false ); $order->save(); $order->update_status( $status, 'Okel: imported from TikTok Shop.' ); if ( $unmatched ) { $order->add_order_note( 'Okel: these TikTok SKUs are not linked to WooCommerce products, so stock was not reduced: ' . implode( ', ', $unmatched ) ); } Okelsync_Store::log( 'tiktok_to_woo', 'order', $o['id'], 'success', sprintf( 'Created order #%d from TikTok order %s', $order->get_id(), $o['id'] ) ); } /** TikTok deducts its own stock on order: mirror it in our record of what TikTok shows. */ private static function deduct_snapshot( WC_Product $sold, $qty ) { $parent = $sold->get_parent_id() ? $sold->get_parent_id() : $sold->get_id(); $snap = json_decode( (string) get_post_meta( $parent, '_okelsync_last_pushed', true ), true ); if ( empty( $snap['skus'] ) ) { return; } foreach ( $snap['skus'] as &$k ) { if ( 'v' . $sold->get_id() === $k['key'] ) { $k['stock'] = max( 0, (int) $k['stock'] - (int) $qty ); } } unset( $k ); update_post_meta( $parent, '_okelsync_last_pushed', wp_json_encode( $snap ) ); } public static function poll_orders() { $last = (int) get_option( 'okelsync_last_poll', time() - 3 * DAY_IN_SECONDS ); $start = time(); $token = null; for ( $i = 0; $i < 40; $i++ ) { $d = self::api( 'POST', '/order/202309/orders/search', array( 'page_size' => 50, 'page_token' => $token, 'sort_field' => 'update_time', 'sort_order' => 'ASC' ), array( 'update_time_ge' => $last - 600 ) ); foreach ( isset( $d['orders'] ) ? $d['orders'] : array() as $o ) { Okelsync_Store::enqueue( 'order.ingest', array( 'id' => $o['id'] ), 'order.ingest:' . $o['id'] ); } $token = isset( $d['next_page_token'] ) ? $d['next_page_token'] : null; if ( ! $token ) { break; } } update_option( 'okelsync_last_poll', $start, false ); } // ======================= fulfillment ======================= public static function tracking_of( WC_Order $order ) { $t = $order->get_meta( '_okelsync_tracking_number' ); if ( $t ) { return array( $t, $order->get_meta( '_okelsync_carrier' ) ); } $items = $order->get_meta( '_wc_shipment_tracking_items' ); if ( is_array( $items ) && $items ) { $last = end( $items ); if ( ! empty( $last['tracking_number'] ) ) { $carrier = ! empty( $last['custom_tracking_provider'] ) ? $last['custom_tracking_provider'] : ( isset( $last['tracking_provider'] ) ? $last['tracking_provider'] : '' ); return array( $last['tracking_number'], $carrier ); } } $t = $order->get_meta( '_okelsync_supplier_tracking' ); return $t ? array( $t, $order->get_meta( '_okelsync_supplier_carrier' ) ) : null; } public static function providers( $delivery_option ) { return self::cached( 'providers' . $delivery_option, DAY_IN_SECONDS, function () use ( $delivery_option ) { $d = self::api( 'GET', '/logistics/202309/delivery_options/' . $delivery_option . '/shipping_providers' ); return isset( $d['shipping_providers'] ) ? $d['shipping_providers'] : array(); } ); } private static function match_provider( $providers, $carrier ) { $n = function ( $s ) { return preg_replace( '/[^a-z0-9]/', '', strtolower( (string) $s ) ); }; $c = $n( $carrier ); if ( ! $c ) { return null; } foreach ( $providers as $p ) { if ( $n( $p['name'] ) === $c ) { return $p['id']; } } foreach ( $providers as $p ) { if ( false !== strpos( $n( $p['name'] ), $c ) || false !== strpos( $c, $n( $p['name'] ) ) ) { return $p['id']; } } return null; } public static function push_tracking( $order_id ) { if ( ! Okelsync_Store::get( 'sync_fulfillment' ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order || ! $order->get_meta( '_okelsync_order_id' ) ) { return; } $tiktok_id = $order->get_meta( '_okelsync_order_id' ); $package = $order->get_meta( '_okelsync_package_id' ); if ( 'TIKTOK' === $order->get_meta( '_okelsync_shipping_type' ) ) { if ( $package ) { self::api( 'POST', '/fulfillment/202309/packages/' . $package . '/ship', array(), array( 'handover_method' => 'DROP_OFF' ) ); } return; } $t = self::tracking_of( $order ); if ( ! $t ) { return; } list( $number, $carrier ) = $t; if ( $order->get_meta( '_okelsync_tracking_pushed' ) === $number ) { return; } $opt = $order->get_meta( '_okelsync_delivery_option' ); $providers = self::providers( $opt ? $opt : 'default' ); $pid = $order->get_meta( '_okelsync_provider_id' ); $pid = $pid ? $pid : self::match_provider( $providers, $carrier ); $pid = $pid ? $pid : self::match_provider( $providers, Okelsync_Store::get( 'default_carrier' ) ); if ( ! $pid ) { throw new Okelsync_Fix_Required( esc_html( sprintf( 'Carrier "%s" is not a TikTok shipping provider', $carrier ) ), esc_html( 'Pick the carrier in the order\'s Okel box (TikTok accepts: ' . implode( ', ', array_slice( wp_list_pluck( $providers, 'name' ), 0, 8 ) ) . '), or set a default carrier in Settings.' ) ); } if ( $order->get_meta( '_okelsync_tracking_pushed' ) && $package ) { self::api( 'POST', '/fulfillment/202309/packages/' . $package . '/shipping_info/update', array(), array( 'tracking_number' => $number, 'shipping_provider_id' => $pid ) ); } else { $r = self::api( 'POST', '/fulfillment/202309/orders/' . $tiktok_id . '/packages', array(), array( 'order_line_item_ids' => (array) json_decode( $order->get_meta( '_okelsync_line_items' ), true ), 'tracking_number' => $number, 'shipping_provider_id' => $pid ) ); if ( ! empty( $r['package_id'] ) ) { $order->update_meta_data( '_okelsync_package_id', $r['package_id'] ); } } $order->update_meta_data( '_okelsync_tracking_pushed', $number ); $order->save(); $order->add_order_note( sprintf( 'Okel: tracking %s (%s) sent to TikTok.', $number, $carrier ) ); Okelsync_Store::log( 'woo_to_tiktok', 'fulfillment', $tiktok_id, 'success', sprintf( 'Tracking %s pushed to TikTok order %s', $number, $tiktok_id ) ); } // ======================= reverse import, reconcile, tokens, sweep ======================= public static function reverse_import() { $token = null; $counts = array( 'linked' => 0, 'created' => 0, 'skipped' => 0, 'already' => 0 ); for ( $i = 0; $i < 200; $i++ ) { $d = self::api( 'POST', '/product/202309/products/search', array( 'page_size' => 50, 'page_token' => $token ), array( 'status' => 'ALL' ) ); foreach ( isset( $d['products'] ) ? $d['products'] : array() as $tp ) { $counts[ self::link_or_create( $tp, 'tiktok_to_woo' === Okelsync_Store::get( 'direction' ) ) ]++; } $token = isset( $d['next_page_token'] ) ? $d['next_page_token'] : null; if ( ! $token ) { break; } } Okelsync_Store::log( 'tiktok_to_woo', 'catalog', null, 'success', sprintf( 'TikTok catalogue: linked %d by SKU, created %d in WooCommerce, %d without a matching SKU', $counts['linked'], $counts['created'], $counts['skipped'] ) ); } /** Links a TikTok listing to the Woo product with the same SKU, or creates it in WooCommerce when $create. */ public static function link_or_create( array $tp, $create ) { $parent = self::linked_parent( $tp['id'] ); if ( $parent ) { return 'already'; } foreach ( $tp['skus'] as $s ) { $id = ! empty( $s['seller_sku'] ) ? wc_get_product_id_by_sku( $s['seller_sku'] ) : 0; if ( $id ) { update_post_meta( $id, '_okelsync_sku_id', $s['id'] ); $p = wc_get_product( $id ); $parent = $p->get_parent_id() ? $p->get_parent_id() : $id; } } if ( $parent ) { update_post_meta( $parent, '_okelsync_tiktok_id', $tp['id'] ); self::set_status( $parent, 'synced' ); // baseline = what TikTok has, so protected fields need approval before overwrite list( $snap ) = self::build_desired( wc_get_product( $parent ) ); if ( $snap ) { foreach ( $snap['skus'] as &$k ) { foreach ( $tp['skus'] as $s ) { if ( $k['sku'] && isset( $s['seller_sku'] ) && $s['seller_sku'] === $k['sku'] ) { $k['stock'] = isset( $s['inventory'][0]['quantity'] ) ? (int) $s['inventory'][0]['quantity'] : 0; $k['price'] = self::to_minor( isset( $s['price']['sale_price'] ) ? $s['price']['sale_price'] : 0 ); } } } unset( $k ); $snap['title'] = $tp['title']; update_post_meta( $parent, '_okelsync_last_pushed', wp_json_encode( $snap ) ); } return 'linked'; } if ( $create ) { self::create_from_tiktok( $tp ); return 'created'; } return 'skipped'; } /** The WooCommerce product linked to a TikTok listing, if any. */ public static function linked_parent( $tiktok_id ) { $ids = get_posts( array( 'post_type' => 'product', 'post_status' => 'any', 'numberposts' => 1, 'fields' => 'ids', 'meta_key' => '_okelsync_tiktok_id', 'meta_value' => (string) $tiktok_id ) ); // phpcs:ignore WordPress.DB.SlowDBQuery return $ids ? (int) $ids[0] : 0; } /** One page of TikTok listings for the Products › TikTok view. */ public static function tiktok_listings( $page_token = null ) { $d = self::api( 'POST', '/product/202309/products/search', array( 'page_size' => 50, 'page_token' => $page_token ), array( 'status' => 'ALL' ) ); return array( 'products' => isset( $d['products'] ) ? $d['products'] : array(), 'next' => isset( $d['next_page_token'] ) ? $d['next_page_token'] : null ); } public static function tiktok_listing( $id ) { return self::api( 'GET', '/product/202309/products/' . rawurlencode( $id ) ); } /** Imports (links or creates) one TikTok listing into WooCommerce. */ public static function import_listing( $id ) { $r = self::link_or_create( self::tiktok_listing( $id ), true ); Okelsync_Store::log( 'tiktok_to_woo', 'product', $id, 'success', 'already' === $r ? sprintf( 'TikTok listing %s is already in WooCommerce', $id ) : sprintf( 'TikTok listing %s %s WooCommerce', $id, 'linked' === $r ? 'linked to the matching SKU in' : 'imported into' ) ); return $r; } /** * Edits price/stock of a TikTok listing (TikTok → Woo mode). TikTok is updated first; the linked * WooCommerce product/variation gets the same values so both sides match. * * @param array $skus [ tiktok_sku_id => [ 'price' => '12.99'|null, 'stock' => int|null ] ] */ public static function save_listing( $id, array $skus ) { $currency = self::currency(); $prices = array(); $stocks = array(); foreach ( $skus as $sku_id => $v ) { if ( isset( $v['price'] ) && '' !== $v['price'] && (float) $v['price'] > 0 ) { $prices[] = array( 'id' => (string) $sku_id, 'price' => array( 'amount' => number_format( (float) $v['price'], 2, '.', '' ), 'currency' => $currency ) ); } if ( isset( $v['stock'] ) && '' !== $v['stock'] ) { $stocks[ (string) $sku_id ] = max( 0, min( 99999, (int) $v['stock'] ) ); } } if ( $prices ) { self::api( 'POST', '/product/202309/products/' . rawurlencode( $id ) . '/prices/update', array(), array( 'skus' => $prices ) ); } if ( $stocks ) { $tp = self::tiktok_listing( $id ); $wh = Okelsync_Store::get( 'warehouse_id' ); $wh = $wh ? $wh : ( isset( $tp['skus'][0]['inventory'][0]['warehouse_id'] ) ? $tp['skus'][0]['inventory'][0]['warehouse_id'] : self::warehouse_id() ); $body = array(); foreach ( $stocks as $sku_id => $q ) { $body[] = array( 'id' => $sku_id, 'inventory' => array( array( 'warehouse_id' => $wh, 'quantity' => $q ) ) ); } self::api( 'POST', '/product/202309/products/' . rawurlencode( $id ) . '/inventory/update', array(), array( 'skus' => $body ) ); } $parent = self::linked_parent( $id ); if ( $parent ) { $snap = json_decode( (string) get_post_meta( $parent, '_okelsync_last_pushed', true ), true ); foreach ( $skus as $sku_id => $v ) { global $wpdb; $wc_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_okelsync_sku_id' AND meta_value = %s LIMIT 1", (string) $sku_id ) ); $p = $wc_id ? wc_get_product( $wc_id ) : null; if ( ! $p ) { continue; } if ( isset( $v['price'] ) && '' !== $v['price'] && (float) $v['price'] > 0 ) { $p->set_regular_price( number_format( (float) $v['price'], 2, '.', '' ) ); } if ( isset( $stocks[ (string) $sku_id ] ) ) { $p->set_manage_stock( true ); $p->set_stock_quantity( $stocks[ (string) $sku_id ] ); } // keep our record of what TikTok shows in step first, so the Woo save doesn't push it back if ( ! empty( $snap['skus'] ) ) { foreach ( $snap['skus'] as &$k ) { if ( 'v' . $p->get_id() === $k['key'] ) { if ( isset( $v['price'] ) && '' !== $v['price'] && (float) $v['price'] > 0 ) { $k['price'] = self::to_minor( $v['price'] ); } if ( isset( $stocks[ (string) $sku_id ] ) ) { $k['stock'] = $stocks[ (string) $sku_id ]; } } } unset( $k ); update_post_meta( $parent, '_okelsync_last_pushed', wp_json_encode( $snap ) ); } $p->save(); } } Okelsync_Store::log( 'tiktok_to_woo', 'product', $id, 'success', sprintf( 'TikTok listing %s edited%s', $id, $parent ? ', WooCommerce updated to match' : '' ) ); return (bool) $parent; } private static function create_from_tiktok( $tp ) { $single = count( $tp['skus'] ) <= 1 && empty( $tp['skus'][0]['sales_attributes'] ); if ( $single ) { $p = new WC_Product_Simple(); } else { $p = new WC_Product_Variable(); } $p->set_name( $tp['title'] ); $p->set_status( 'publish' ); $p->set_description( isset( $tp['description'] ) ? $tp['description'] : '' ); if ( $single ) { $s = $tp['skus'][0]; $p->set_sku( isset( $s['seller_sku'] ) ? $s['seller_sku'] : '' ); $p->set_regular_price( isset( $s['price']['sale_price'] ) ? $s['price']['sale_price'] : '0' ); $p->set_manage_stock( true ); $p->set_stock_quantity( isset( $s['inventory'][0]['quantity'] ) ? $s['inventory'][0]['quantity'] : 0 ); } else { $opts = array(); foreach ( $tp['skus'] as $s ) { foreach ( $s['sales_attributes'] as $a ) { $opts[ $a['name'] ][ $a['value_name'] ] = true; } } $attrs = array(); foreach ( $opts as $name => $vals ) { $at = new WC_Product_Attribute(); $at->set_name( $name ); $at->set_options( array_keys( $vals ) ); $at->set_variation( true ); $at->set_visible( true ); $attrs[] = $at; } $p->set_attributes( $attrs ); } $p->update_meta_data( '_okelsync_tiktok_id', $tp['id'] ); $p->update_meta_data( '_okelsync_source', 'tiktok' ); $pid = $p->save(); if ( ! $single ) { foreach ( $tp['skus'] as $s ) { $v = new WC_Product_Variation(); $v->set_parent_id( $pid ); $va = array(); foreach ( $s['sales_attributes'] as $a ) { $va[ sanitize_title( $a['name'] ) ] = $a['value_name']; } $v->set_attributes( $va ); $v->set_sku( isset( $s['seller_sku'] ) ? $s['seller_sku'] : '' ); $v->set_regular_price( isset( $s['price']['sale_price'] ) ? $s['price']['sale_price'] : '0' ); $v->set_manage_stock( true ); $v->set_stock_quantity( isset( $s['inventory'][0]['quantity'] ) ? $s['inventory'][0]['quantity'] : 0 ); $v->update_meta_data( '_okelsync_sku_id', $s['id'] ); $v->save(); } } else { update_post_meta( $pid, '_okelsync_sku_id', $tp['skus'][0]['id'] ); } self::set_status( $pid, 'synced' ); } public static function reconcile() { $ids = get_posts( array( 'post_type' => 'product', 'numberposts' => -1, 'fields' => 'ids', 'meta_key' => '_okelsync_tiktok_id' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery foreach ( $ids as $id ) { Okelsync_Store::enqueue( 'product.push', array( 'id' => $id, 'only' => array( 'stock' ) ), 'product.push:' . $id, 0 ); } } public static function refresh_token() { $shop = Okelsync_Store::shop(); if ( empty( $shop['refresh_token'] ) ) { return; } $t = Okelsync_Store::client()->token_refresh( Okelsync_Store::decrypt( $shop['refresh_token'] ) ); $shop['access_token'] = Okelsync_Store::encrypt( $t['access_token'] ); $shop['refresh_token'] = Okelsync_Store::encrypt( $t['refresh_token'] ); $shop['expires_at'] = (int) $t['access_token_expire_in']; $shop['status'] = 'connected'; Okelsync_Store::save_shop( $shop ); Okelsync_Store::log( 'system', 'auth', null, 'success', 'Renewed TikTok access' ); } public static function sweep() { if ( 'woo_to_tiktok' === Okelsync_Store::get( 'direction' ) ) { $ids = get_posts( array( 'post_type' => 'product', 'post_status' => array( 'publish', 'private' ), 'numberposts' => -1, 'fields' => 'ids' ) ); foreach ( $ids as $id ) { Okelsync_Store::enqueue( 'product.push', array( 'id' => $id ), 'product.push:' . $id ); } } Okelsync_Store::enqueue( 'reverse.import', array(), 'reverse.import' ); Okelsync_Store::enqueue( 'orders.poll', array(), 'orders.poll' ); Okelsync_Store::log( 'system', 'sweep', null, 'info', 'Sweep started' ); } }