@rangka-os/create 0.5.0-alpha.26 → 0.5.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/base/apps/absen_karyawan/app.rk +37 -0
- package/template/base/apps/absen_karyawan/dashboards/absen_hari_ini.rk +20 -0
- package/template/base/apps/absen_karyawan/dashboards/absen_karyawan_saya.rk +14 -0
- package/template/base/apps/absen_karyawan/dashboards/rekap_absen_karyawan.rk +12 -0
- package/template/base/apps/jasa_proyek/app.rk +1 -1
- package/template/base/apps/kasir/app.rk +5 -1
- package/template/base/apps/kasir/dashboards/kasir_ringkas.rk +4 -0
- package/template/base/apps/kasir/skills/rangka-app-kasir/SKILL.md +20 -0
- package/template/base/connectors/email/connector.rk +144 -0
- package/template/base/connectors/email/fixtures/email_received.json +33 -0
- package/template/base/connectors/email/fixtures/email_received_reply.json +31 -0
- package/template/base/connectors/email/fixtures/expect.json +20 -0
- package/template/base/connectors/email/fixtures/fetch_email.json +66 -0
- package/template/base/connectors/email/fixtures/send_email.json +4 -0
- package/template/base/connectors/midtrans/connector.rk +249 -0
- package/template/base/connectors/midtrans/fixtures/charge_gopay.json +34 -0
- package/template/base/connectors/midtrans/fixtures/charge_qris.json +23 -0
- package/template/base/connectors/midtrans/fixtures/charge_va.json +20 -0
- package/template/base/connectors/midtrans/fixtures/create_snap.json +4 -0
- package/template/base/connectors/midtrans/fixtures/expect.json +88 -0
- package/template/base/connectors/midtrans/fixtures/get_status.json +15 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_challenge.json +24 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_expire.json +24 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_other_amount.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_partial_refund.json +34 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_pending.json +31 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_refund.json +34 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_relabelled.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_va.json +32 -0
- package/template/base/connectors/midtrans/fixtures/signature_vector.txt +3 -0
- package/template/base/connectors/midtrans/mock/midtrans_mock.py +335 -0
- package/template/base/connectors/rangka_whatsapp/README.md +105 -0
- package/template/base/connectors/rangka_whatsapp/connector.rk +141 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/expect.json +9 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_received.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_status.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_status_refused.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/opted_out.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/send_template.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/send_template_duplicate.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/set_opt_out.json +1 -0
- package/template/base/connectors/rangka_whatsapp/mock/rangka_whatsapp_mock.py +354 -0
- package/template/base/connectors/shopee/connector.rk +360 -0
- package/template/base/connectors/shopee/fixtures/expect.json +119 -0
- package/template/base/connectors/shopee/fixtures/get_models.json +52 -0
- package/template/base/connectors/shopee/fixtures/get_order_detail.json +396 -0
- package/template/base/connectors/shopee/fixtures/get_settlement.json +90 -0
- package/template/base/connectors/shopee/fixtures/get_tracking.json +13 -0
- package/template/base/connectors/shopee/fixtures/list_items.json +29 -0
- package/template/base/connectors/shopee/fixtures/list_orders.json +31 -0
- package/template/base/connectors/shopee/fixtures/list_settlements.json +15 -0
- package/template/base/connectors/shopee/fixtures/order_changed.json +101 -0
- package/template/base/connectors/shopee/fixtures/order_changed_cancelled.json +72 -0
- package/template/base/connectors/shopee/fixtures/order_changed_completed.json +101 -0
- package/template/base/connectors/shopee/fixtures/order_changed_in_cancel.json +72 -0
- package/template/base/connectors/shopee/fixtures/order_changed_unpaid.json +71 -0
- package/template/base/connectors/shopee/fixtures/order_settled.json +92 -0
- package/template/base/connectors/shopee/fixtures/push_received.json +12 -0
- package/template/base/connectors/shopee/fixtures/push_received_tracking.json +11 -0
- package/template/base/connectors/shopee/fixtures/update_stock.json +15 -0
- package/template/base/connectors/shopee/mock/shopee_mock.py +894 -0
- package/template/base/connectors/tiktok_shop/connector.rk +300 -0
- package/template/base/connectors/tiktok_shop/fixtures/expect.json +105 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_order_detail.json +136 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_settlement.json +83 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_tracking.json +28 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_orders.json +242 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_products.json +77 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_settlements.json +22 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_shops.json +17 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed.json +129 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_cancelled.json +81 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_completed.json +106 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_on_hold.json +104 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_tokopedia.json +106 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_unpaid.json +79 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_settled.json +73 -0
- package/template/base/connectors/tiktok_shop/fixtures/update_stock.json +6 -0
- package/template/base/connectors/tiktok_shop/fixtures/webhook_received.json +12 -0
- package/template/base/connectors/tiktok_shop/fixtures/webhook_received_cancellation.json +13 -0
- package/template/base/connectors/tiktok_shop/mock/tiktok_shop_mock.py +819 -0
- package/template/base/connectors/whatsapp_business/connector.rk +3 -1
- package/template/base/connectors/whatsapp_business/templates.md +13 -1
- package/template/base/modules/attendance/flows/attendance_missing_digest.rk +30 -0
- package/template/base/modules/attendance/flows/attendance_period_on_cancel.rk +15 -0
- package/template/base/modules/attendance/flows/attendance_period_on_submit.rk +60 -0
- package/template/base/modules/attendance/flows/staff_attendance_cancel_guard.rk +14 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_created.rk +16 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_submitted.rk +37 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_updated.rk +14 -0
- package/template/base/modules/attendance/models/attendance_period.rk +62 -0
- package/template/base/modules/attendance/models/attendance_summary.rk +37 -0
- package/template/base/modules/attendance/models/staff_attendance.rk +281 -0
- package/template/base/modules/attendance/models/staff_attendance_guard.rk +50 -0
- package/template/base/modules/attendance/module.rk +18 -0
- package/template/base/modules/attendance/screens/absen_outlet.rk +22 -0
- package/template/base/modules/catalogue/models/item.rk +69 -0
- package/template/base/modules/catalogue/module.rk +1 -1
- package/template/base/modules/contacts/models/customer.rk +43 -19
- package/template/base/modules/contacts/module.rk +1 -1
- package/template/base/modules/coretax/module.rk +1 -1
- package/template/base/modules/coretax/print/coretax_faktur.rk +3 -2
- package/template/base/modules/coretax/print/coretax_faktur.xml +3 -1
- package/template/base/modules/coretax/print/rekap_ppn.html +9 -7
- package/template/base/modules/courses/flows/charge_invoice_on_submit.rk +15 -0
- package/template/base/modules/courses/module.rk +1 -1
- package/template/base/modules/courses/screens/absen_kelas.rk +1 -0
- package/template/base/modules/invoicing/flows/invoice_due_digest.rk +45 -7
- package/template/base/modules/invoicing/models/sales_invoice_item.rk +4 -1
- package/template/base/modules/invoicing/module.rk +15 -2
- package/template/base/modules/kitchen/screens/dapur.rk +1 -0
- package/template/base/modules/outlets/models/outlet.rk +69 -0
- package/template/base/modules/outlets/module.rk +1 -1
- package/template/base/modules/payments/flows/payment_from_midtrans.rk +85 -0
- package/template/base/modules/payments/flows/payment_refund_from_midtrans.rk +22 -0
- package/template/base/modules/payments/models/payment.rk +2 -1
- package/template/base/modules/payments/module.rk +1 -1
- package/template/base/modules/payroll/flows/payroll_close_on_cancel.rk +8 -5
- package/template/base/modules/payroll/flows/payroll_close_on_submit.rk +8 -5
- package/template/base/modules/payroll/flows/payroll_reminder.rk +106 -0
- package/template/base/modules/payroll/flows/payroll_run_overlap_guard_created.rk +5 -3
- package/template/base/modules/payroll/flows/payroll_run_overlap_guard_updated.rk +5 -3
- package/template/base/modules/payroll/flows/payslip_from_recap.rk +1 -1
- package/template/base/modules/payroll/imports/payroll_profile_list.rk +27 -0
- package/template/base/modules/payroll/models/payroll_close.rk +10 -6
- package/template/base/modules/payroll/models/payroll_run.rk +64 -15
- package/template/base/modules/payroll/models/payslip.rk +48 -9
- package/template/base/modules/payroll/module.rk +22 -5
- package/template/base/modules/payroll/print/payslip.html +4 -1
- package/template/base/modules/pos/models/pos_sale.rk +136 -9
- package/template/base/modules/pos/models/pos_sale_item.rk +33 -1
- package/template/base/modules/pos/module.rk +5 -3
- package/template/base/modules/pos/print/pos_receipt.html +7 -3
- package/template/base/modules/pos/screens/kasir.rk +7 -2
- package/template/base/modules/procurement/flows/reorder_draft_po.rk +57 -0
- package/template/base/modules/procurement/models/vendor_bill.rk +14 -1
- package/template/base/modules/procurement/module.rk +11 -2
- package/template/base/modules/projects/screens/absen.rk +1 -0
- package/template/base/modules/promotions/flows/promo_code_batch_on_submit.rk +26 -0
- package/template/base/modules/promotions/flows/promotion_apply.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_create.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_delete.rk +111 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_update.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_on_sale.rk +95 -0
- package/template/base/modules/promotions/flows/promotion_on_sale_cancel.rk +43 -0
- package/template/base/modules/promotions/models/promo_code.rk +27 -0
- package/template/base/modules/promotions/models/promo_code_batch.rk +36 -0
- package/template/base/modules/promotions/models/promo_guard.rk +44 -0
- package/template/base/modules/promotions/models/promotion.rk +197 -0
- package/template/base/modules/promotions/models/promotion_ledger.rk +35 -0
- package/template/base/modules/promotions/module.rk +20 -0
- package/template/base/modules/rental/screens/alat_keluar.rk +1 -0
- package/template/base/modules/rental/screens/alat_kembali.rk +1 -0
- package/template/base/modules/rental/screens/jadwal_alat.rk +1 -0
- package/template/base/modules/stock/flows/stock_low_alert.rk +65 -0
- package/template/base/modules/stock/flows/stock_negative_alert.rk +14 -5
- package/template/base/modules/stock/models/stock_reorder.rk +34 -0
- package/template/base/modules/stock/module.rk +17 -2
- package/template/base/modules/subscriptions/screens/catat_tagih.rk +1 -0
- package/template/base/modules/subscriptions/screens/rute_tagih.rk +1 -0
- package/template/base/modules/users/flows/summary_daily.rk +83 -0
- package/template/base/modules/users/flows/summary_monthly.rk +83 -0
- package/template/base/modules/users/flows/summary_weekly.rk +83 -0
- package/template/base/modules/users/models/business_summary.rk +67 -0
- package/template/base/modules/users/models/summary_setting.rk +35 -0
- package/template/base/modules/users/models/user.rk +11 -3
- package/template/base/modules/users/module.rk +21 -2
- package/template/base/modules/users/roles/employee.rk +8 -0
- package/template/base/modules/users/roles/outlet_supervisor.rk +7 -0
- package/template/base/modules/whatsapp/flows/whatsapp_customer_opt_out.rk +16 -0
- package/template/base/modules/whatsapp/flows/whatsapp_customer_opt_out_new.rk +17 -0
- package/template/base/modules/whatsapp/flows/whatsapp_message_status.rk +24 -0
- package/template/base/modules/whatsapp/flows/whatsapp_opted_out.rk +26 -0
- package/template/base/modules/whatsapp/models/whatsapp_message.rk +99 -0
- package/template/base/modules/whatsapp/models/whatsapp_opt_out.rk +44 -0
- package/template/base/modules/whatsapp/module.rk +23 -0
- package/template/base/modules/whatsapp_booking/flows/whatsapp_booking_tomorrow.rk +48 -0
- package/template/base/modules/whatsapp_booking/module.rk +13 -0
- package/template/base/modules/whatsapp_order_ready/flows/whatsapp_pickup_on_sale.rk +19 -0
- package/template/base/modules/whatsapp_order_ready/flows/whatsapp_ticket_ready.rk +40 -0
- package/template/base/modules/whatsapp_order_ready/models/whatsapp_pickup.rk +22 -0
- package/template/base/modules/whatsapp_order_ready/module.rk +14 -0
- package/template/base/modules/whatsapp_receipt/flows/whatsapp_receipt_on_sale.rk +43 -0
- package/template/base/modules/whatsapp_receipt/module.rk +13 -0
- package/template/base/modules/whatsapp_reminder/flows/whatsapp_invoice_overdue.rk +64 -0
- package/template/base/modules/whatsapp_reminder/module.rk +15 -0
- package/template/base/modules/workforce/imports/worker_list.rk +4 -1
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""A local stand-in for the TikTok Shop Partner API (which also carries Tokopedia orders), and a poll relay that does
|
|
3
|
+
what the kernel's poll triggers will do once it can sign in the query string (tiktok_shop/connector.rk, Juragan's
|
|
4
|
+
proposals/marketplace-connector-runtime.md). For demos and tests without a TikTok Shop app.
|
|
5
|
+
|
|
6
|
+
TIKTOK_SHOP_MOCK_APP_SECRET=tts-test-dummy-secret python3 tiktok_shop/mock/tiktok_shop_mock.py serve \
|
|
7
|
+
--port 8931 --app-key demo-app-key [--webhook-url http://127.0.0.1:8080/hooks/<org>/tiktok_shop/webhook_received]
|
|
8
|
+
|
|
9
|
+
TIKTOK_SHOP_APP_KEY=demo-app-key TIKTOK_SHOP_APP_SECRET=tts-test-dummy-secret \
|
|
10
|
+
TIKTOK_SHOP_SHOP_CIPHER=ROW_TahuContohDemoCipher0001 TIKTOK_SHOP_ACCESS_TOKEN=... TIKTOK_SHOP_REFRESH_TOKEN=... \
|
|
11
|
+
RANGKA_TOKEN=... python3 tiktok_shop/mock/tiktok_shop_mock.py poll --api http://127.0.0.1:8931 \
|
|
12
|
+
--auth-api http://127.0.0.1:8931 --rangka http://127.0.0.1:8101 --token-file tts-tokens.json [--dry-run] \
|
|
13
|
+
[--since-days 2] [--settled-days 7]
|
|
14
|
+
|
|
15
|
+
Dummy keys only. The mock signs any webhook it is asked for (/simulate/*), without authentication: it is a signing
|
|
16
|
+
oracle for its secret. So it listens on 127.0.0.1 only, reads the secret from TIKTOK_SHOP_MOCK_APP_SECRET (not argv,
|
|
17
|
+
which `ps` shows), and refuses a secret that does not say it is a dummy (a part "dummy" or "test" between - _ or .).
|
|
18
|
+
It never prints a secret or a token.
|
|
19
|
+
|
|
20
|
+
serve answers in TikTok Shop's formats, from the fixtures folder and in-memory state. Every call to the API paths
|
|
21
|
+
checks, in this order, as TikTok documents: app_key (36009004), timestamp within 5 minutes before to 30 seconds after
|
|
22
|
+
the mock's clock (36009004), sign present (36009004) and equal to sign_request() (106001), x-tts-access-token known
|
|
23
|
+
(101000) and not expired (105002), shop_cipher present (106013) and the shop's (101000). Errors use TikTok's envelope
|
|
24
|
+
{"code", "message", "request_id", "data"}.
|
|
25
|
+
- GET /api/v2/token/get?app_key&app_secret&auth_code&grant_type=authorized_code (not signed, as at TikTok)
|
|
26
|
+
- GET /api/v2/token/refresh?app_key&app_secret&refresh_token&grant_type=refresh_token
|
|
27
|
+
A refresh rotates both tokens; the old refresh token stops working (the strictest reading: TikTok does not say
|
|
28
|
+
whether it rotates, so a client must store whatever comes back).
|
|
29
|
+
- GET /authorization/202309/shops list_shops.json (no shop_cipher on this call)
|
|
30
|
+
- POST /order/202309/orders/search?page_size&page_token&sort_field&sort_order body filters update_time_ge/_lt,
|
|
31
|
+
create_time_ge/_lt, order_status; page_token paging, next_page_token "" on the last page
|
|
32
|
+
- GET /order/202507/orders?ids=a,b order detail (max 50)
|
|
33
|
+
- GET /finance/202309/statements?statement_time_ge&_lt&payment_status&page_size&page_token
|
|
34
|
+
- GET /finance/202501/statements/<id>/statement_transactions?page_size&page_token
|
|
35
|
+
- POST /product/202309/products/<product_id>/inventory/update sets the absolute quantity (kept in memory)
|
|
36
|
+
- POST /product/202502/products/search products with their current inventory; seller_skus filter
|
|
37
|
+
- GET /fulfillment/202309/packages/<package_id> tracking number of a package
|
|
38
|
+
- GET /calls every request it received (for tests; tokens masked)
|
|
39
|
+
/simulate/* (no auth, POST): create (body {"commerce_platform", "skus": [seller_sku, ...]}, one line per unit),
|
|
40
|
+
pay/<id>, hold/<id>, ship/<id>, deliver/<id>, complete/<id> (also makes its paid statement and transaction),
|
|
41
|
+
cancel/<id>, expire_token, authorize (an auth code for /api/v2/token/get). Each order change bumps update_time and,
|
|
42
|
+
with --webhook-url, sends webhook type 1 signed as TikTok signs it: Authorization = hex HMAC-SHA256(app_secret,
|
|
43
|
+
app_key + raw body).
|
|
44
|
+
|
|
45
|
+
Orders never carry buyer data here: recipient_address, buyer_nickname, buyer_email, buyer_message and user_id are
|
|
46
|
+
dropped from every fixture before it is served. Fixture times are moved by whole days so that the latest one falls in
|
|
47
|
+
the last 24 hours (--keep-times turns this off), so the two-day poll window always finds them.
|
|
48
|
+
|
|
49
|
+
poll reads the API the way the kernel's triggers order_changed and order_settled will: it signs every request, pages
|
|
50
|
+
over next_page_token (orders, statements and statement transactions), refreshes once on 105002 and sends the call
|
|
51
|
+
again, reads the paid statements and their transactions, builds each event with exactly the keys the triggers emit,
|
|
52
|
+
and posts it to the tenant's flow tiktok_shop_order_staged or tiktok_shop_order_settled (POST
|
|
53
|
+
/api/v1/flows/<name>/run with RANGKA_TOKEN), as moka_mock.py poll does. A rotated token pair is written to
|
|
54
|
+
--token-file (mode 0600) whenever a refresh happened, also on --dry-run: TikTok has already rotated it, and losing it
|
|
55
|
+
means the owner must authorize again. A run that posts refuses to start without --token-file.
|
|
56
|
+
The app secret and tokens go only over https to the hosts of connector.rk (open-api.tiktokglobalshop.com,
|
|
57
|
+
auth.tiktok-shops.com), or plain http to 127.0.0.1 or localhost (the mock), for --api and --auth-api alike;
|
|
58
|
+
RANGKA_TOKEN goes only over https, or plain http to 127.0.0.1 or localhost. Both are checked before any request.
|
|
59
|
+
Each poll reads a fixed window and keeps no cursor: after an outage longer than the window (relay off, kernel down,
|
|
60
|
+
token expired) run poll --since-days N --settled-days N once, N covering the outage. The flows' idempotency keys
|
|
61
|
+
(marketplace/README.md, "Flow keys") make the overlap and the repeated events of every poll harmless.
|
|
62
|
+
|
|
63
|
+
Synthetic data only. Stdlib only.
|
|
64
|
+
"""
|
|
65
|
+
from __future__ import annotations
|
|
66
|
+
|
|
67
|
+
import argparse
|
|
68
|
+
import base64
|
|
69
|
+
import copy
|
|
70
|
+
import glob
|
|
71
|
+
import hashlib
|
|
72
|
+
import hmac
|
|
73
|
+
import json
|
|
74
|
+
import os
|
|
75
|
+
import re
|
|
76
|
+
import secrets
|
|
77
|
+
import sys
|
|
78
|
+
import threading
|
|
79
|
+
import time
|
|
80
|
+
import urllib.error
|
|
81
|
+
import urllib.parse
|
|
82
|
+
import urllib.request
|
|
83
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
84
|
+
|
|
85
|
+
HOSTS = ("open-api.tiktokglobalshop.com", "auth.tiktok-shops.com") # hosts: of tiktok_shop/connector.rk
|
|
86
|
+
LOCAL = ("127.0.0.1", "localhost", "::1")
|
|
87
|
+
API_PREFIXES = ("/authorization/", "/order/", "/finance/", "/product/", "/fulfillment/")
|
|
88
|
+
BUYER_KEYS = ("recipient_address", "buyer_nickname", "buyer_email", "buyer_message", "user_id")
|
|
89
|
+
# the flag table of marketplace/README.md, column tiktok_shop (status of the order API)
|
|
90
|
+
SOLD = ("AWAITING_SHIPMENT", "PARTIALLY_SHIPPING", "AWAITING_COLLECTION", "IN_TRANSIT", "DELIVERED", "COMPLETED")
|
|
91
|
+
SHIPPED = ("IN_TRANSIT", "DELIVERED", "COMPLETED")
|
|
92
|
+
ACCESS_TTL, REFRESH_TTL = 7 * 86400, 365 * 86400
|
|
93
|
+
FLOW_STAGED, FLOW_SETTLED = "tiktok_shop_order_staged", "tiktok_shop_order_settled"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------------------------------------------------- signing
|
|
97
|
+
def sign_request(app_secret: str, path: str, query: dict, body: bytes | str | None = None) -> str:
|
|
98
|
+
"""TikTok Shop request signature: hex HMAC-SHA256(app_secret, app_secret + path + sorted key+value of the query
|
|
99
|
+
without sign and access_token + raw body + app_secret). The body is left out for multipart/form-data (not used)."""
|
|
100
|
+
if isinstance(body, str):
|
|
101
|
+
body = body.encode()
|
|
102
|
+
params = "".join(f"{k}{query[k]}" for k in sorted(query) if k not in ("sign", "access_token"))
|
|
103
|
+
base = app_secret.encode() + path.encode() + params.encode() + (body or b"") + app_secret.encode()
|
|
104
|
+
return hmac.new(app_secret.encode(), base, hashlib.sha256).hexdigest()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def sign_webhook(app_key: str, app_secret: str, body: bytes | str) -> str:
|
|
108
|
+
"""TikTok Shop webhook signature (the Authorization header): hex HMAC-SHA256(app_secret, app_key + raw body)."""
|
|
109
|
+
if isinstance(body, str):
|
|
110
|
+
body = body.encode()
|
|
111
|
+
return hmac.new(app_secret.encode(), app_key.encode() + body, hashlib.sha256).hexdigest()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def dummy_key(secret: str) -> bool:
|
|
115
|
+
"""True for a secret that says it is a dummy: the mock signs whatever it is asked, so a real one must never reach it."""
|
|
116
|
+
return bool(re.search(r"(^|[-_.])(dummy|test)([-_.]|$)", secret or "", re.IGNORECASE))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ------------------------------------------------------------------------------------------------------- the events
|
|
120
|
+
def order_event(o: dict) -> dict:
|
|
121
|
+
"""The emit of trigger order_changed (tiktok_shop/connector.rk), item = o."""
|
|
122
|
+
st = o.get("status")
|
|
123
|
+
pay = o.get("payment") or {}
|
|
124
|
+
return {
|
|
125
|
+
"channel": "tiktok_shop", "storefront": o.get("commerce_platform"), "order_id": o.get("id"), "status": st,
|
|
126
|
+
"sold": st in SOLD, "shipped": st in SHIPPED, "completed": st == "COMPLETED", "cancelled": st == "CANCELLED",
|
|
127
|
+
"created_at": o.get("create_time"), "paid_at": o.get("paid_time"), "updated_at": o.get("update_time"),
|
|
128
|
+
"currency": pay.get("currency"), "buyer_total": pay.get("total_amount"), "lines": o.get("line_items"),
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def settled_event(statement: dict, t: dict) -> dict:
|
|
133
|
+
"""The emit of trigger order_settled, statement = the list_settlements row, item = t."""
|
|
134
|
+
ftb = t.get("fee_tax_breakdown") or {}
|
|
135
|
+
fee, tax = ftb.get("fee") or {}, ftb.get("tax") or {}
|
|
136
|
+
return {
|
|
137
|
+
"channel": "tiktok_shop", "order_id": t.get("order_id"), "currency": statement.get("currency"),
|
|
138
|
+
"settled_at": statement.get("payment_time"), "net": t.get("settlement_amount"), "adjusted_net": None,
|
|
139
|
+
"commission_fee": fee.get("platform_commission_amount"), "service_fee": None,
|
|
140
|
+
"transaction_fee": fee.get("transaction_fee_amount"), "withheld_tax": tax.get("article_22_income_tax_withheld"),
|
|
141
|
+
"income": t,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---------------------------------------------------------------------------------------------------------- the mock
|
|
146
|
+
TIME_KEYS = ("create_time", "update_time", "paid_time", "rts_time", "rts_sla_time", "cancel_time", "collection_time",
|
|
147
|
+
"delivery_time", "statement_time", "payment_time", "order_create_time")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def shift_times(obj, delta: int):
|
|
151
|
+
if isinstance(obj, dict):
|
|
152
|
+
return {k: (v + delta if k in TIME_KEYS and isinstance(v, int) else shift_times(v, delta)) for k, v in obj.items()}
|
|
153
|
+
if isinstance(obj, list):
|
|
154
|
+
return [shift_times(v, delta) for v in obj]
|
|
155
|
+
return obj
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def scrub(o: dict) -> dict:
|
|
159
|
+
return {k: v for k, v in o.items() if k not in BUYER_KEYS}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class State:
|
|
163
|
+
"""The mock's memory. app_secret is a dummy: whoever reaches the mock can have anything signed with it."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, fixtures: str, app_key: str, app_secret: str, access_token: str, refresh_token: str,
|
|
166
|
+
webhook_url: str | None = None, keep_times: bool = False, max_page_size: int = 100, clock=time.time):
|
|
167
|
+
self.app_key, self.app_secret, self.webhook_url, self.clock = app_key, app_secret, webhook_url, clock
|
|
168
|
+
self.max_page_size = max(1, min(100, max_page_size))
|
|
169
|
+
self.lock = threading.Lock()
|
|
170
|
+
self.calls: list[dict] = []
|
|
171
|
+
now = int(clock())
|
|
172
|
+
self.access = {access_token: now + ACCESS_TTL}
|
|
173
|
+
self.refresh = {refresh_token: now + REFRESH_TTL}
|
|
174
|
+
self.auth_codes: dict[str, int] = {}
|
|
175
|
+
self.seq = 0
|
|
176
|
+
|
|
177
|
+
def fx(name):
|
|
178
|
+
return json.load(open(os.path.join(fixtures, name)))
|
|
179
|
+
orders = [fx(os.path.basename(f))["item"] for f in sorted(glob.glob(os.path.join(fixtures, "order_changed*.json")))]
|
|
180
|
+
settled = fx("order_settled.json")
|
|
181
|
+
self.shops = fx("list_shops.json")["data"]["shops"]
|
|
182
|
+
self.shop = self.shops[0]
|
|
183
|
+
products = fx("list_products.json")["data"]["products"]
|
|
184
|
+
pkg = fx("get_tracking.json")["data"]
|
|
185
|
+
if not keep_times:
|
|
186
|
+
latest = max([o.get("update_time") or 0 for o in orders] + [settled["statement"].get("payment_time") or 0])
|
|
187
|
+
delta = ((now - latest) // 86400) * 86400
|
|
188
|
+
orders, settled, products, pkg = (shift_times(x, delta) for x in (orders, settled, products, pkg))
|
|
189
|
+
self.orders = {o["id"]: scrub(o) for o in orders}
|
|
190
|
+
self.statements = {settled["statement"]["id"]: dict(settled["statement"])}
|
|
191
|
+
self.transactions = {settled["statement"]["id"]: [settled["item"]]}
|
|
192
|
+
self.products = {p["id"]: p for p in products}
|
|
193
|
+
self.packages = {pkg["package_id"]: pkg}
|
|
194
|
+
self.webhooks: list[dict] = []
|
|
195
|
+
|
|
196
|
+
# -- helpers
|
|
197
|
+
def new_id(self, prefix: str, width: int = 19) -> str:
|
|
198
|
+
self.seq += 1
|
|
199
|
+
return (prefix + str(int(self.clock())) + f"{self.seq:04d}").ljust(width, "0")[:width]
|
|
200
|
+
|
|
201
|
+
def touch(self, o: dict):
|
|
202
|
+
o["update_time"] = max(int(self.clock()), int(o.get("update_time") or 0) + 1)
|
|
203
|
+
|
|
204
|
+
def set_status(self, o: dict, status: str, line_status: str | None = None, package_status: str | None = None):
|
|
205
|
+
o["status"] = status
|
|
206
|
+
o["is_on_hold_order"] = status == "ON_HOLD"
|
|
207
|
+
for li in o.get("line_items") or []:
|
|
208
|
+
li["display_status"] = line_status or status
|
|
209
|
+
if package_status:
|
|
210
|
+
li["package_status"] = package_status
|
|
211
|
+
self.touch(o)
|
|
212
|
+
|
|
213
|
+
def webhook(self, o: dict) -> int:
|
|
214
|
+
"""Webhook type 1 for an order change, signed as TikTok signs; returns the HTTP status (0 unreachable/none)."""
|
|
215
|
+
status = "CANCEL" if o["status"] == "CANCELLED" else o["status"]
|
|
216
|
+
body = json.dumps({"type": 1, "tts_notification_id": self.new_id("738"), "shop_id": self.shop["id"],
|
|
217
|
+
"timestamp": int(self.clock()), "data": {"order_id": o["id"], "order_status": status,
|
|
218
|
+
"is_on_hold_order": o["status"] == "ON_HOLD",
|
|
219
|
+
"update_time": o["update_time"]}},
|
|
220
|
+
separators=(",", ":")).encode()
|
|
221
|
+
self.webhooks.append(json.loads(body))
|
|
222
|
+
if not self.webhook_url:
|
|
223
|
+
return 0
|
|
224
|
+
req = urllib.request.Request(self.webhook_url, data=body, method="POST", headers={
|
|
225
|
+
"Content-Type": "application/json", "Authorization": sign_webhook(self.app_key, self.app_secret, body)})
|
|
226
|
+
try:
|
|
227
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
228
|
+
return r.status
|
|
229
|
+
except urllib.error.HTTPError as e:
|
|
230
|
+
return e.code
|
|
231
|
+
except OSError:
|
|
232
|
+
return 0
|
|
233
|
+
|
|
234
|
+
def settle(self, o: dict):
|
|
235
|
+
"""A paid statement for today with one ORDER transaction, fees as negative strings as in TikTok's samples."""
|
|
236
|
+
now = int(self.clock())
|
|
237
|
+
revenue = sum(int(li.get("sale_price") or 0) for li in o.get("line_items") or [])
|
|
238
|
+
commission, txfee, pph22 = revenue * 4 // 100, revenue * 2 // 100, revenue * 5 // 1000
|
|
239
|
+
fee_tax = -(commission + txfee + pph22)
|
|
240
|
+
net = revenue + fee_tax
|
|
241
|
+
sid = self.new_id("730")
|
|
242
|
+
tx = {"id": self.new_id("730"), "type": "ORDER", "order_id": o["id"], "order_create_time": o["create_time"],
|
|
243
|
+
"adjustment_id": "", "adjustment_order_id": "", "adjustment_amount": "0",
|
|
244
|
+
"settlement_amount": str(net), "revenue_amount": str(revenue),
|
|
245
|
+
"revenue_breakdown": {"subtotal_before_discount_amount": str(revenue), "seller_discount_amount": "0"},
|
|
246
|
+
"shipping_cost_amount": "0", "shipping_cost_breakdown": {"actual_shipping_fee_amount": "0"},
|
|
247
|
+
"fee_tax_amount": str(fee_tax),
|
|
248
|
+
"fee_tax_breakdown": {"fee": {"platform_commission_amount": str(-commission), "transaction_fee_amount": str(-txfee)},
|
|
249
|
+
"tax": {"article_22_income_tax_withheld": str(-pph22)}},
|
|
250
|
+
"supplementary_component": {"customer_payment_amount": (o.get("payment") or {}).get("total_amount", "0")}}
|
|
251
|
+
self.statements[sid] = {"id": sid, "statement_time": now - now % 86400, "settlement_amount": str(net), "currency": "IDR",
|
|
252
|
+
"revenue_amount": str(revenue), "fee_amount": str(fee_tax), "adjustment_amount": "0",
|
|
253
|
+
"payment_status": "PAID", "payment_id": self.new_id("731"), "payment_time": now}
|
|
254
|
+
self.transactions[sid] = [tx]
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def envelope(code: int, message: str, data=None) -> dict:
|
|
258
|
+
return {"code": code, "message": message, "request_id": secrets.token_hex(16).upper(), "data": data if data is not None else {}}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def page_of(rows: list, q: dict, cap: int):
|
|
262
|
+
"""TikTok-style paging: page_size from the query (capped by --max-page-size), an opaque page_token."""
|
|
263
|
+
try:
|
|
264
|
+
size = max(1, min(cap, int(q.get("page_size") or 20)))
|
|
265
|
+
except ValueError:
|
|
266
|
+
size = 20
|
|
267
|
+
start = 0
|
|
268
|
+
if q.get("page_token"):
|
|
269
|
+
try:
|
|
270
|
+
start = int(base64.urlsafe_b64decode(q["page_token"].encode()).decode().removeprefix("o:"))
|
|
271
|
+
except (ValueError, UnicodeDecodeError):
|
|
272
|
+
return None, None
|
|
273
|
+
chunk = rows[start:start + size]
|
|
274
|
+
nxt = base64.urlsafe_b64encode(f"o:{start + size}".encode()).decode() if start + size < len(rows) else ""
|
|
275
|
+
return chunk, nxt
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def handler(st: State):
|
|
279
|
+
class H(BaseHTTPRequestHandler):
|
|
280
|
+
def log_message(self, *a):
|
|
281
|
+
pass
|
|
282
|
+
|
|
283
|
+
def send(self, code: int, obj):
|
|
284
|
+
raw = json.dumps(obj).encode()
|
|
285
|
+
self.send_response(code)
|
|
286
|
+
self.send_header("Content-Type", "application/json")
|
|
287
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
288
|
+
self.end_headers()
|
|
289
|
+
self.wfile.write(raw)
|
|
290
|
+
|
|
291
|
+
def ok(self, data):
|
|
292
|
+
self.send(200, envelope(0, "Success", data))
|
|
293
|
+
|
|
294
|
+
def err(self, http: int, code: int, message: str):
|
|
295
|
+
self.send(http, envelope(code, message))
|
|
296
|
+
|
|
297
|
+
def record(self, method: str, raw: bytes):
|
|
298
|
+
u = urllib.parse.urlsplit(self.path)
|
|
299
|
+
q = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
|
|
300
|
+
for k in ("app_secret", "refresh_token", "access_token", "auth_code"):
|
|
301
|
+
if k in q:
|
|
302
|
+
q[k] = "***"
|
|
303
|
+
with st.lock:
|
|
304
|
+
st.calls.append({"method": method, "path": u.path, "query": q, "body": raw.decode(errors="replace"),
|
|
305
|
+
"has_access_token": bool(self.headers.get("x-tts-access-token"))})
|
|
306
|
+
|
|
307
|
+
def do_GET(self):
|
|
308
|
+
self.route("GET", b"")
|
|
309
|
+
|
|
310
|
+
def do_POST(self):
|
|
311
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
312
|
+
self.route("POST", self.rfile.read(n) if n else b"")
|
|
313
|
+
|
|
314
|
+
def do_PUT(self):
|
|
315
|
+
self.do_POST()
|
|
316
|
+
|
|
317
|
+
# -- the API gate, in TikTok's order of checks
|
|
318
|
+
def gate(self, path: str, q: dict, raw: bytes, shop_scoped: bool) -> bool:
|
|
319
|
+
if q.get("app_key") != st.app_key:
|
|
320
|
+
return self.err(401, 36009004, "Invalid app_key") or False
|
|
321
|
+
try:
|
|
322
|
+
ts = int(q.get("timestamp", ""))
|
|
323
|
+
except ValueError:
|
|
324
|
+
return self.err(401, 36009004, "Invalid timestamp") or False
|
|
325
|
+
now = int(st.clock())
|
|
326
|
+
if not (now - 300 <= ts <= now + 30):
|
|
327
|
+
return self.err(401, 36009004, "Invalid timestamp: outside 5 minutes before to 30 seconds after the current time") or False
|
|
328
|
+
if not q.get("sign"):
|
|
329
|
+
return self.err(401, 36009004, "Missing signature") or False
|
|
330
|
+
if not hmac.compare_digest(q["sign"], sign_request(st.app_secret, path, q, raw)):
|
|
331
|
+
return self.err(401, 106001, "Invalid sign") or False
|
|
332
|
+
tok = self.headers.get("x-tts-access-token") or ""
|
|
333
|
+
with st.lock:
|
|
334
|
+
exp = st.access.get(tok)
|
|
335
|
+
if exp is None:
|
|
336
|
+
return self.err(401, 101000, "Invalid x-tts-access-token") or False
|
|
337
|
+
if exp <= now:
|
|
338
|
+
return self.err(401, 105002, "Access token is expired, please refresh it") or False
|
|
339
|
+
if shop_scoped:
|
|
340
|
+
if not q.get("shop_cipher"):
|
|
341
|
+
return self.err(400, 106013, "Missing shop_cipher") or False
|
|
342
|
+
if q["shop_cipher"] != st.shop["cipher"]:
|
|
343
|
+
return self.err(401, 101000, "Invalid shop_cipher") or False
|
|
344
|
+
return True
|
|
345
|
+
|
|
346
|
+
def route(self, method: str, raw: bytes):
|
|
347
|
+
u = urllib.parse.urlsplit(self.path)
|
|
348
|
+
path = u.path
|
|
349
|
+
q = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
|
|
350
|
+
self.record(method, raw)
|
|
351
|
+
if path == "/calls" and method == "GET":
|
|
352
|
+
with st.lock:
|
|
353
|
+
return self.send(200, st.calls)
|
|
354
|
+
if path.startswith("/api/v2/token/"):
|
|
355
|
+
return self.token(path, q)
|
|
356
|
+
if path.startswith("/simulate/") and method == "POST":
|
|
357
|
+
return self.simulate(path, raw)
|
|
358
|
+
if not path.startswith(API_PREFIXES):
|
|
359
|
+
return self.err(404, 36009009, "Invalid path")
|
|
360
|
+
if not self.gate(path, q, raw, shop_scoped=path != "/authorization/202309/shops"):
|
|
361
|
+
return
|
|
362
|
+
try:
|
|
363
|
+
body = json.loads(raw) if raw else {}
|
|
364
|
+
except ValueError:
|
|
365
|
+
return self.err(400, 36009022, "Invalid request format")
|
|
366
|
+
return self.api(method, path, q, body)
|
|
367
|
+
|
|
368
|
+
# -- tokens (auth.tiktok-shops.com, not signed)
|
|
369
|
+
def token(self, path: str, q: dict):
|
|
370
|
+
if q.get("app_key") != st.app_key or not hmac.compare_digest(q.get("app_secret", ""), st.app_secret):
|
|
371
|
+
return self.err(401, 36009004, "Invalid app_key or app_secret")
|
|
372
|
+
now = int(st.clock())
|
|
373
|
+
with st.lock:
|
|
374
|
+
if path == "/api/v2/token/get":
|
|
375
|
+
if q.get("grant_type") != "authorized_code":
|
|
376
|
+
return self.err(400, 36009004, "Invalid grant_type")
|
|
377
|
+
if st.auth_codes.pop(q.get("auth_code", ""), 0) < now:
|
|
378
|
+
return self.err(400, 36004004, "Invalid auth code")
|
|
379
|
+
elif path == "/api/v2/token/refresh":
|
|
380
|
+
if q.get("grant_type") != "refresh_token":
|
|
381
|
+
return self.err(400, 36009004, "Invalid grant_type")
|
|
382
|
+
if st.refresh.pop(q.get("refresh_token", ""), 0) < now:
|
|
383
|
+
return self.err(400, 36009004, "Invalid refresh_token")
|
|
384
|
+
else:
|
|
385
|
+
return self.err(404, 36009009, "Invalid path")
|
|
386
|
+
access, refresh = "tts-access-" + secrets.token_hex(12), "tts-refresh-" + secrets.token_hex(12)
|
|
387
|
+
st.access[access] = now + ACCESS_TTL
|
|
388
|
+
st.refresh[refresh] = now + REFRESH_TTL
|
|
389
|
+
return self.ok({"access_token": access, "access_token_expire_in": now + ACCESS_TTL, "refresh_token": refresh,
|
|
390
|
+
"refresh_token_expire_in": now + REFRESH_TTL, "open_id": "mock-open-id", "seller_name": st.shop["name"],
|
|
391
|
+
"seller_base_region": "ID", "user_type": 0, "granted_scopes": ["seller.order.info", "seller.finance.info",
|
|
392
|
+
"seller.product.basic"]})
|
|
393
|
+
|
|
394
|
+
# -- the signed API
|
|
395
|
+
def api(self, method: str, path: str, q: dict, body: dict):
|
|
396
|
+
if method == "GET" and path == "/authorization/202309/shops":
|
|
397
|
+
return self.ok({"shops": st.shops})
|
|
398
|
+
if method == "POST" and path == "/order/202309/orders/search":
|
|
399
|
+
def within(o, f):
|
|
400
|
+
v = o.get(f) or 0
|
|
401
|
+
return (f + "_ge" not in body or v >= int(body[f + "_ge"])) and (f + "_lt" not in body or v < int(body[f + "_lt"]))
|
|
402
|
+
with st.lock:
|
|
403
|
+
rows = [o for o in st.orders.values() if within(o, "update_time") and within(o, "create_time")
|
|
404
|
+
and (not body.get("order_status") or o["status"] == body["order_status"])]
|
|
405
|
+
key = "update_time" if q.get("sort_field") == "update_time" else "create_time"
|
|
406
|
+
rows.sort(key=lambda o: (o.get(key) or 0, o["id"]), reverse=q.get("sort_order", "DESC") != "ASC")
|
|
407
|
+
chunk, nxt = page_of(copy.deepcopy(rows), q, st.max_page_size)
|
|
408
|
+
if chunk is None:
|
|
409
|
+
return self.err(400, 36009004, "Invalid page_token")
|
|
410
|
+
return self.ok({"total_count": len(rows), "next_page_token": nxt, "orders": chunk})
|
|
411
|
+
if method == "GET" and path == "/order/202507/orders":
|
|
412
|
+
ids = [i for i in (q.get("ids") or "").split(",") if i]
|
|
413
|
+
if not ids or len(ids) > 50:
|
|
414
|
+
return self.err(400, 36009004, "ids: 1 to 50 order ids")
|
|
415
|
+
with st.lock:
|
|
416
|
+
if any(i not in st.orders for i in ids):
|
|
417
|
+
return self.err(400, 21008111, "The order or package does not belong to the current seller")
|
|
418
|
+
return self.ok({"orders": [copy.deepcopy(st.orders[i]) for i in ids]})
|
|
419
|
+
if method == "GET" and path == "/finance/202309/statements":
|
|
420
|
+
if q.get("sort_field") != "statement_time":
|
|
421
|
+
return self.err(400, 36009004, "sort_field must be statement_time")
|
|
422
|
+
with st.lock:
|
|
423
|
+
rows = [s for s in st.statements.values()
|
|
424
|
+
if (not q.get("statement_time_ge") or s["statement_time"] >= int(q["statement_time_ge"]))
|
|
425
|
+
and (not q.get("statement_time_lt") or s["statement_time"] < int(q["statement_time_lt"]))
|
|
426
|
+
and (not q.get("payment_status") or s["payment_status"] == q["payment_status"])]
|
|
427
|
+
rows.sort(key=lambda s: (s["statement_time"], s["id"]), reverse=q.get("sort_order", "ASC") == "DESC")
|
|
428
|
+
chunk, nxt = page_of(copy.deepcopy(rows), q, st.max_page_size)
|
|
429
|
+
if chunk is None:
|
|
430
|
+
return self.err(400, 36009004, "Invalid page_token")
|
|
431
|
+
return self.ok({"next_page_token": nxt, "statements": chunk})
|
|
432
|
+
m = re.fullmatch(r"/finance/202501/statements/([^/]+)/statement_transactions", path)
|
|
433
|
+
if method == "GET" and m:
|
|
434
|
+
with st.lock:
|
|
435
|
+
s = st.statements.get(m.group(1))
|
|
436
|
+
if not s:
|
|
437
|
+
return self.err(404, 36009004, "Statement not found")
|
|
438
|
+
txs = copy.deepcopy(st.transactions.get(s["id"], []))
|
|
439
|
+
chunk, nxt = page_of(txs, q, st.max_page_size)
|
|
440
|
+
if chunk is None:
|
|
441
|
+
return self.err(400, 36009004, "Invalid page_token")
|
|
442
|
+
return self.ok({"id": s["id"], "create_time": s["statement_time"], "status": "SETTLED", "currency": s["currency"],
|
|
443
|
+
"payable_amount": s["settlement_amount"], "total_reserve_amount": "0",
|
|
444
|
+
"total_settlement_amount": s["settlement_amount"], "total_count": len(txs),
|
|
445
|
+
"next_page_token": nxt, "transactions": chunk})
|
|
446
|
+
m = re.fullmatch(r"/product/202309/products/([^/]+)/inventory/update", path)
|
|
447
|
+
if method == "POST" and m:
|
|
448
|
+
return self.inventory(m.group(1), body)
|
|
449
|
+
if method == "POST" and path == "/product/202502/products/search":
|
|
450
|
+
want = set(body.get("seller_skus") or [])
|
|
451
|
+
status = body.get("status") or "ALL"
|
|
452
|
+
with st.lock:
|
|
453
|
+
rows = [p for p in st.products.values() if (status == "ALL" or p["status"] == status)
|
|
454
|
+
and (not want or any(s["seller_sku"] in want for s in p["skus"]))]
|
|
455
|
+
chunk, nxt = page_of(copy.deepcopy(rows), q, st.max_page_size)
|
|
456
|
+
if chunk is None:
|
|
457
|
+
return self.err(400, 36009004, "Invalid page_token")
|
|
458
|
+
return self.ok({"total_count": len(rows), "next_page_token": nxt, "products": chunk})
|
|
459
|
+
m = re.fullmatch(r"/fulfillment/202309/packages/([^/]+)", path)
|
|
460
|
+
if method == "GET" and m:
|
|
461
|
+
with st.lock:
|
|
462
|
+
p = st.packages.get(m.group(1))
|
|
463
|
+
if not p:
|
|
464
|
+
return self.err(400, 21008111, "The order or package does not belong to the current seller")
|
|
465
|
+
return self.ok(copy.deepcopy(p))
|
|
466
|
+
return self.err(404, 36009009, "Invalid path")
|
|
467
|
+
|
|
468
|
+
def inventory(self, product_id: str, body: dict):
|
|
469
|
+
with st.lock:
|
|
470
|
+
p = st.products.get(product_id)
|
|
471
|
+
if not p:
|
|
472
|
+
return self.err(400, 12052990, "Batch update inventory error: product not found")
|
|
473
|
+
errors = []
|
|
474
|
+
for s in body.get("skus") or []:
|
|
475
|
+
sku = next((x for x in p["skus"] if x["id"] == str(s.get("id"))), None)
|
|
476
|
+
if not sku:
|
|
477
|
+
errors.append({"code": 12052990, "message": "SKU not found", "detail": {"sku_id": str(s.get("id"))}})
|
|
478
|
+
continue
|
|
479
|
+
for inv in s.get("inventory") or []:
|
|
480
|
+
qty = inv.get("quantity")
|
|
481
|
+
if isinstance(qty, str) and qty.isdigit():
|
|
482
|
+
qty = int(qty) # the kernel templates numbers as text today; TikTok documents an integer
|
|
483
|
+
if not isinstance(qty, int) or qty < 0:
|
|
484
|
+
errors.append({"code": 12052990, "message": "Invalid quantity", "detail": {"sku_id": sku["id"]}})
|
|
485
|
+
continue
|
|
486
|
+
wh = str(inv.get("warehouse_id") or "") or sku["inventory"][0]["warehouse_id"]
|
|
487
|
+
row = next((x for x in sku["inventory"] if x["warehouse_id"] == wh), None)
|
|
488
|
+
if not row:
|
|
489
|
+
errors.append({"code": 12052097, "message": "The warehouse does not exist",
|
|
490
|
+
"detail": {"sku_id": sku["id"], "extra_errors": [{"warehouse_id": wh, "code": 12052097}]}})
|
|
491
|
+
continue
|
|
492
|
+
row["quantity"] = qty # absolute, never a delta
|
|
493
|
+
p["update_time"] = int(st.clock())
|
|
494
|
+
return self.ok({"errors": errors} if errors else {})
|
|
495
|
+
|
|
496
|
+
# -- /simulate/*
|
|
497
|
+
def simulate(self, path: str, raw: bytes):
|
|
498
|
+
parts = path.strip("/").split("/")
|
|
499
|
+
act = parts[1] if len(parts) > 1 else ""
|
|
500
|
+
now = int(st.clock())
|
|
501
|
+
if act == "expire_token":
|
|
502
|
+
with st.lock:
|
|
503
|
+
for k in st.access:
|
|
504
|
+
st.access[k] = now - 1
|
|
505
|
+
return self.send(200, {"expired": len(st.access)})
|
|
506
|
+
if act == "authorize":
|
|
507
|
+
code = "mock-auth-" + secrets.token_hex(8)
|
|
508
|
+
with st.lock:
|
|
509
|
+
st.auth_codes[code] = now + 1800 # 30 minutes, single use
|
|
510
|
+
return self.send(200, {"auth_code": code})
|
|
511
|
+
if act == "create":
|
|
512
|
+
try:
|
|
513
|
+
req = json.loads(raw or b"{}")
|
|
514
|
+
skus = list(req["skus"])
|
|
515
|
+
platform = req.get("commerce_platform", "TIKTOK_SHOP")
|
|
516
|
+
except (ValueError, KeyError, TypeError):
|
|
517
|
+
return self.send(400, {"error": "body {\"commerce_platform\", \"skus\": [seller_sku, ...]}"})
|
|
518
|
+
if platform not in ("TIKTOK_SHOP", "TOKOPEDIA", "TIKTOK_SHOP_APP"):
|
|
519
|
+
return self.send(400, {"error": "commerce_platform: TIKTOK_SHOP, TOKOPEDIA or TIKTOK_SHOP_APP"})
|
|
520
|
+
with st.lock:
|
|
521
|
+
o = self.new_order(platform, skus, now)
|
|
522
|
+
snap = copy.deepcopy(o)
|
|
523
|
+
if o is None:
|
|
524
|
+
return self.send(400, {"error": "unknown seller_sku"})
|
|
525
|
+
return self.send(200, {"order": snap, "notified": st.webhook(snap)})
|
|
526
|
+
if len(parts) != 3:
|
|
527
|
+
return self.send(404, {"error": "not found"})
|
|
528
|
+
with st.lock:
|
|
529
|
+
o = st.orders.get(parts[2])
|
|
530
|
+
if not o:
|
|
531
|
+
return self.send(404, {"error": "order not found"})
|
|
532
|
+
cur = o["status"]
|
|
533
|
+
if act == "pay" and cur in ("UNPAID", "ON_HOLD"):
|
|
534
|
+
o.setdefault("paid_time", now)
|
|
535
|
+
st.set_status(o, "AWAITING_SHIPMENT")
|
|
536
|
+
elif act == "hold" and cur in ("UNPAID", "AWAITING_SHIPMENT"):
|
|
537
|
+
o.setdefault("paid_time", now)
|
|
538
|
+
st.set_status(o, "ON_HOLD", "AWAITING_SHIPMENT")
|
|
539
|
+
elif act == "ship" and cur in ("AWAITING_SHIPMENT", "AWAITING_COLLECTION"):
|
|
540
|
+
tracking = "JX" + o["id"][-10:]
|
|
541
|
+
o["tracking_number"], o["rts_time"] = tracking, now
|
|
542
|
+
for li in o["line_items"]:
|
|
543
|
+
li["tracking_number"] = tracking
|
|
544
|
+
st.set_status(o, "IN_TRANSIT", package_status="FULFILLING")
|
|
545
|
+
pkg = o["packages"][0]["id"]
|
|
546
|
+
st.packages[pkg] = {"package_id": pkg, "orders": [{"id": o["id"]}], "package_status": "FULFILLING",
|
|
547
|
+
"shipping_provider_name": o.get("shipping_provider", "J&T Express"),
|
|
548
|
+
"shipping_type": "TIKTOK", "tracking_number": tracking, "handover_method": "PICKUP",
|
|
549
|
+
"order_line_item_ids": [li["id"] for li in o["line_items"]], "create_time": now,
|
|
550
|
+
"update_time": now}
|
|
551
|
+
elif act == "deliver" and cur == "IN_TRANSIT":
|
|
552
|
+
o["delivery_time"] = now
|
|
553
|
+
st.set_status(o, "DELIVERED")
|
|
554
|
+
elif act == "complete" and cur == "DELIVERED":
|
|
555
|
+
st.set_status(o, "COMPLETED", package_status="COMPLETED")
|
|
556
|
+
st.settle(o)
|
|
557
|
+
elif act == "cancel" and cur not in ("IN_TRANSIT", "DELIVERED", "COMPLETED", "CANCELLED"):
|
|
558
|
+
o["cancel_time"], o["cancellation_initiator"], o["cancel_reason"] = now, "BUYER", "Pembeli membatalkan pesanan"
|
|
559
|
+
st.set_status(o, "CANCELLED", package_status="CANCELLED")
|
|
560
|
+
elif act in ("pay", "hold", "ship", "deliver", "complete", "cancel"):
|
|
561
|
+
return self.send(409, {"error": f"cannot {act} an order in {cur}"})
|
|
562
|
+
else:
|
|
563
|
+
return self.send(404, {"error": "not found"})
|
|
564
|
+
snap = copy.deepcopy(o)
|
|
565
|
+
# the push is sent outside the lock: the receiver may call the mock back
|
|
566
|
+
return self.send(200, {"order": snap, "notified": st.webhook(snap)})
|
|
567
|
+
|
|
568
|
+
def new_order(self, platform: str, skus: list, now: int):
|
|
569
|
+
by_sku = {s["seller_sku"]: (p, s) for p in st.products.values() for s in p["skus"]}
|
|
570
|
+
if not skus or any(x not in by_sku for x in skus):
|
|
571
|
+
return None
|
|
572
|
+
oid = st.new_id("5770", 18)
|
|
573
|
+
pkg = st.new_id("1152")
|
|
574
|
+
lines = []
|
|
575
|
+
for n, x in enumerate(skus):
|
|
576
|
+
p, s = by_sku[x]
|
|
577
|
+
lines.append({"id": f"{oid}{n + 1:02d}", "product_id": p["id"], "product_name": p["title"], "sku_id": s["id"],
|
|
578
|
+
"sku_name": "", "seller_sku": x, "original_price": s["price"]["sale_price"],
|
|
579
|
+
"sale_price": s["price"]["sale_price"], "platform_discount": "0", "seller_discount": "0",
|
|
580
|
+
"currency": "IDR", "display_status": "UNPAID", "package_id": pkg, "package_status": "TO_FULFILL",
|
|
581
|
+
"tracking_number": "", "is_gift": False})
|
|
582
|
+
total = sum(int(li["sale_price"]) for li in lines)
|
|
583
|
+
o = {"id": oid, "status": "UNPAID", "commerce_platform": platform, "order_type": "NORMAL", "create_time": now,
|
|
584
|
+
"update_time": now, "is_on_hold_order": False, "is_cod": False, "shipping_type": "TIKTOK",
|
|
585
|
+
"fulfillment_type": "FULFILLMENT_BY_SELLER", "shipping_provider": "J&T Express", "tracking_number": "",
|
|
586
|
+
"packages": [{"id": pkg}], "line_items": lines,
|
|
587
|
+
"payment": {"currency": "IDR", "original_total_product_price": str(total), "seller_discount": "0",
|
|
588
|
+
"platform_discount": "0", "sub_total": str(total), "shipping_fee": "10000",
|
|
589
|
+
"total_amount": str(total + 10000)}}
|
|
590
|
+
st.orders[oid] = o
|
|
591
|
+
return o
|
|
592
|
+
|
|
593
|
+
return H
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
# ------------------------------------------------------------------------------------------------------------ poll
|
|
597
|
+
class TikTokError(Exception):
|
|
598
|
+
def __init__(self, code: int, message: str):
|
|
599
|
+
super().__init__(f"TikTok Shop code {code}: {message}")
|
|
600
|
+
self.code = code
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def check_api(url: str, flag: str = "--api") -> str:
|
|
604
|
+
"""A base URL the relay may send the app secret and tokens to: https to a host of connector.rk, or plain http to
|
|
605
|
+
this machine (the mock)."""
|
|
606
|
+
u = urllib.parse.urlsplit(url or "")
|
|
607
|
+
if (u.scheme == "https" and u.hostname in HOSTS) or (u.scheme == "http" and u.hostname in LOCAL):
|
|
608
|
+
return url.rstrip("/")
|
|
609
|
+
raise SystemExit(f"{flag} must be https://{HOSTS[0]}, https://{HOSTS[1]} or http://127.0.0.1:<port> (the mock)")
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def check_rangka(rangka: str) -> str:
|
|
613
|
+
"""The kernel URL the relay may send RANGKA_TOKEN to: https, or plain http to this machine."""
|
|
614
|
+
u = urllib.parse.urlsplit(rangka or "")
|
|
615
|
+
if (u.scheme == "https" and u.hostname) or (u.scheme == "http" and u.hostname in LOCAL):
|
|
616
|
+
return rangka.rstrip("/")
|
|
617
|
+
raise SystemExit("--rangka must be https://<kernel> or http://127.0.0.1:<port>: RANGKA_TOKEN never goes over plain http to another machine")
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
class Client:
|
|
621
|
+
"""Signs, sends, refreshes once on 105002 and sends the call again. Never logs a secret or a token."""
|
|
622
|
+
|
|
623
|
+
def __init__(self, api: str, auth_api: str, creds: dict, token_file: str | None = None):
|
|
624
|
+
self.api, self.auth_api = check_api(api, "--api"), check_api(auth_api, "--auth-api")
|
|
625
|
+
self.c = dict(creds)
|
|
626
|
+
self.token_file = token_file
|
|
627
|
+
self.refreshed = False
|
|
628
|
+
self.calls = 0
|
|
629
|
+
|
|
630
|
+
def call(self, method: str, path: str, query: dict | None = None, body: dict | None = None, shop: bool = True) -> dict:
|
|
631
|
+
for attempt in (1, 2):
|
|
632
|
+
q = {"app_key": self.c["app_key"], **(query or {})}
|
|
633
|
+
if shop:
|
|
634
|
+
q["shop_cipher"] = self.c["shop_cipher"]
|
|
635
|
+
q = {k: str(v) for k, v in q.items() if v is not None and v != ""}
|
|
636
|
+
q["timestamp"] = str(int(time.time()))
|
|
637
|
+
raw = json.dumps(body, separators=(",", ":")).encode() if body is not None else b""
|
|
638
|
+
q["sign"] = sign_request(self.c["app_secret"], path, q, raw)
|
|
639
|
+
req = urllib.request.Request(f"{self.api}{path}?{urllib.parse.urlencode(q)}", data=raw if body is not None else None,
|
|
640
|
+
method=method, headers={"x-tts-access-token": self.c["access_token"],
|
|
641
|
+
"Content-Type": "application/json"})
|
|
642
|
+
self.calls += 1
|
|
643
|
+
try:
|
|
644
|
+
with urllib.request.urlopen(req, timeout=30) as r:
|
|
645
|
+
out = json.loads(r.read())
|
|
646
|
+
except urllib.error.HTTPError as e:
|
|
647
|
+
try:
|
|
648
|
+
out = json.loads(e.read())
|
|
649
|
+
except ValueError:
|
|
650
|
+
raise TikTokError(e.code, "HTTP error without a TikTok envelope") from None
|
|
651
|
+
if out.get("code") == 0:
|
|
652
|
+
return out.get("data") or {}
|
|
653
|
+
if out.get("code") == 105002 and attempt == 1 and not self.refreshed:
|
|
654
|
+
self.refresh()
|
|
655
|
+
continue
|
|
656
|
+
raise TikTokError(out.get("code"), out.get("message", ""))
|
|
657
|
+
raise TikTokError(105002, "access token still expired after a refresh")
|
|
658
|
+
|
|
659
|
+
def refresh(self):
|
|
660
|
+
if not self.token_file:
|
|
661
|
+
# TikTok Shop may rotate the pair on a refresh: without a file to keep the new pair it would be lost
|
|
662
|
+
raise SystemExit("the access token expired: rerun with --token-file so the refreshed token pair is kept")
|
|
663
|
+
q = urllib.parse.urlencode({"app_key": self.c["app_key"], "app_secret": self.c["app_secret"],
|
|
664
|
+
"refresh_token": self.c["refresh_token"], "grant_type": "refresh_token"})
|
|
665
|
+
try:
|
|
666
|
+
with urllib.request.urlopen(f"{self.auth_api}/api/v2/token/refresh?{q}", timeout=30) as r:
|
|
667
|
+
out = json.loads(r.read())
|
|
668
|
+
except urllib.error.HTTPError as e:
|
|
669
|
+
out = json.loads(e.read() or b"{}")
|
|
670
|
+
if out.get("code") != 0:
|
|
671
|
+
raise TikTokError(out.get("code"), "token refresh refused: " + str(out.get("message", "")))
|
|
672
|
+
d = out["data"]
|
|
673
|
+
self.c["access_token"], self.c["refresh_token"] = d["access_token"], d["refresh_token"]
|
|
674
|
+
self.refreshed = True
|
|
675
|
+
# the rotated refresh token is stored before the new access token is used
|
|
676
|
+
if self.token_file:
|
|
677
|
+
save_tokens(self.token_file, {"access_token": d["access_token"], "refresh_token": d["refresh_token"],
|
|
678
|
+
"access_token_expire_in": d.get("access_token_expire_in"),
|
|
679
|
+
"refresh_token_expire_in": d.get("refresh_token_expire_in")})
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def save_tokens(path: str, tokens: dict):
|
|
683
|
+
tmp = path + ".tmp"
|
|
684
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
685
|
+
with os.fdopen(fd, "w") as f:
|
|
686
|
+
json.dump(tokens, f)
|
|
687
|
+
os.chmod(tmp, 0o600)
|
|
688
|
+
os.replace(tmp, path)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def pages(client: Client, method: str, path: str, query: dict, body: dict | None, key: str, max_pages: int = 50):
|
|
692
|
+
"""Every row of every page, following next_page_token until it is empty (or seen before, or max_pages)."""
|
|
693
|
+
token, seen = "", set()
|
|
694
|
+
for _ in range(max_pages):
|
|
695
|
+
data = client.call(method, path, dict(query, page_token=token), body)
|
|
696
|
+
yield data, data.get(key) or []
|
|
697
|
+
token = data.get("next_page_token") or ""
|
|
698
|
+
if not token or token in seen:
|
|
699
|
+
return
|
|
700
|
+
seen.add(token)
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def collect(client: Client, since_days: int = 2, settled_days: int = 7, page_size: int = 50, now: int | None = None) -> list:
|
|
704
|
+
"""One poll of both triggers; returns [(flow, event), ...] in the order the kernel would see them."""
|
|
705
|
+
now = int(now or time.time())
|
|
706
|
+
midnight = now - now % 86400 # the spec's (days_between('1970-01-01', today()) - n) * 86400
|
|
707
|
+
out = []
|
|
708
|
+
for _, orders in pages(client, "POST", "/order/202309/orders/search",
|
|
709
|
+
{"page_size": page_size, "sort_field": "update_time", "sort_order": "ASC"},
|
|
710
|
+
{"update_time_ge": midnight - since_days * 86400}, "orders"):
|
|
711
|
+
out += [(FLOW_STAGED, order_event(o)) for o in orders]
|
|
712
|
+
statements = []
|
|
713
|
+
for _, rows in pages(client, "GET", "/finance/202309/statements", {"sort_field": "statement_time", "page_size": 100,
|
|
714
|
+
"statement_time_ge": midnight - settled_days * 86400,
|
|
715
|
+
"payment_status": "PAID"}, None, "statements"):
|
|
716
|
+
statements += [s for s in rows if s["id"] not in {x["id"] for x in statements}]
|
|
717
|
+
for s in statements:
|
|
718
|
+
for _, txs in pages(client, "GET", f"/finance/202501/statements/{s['id']}/statement_transactions",
|
|
719
|
+
{"sort_field": "order_create_time", "page_size": page_size}, None, "transactions"):
|
|
720
|
+
out += [(FLOW_SETTLED, settled_event(s, t)) for t in txs]
|
|
721
|
+
return out
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def deliver(rangka: str, rangka_token: str, events: list) -> dict:
|
|
725
|
+
res = {"events": len(events), "delivered": 0, "refused": []}
|
|
726
|
+
for flow, ev in events:
|
|
727
|
+
req = urllib.request.Request(f"{rangka.rstrip('/')}/api/v1/flows/{flow}/run", data=json.dumps({"event": ev}).encode(),
|
|
728
|
+
method="POST", headers={"Content-Type": "application/json",
|
|
729
|
+
"Authorization": f"Bearer {rangka_token}"})
|
|
730
|
+
try:
|
|
731
|
+
with urllib.request.urlopen(req, timeout=60) as r:
|
|
732
|
+
res["delivered"] += r.status == 200
|
|
733
|
+
except urllib.error.HTTPError as e:
|
|
734
|
+
res["refused"].append({"flow": flow, "order_id": ev.get("order_id"), "status": e.code,
|
|
735
|
+
"body": e.read()[:300].decode(errors="replace")})
|
|
736
|
+
return res
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def creds_from_env(token_file: str | None) -> dict:
|
|
740
|
+
c = {"app_key": os.environ.get("TIKTOK_SHOP_APP_KEY", ""), "app_secret": os.environ.get("TIKTOK_SHOP_APP_SECRET", ""),
|
|
741
|
+
"shop_cipher": os.environ.get("TIKTOK_SHOP_SHOP_CIPHER", ""),
|
|
742
|
+
"access_token": os.environ.get("TIKTOK_SHOP_ACCESS_TOKEN", ""), "refresh_token": os.environ.get("TIKTOK_SHOP_REFRESH_TOKEN", "")}
|
|
743
|
+
if token_file and os.path.exists(token_file):
|
|
744
|
+
saved = json.load(open(token_file))
|
|
745
|
+
c["access_token"] = saved.get("access_token") or c["access_token"]
|
|
746
|
+
c["refresh_token"] = saved.get("refresh_token") or c["refresh_token"]
|
|
747
|
+
return c
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def main(argv=None):
|
|
751
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
752
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
753
|
+
s = sub.add_parser("serve")
|
|
754
|
+
s.add_argument("--port", type=int, default=8931)
|
|
755
|
+
s.add_argument("--app-key", default="demo-app-key")
|
|
756
|
+
s.add_argument("--fixtures", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "fixtures"))
|
|
757
|
+
s.add_argument("--webhook-url", default=None, help="where /simulate/* sends webhook type 1 (the kernel hook)")
|
|
758
|
+
s.add_argument("--max-page-size", type=int, default=100, help="cap page_size so paging is exercised (e.g. 2)")
|
|
759
|
+
s.add_argument("--keep-times", action="store_true", help="serve fixture times unchanged")
|
|
760
|
+
p = sub.add_parser("poll")
|
|
761
|
+
p.add_argument("--api", required=True, help="https://open-api.tiktokglobalshop.com or the mock")
|
|
762
|
+
p.add_argument("--auth-api", default="https://auth.tiktok-shops.com", help="token host (the mock serves both)")
|
|
763
|
+
p.add_argument("--rangka", help="kernel base URL (not needed with --dry-run)")
|
|
764
|
+
p.add_argument("--dry-run", action="store_true", help="print the events as JSON lines, post nothing")
|
|
765
|
+
p.add_argument("--since-days", type=int, default=2)
|
|
766
|
+
p.add_argument("--settled-days", type=int, default=7)
|
|
767
|
+
p.add_argument("--page-size", type=int, default=50)
|
|
768
|
+
p.add_argument("--token-file", help="JSON file (0600) holding the rotated tokens; read first when it exists; "
|
|
769
|
+
"needed unless --dry-run")
|
|
770
|
+
a = ap.parse_args(argv)
|
|
771
|
+
if a.cmd == "serve":
|
|
772
|
+
secret = os.environ.get("TIKTOK_SHOP_MOCK_APP_SECRET", "")
|
|
773
|
+
if not dummy_key(secret):
|
|
774
|
+
ap.error("set TIKTOK_SHOP_MOCK_APP_SECRET to a dummy secret (a part dummy or test, e.g. tts-test-dummy-secret); "
|
|
775
|
+
"never a real app secret")
|
|
776
|
+
st = State(a.fixtures, a.app_key, secret, os.environ.get("TIKTOK_SHOP_MOCK_ACCESS_TOKEN", "demo-tts-access-token"),
|
|
777
|
+
os.environ.get("TIKTOK_SHOP_MOCK_REFRESH_TOKEN", "demo-tts-refresh-token"), a.webhook_url, a.keep_times,
|
|
778
|
+
a.max_page_size)
|
|
779
|
+
srv = ThreadingHTTPServer(("127.0.0.1", a.port), handler(st))
|
|
780
|
+
print(f"tiktok_shop mock: http://127.0.0.1:{srv.server_address[1]}"
|
|
781
|
+
+ (f" (webhooks to {a.webhook_url})" if a.webhook_url else ""), flush=True)
|
|
782
|
+
try:
|
|
783
|
+
srv.serve_forever()
|
|
784
|
+
except KeyboardInterrupt:
|
|
785
|
+
pass
|
|
786
|
+
return 0
|
|
787
|
+
# hosts first: nothing is sent anywhere before every address is allowed
|
|
788
|
+
check_api(a.api, "--api")
|
|
789
|
+
check_api(a.auth_api, "--auth-api")
|
|
790
|
+
if not a.dry_run:
|
|
791
|
+
if a.rangka:
|
|
792
|
+
check_rangka(a.rangka)
|
|
793
|
+
if not a.token_file:
|
|
794
|
+
ap.error("--token-file is needed unless --dry-run: TikTok Shop rotates the token pair on a refresh")
|
|
795
|
+
creds = creds_from_env(a.token_file)
|
|
796
|
+
missing = [k for k in ("app_key", "app_secret", "shop_cipher", "access_token") if not creds[k]]
|
|
797
|
+
if missing:
|
|
798
|
+
sys.exit("set " + ", ".join("TIKTOK_SHOP_" + k.upper() for k in missing))
|
|
799
|
+
rangka_token = os.environ.get("RANGKA_TOKEN", "")
|
|
800
|
+
if not a.dry_run and (not a.rangka or not rangka_token):
|
|
801
|
+
sys.exit("set --rangka and RANGKA_TOKEN (an API token of the tenant's owner or head office), or use --dry-run")
|
|
802
|
+
client = Client(a.api, a.auth_api, creds, a.token_file)
|
|
803
|
+
try:
|
|
804
|
+
events = collect(client, a.since_days, a.settled_days, a.page_size)
|
|
805
|
+
except TikTokError as e:
|
|
806
|
+
sys.exit(str(e))
|
|
807
|
+
if a.dry_run:
|
|
808
|
+
for flow, ev in events:
|
|
809
|
+
print(json.dumps({"flow": flow, "event": ev}, ensure_ascii=False))
|
|
810
|
+
print(json.dumps({"events": len(events), "calls": client.calls, "refreshed": client.refreshed}), file=sys.stderr)
|
|
811
|
+
return 0
|
|
812
|
+
res = deliver(a.rangka, rangka_token, events)
|
|
813
|
+
res.update(calls=client.calls, refreshed=client.refreshed)
|
|
814
|
+
print(json.dumps(res))
|
|
815
|
+
return 1 if res["refused"] else 0
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
if __name__ == "__main__":
|
|
819
|
+
sys.exit(main())
|