@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,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"transaction_time": "2026-11-19 10:12:40",
|
|
3
|
+
"transaction_status": "settlement",
|
|
4
|
+
"transaction_id": "9f1c7a52-3b8e-4d61-a2f4-000000000007",
|
|
5
|
+
"status_message": "midtrans payment notification",
|
|
6
|
+
"status_code": "200",
|
|
7
|
+
"signature_key": "(hex SHA-512, see signature_vector.txt)",
|
|
8
|
+
"payment_type": "qris",
|
|
9
|
+
"order_id": "INV-2026-00012",
|
|
10
|
+
"merchant_id": "G000000001",
|
|
11
|
+
"gross_amount": "750000.00",
|
|
12
|
+
"fraud_status": "accept",
|
|
13
|
+
"currency": "IDR",
|
|
14
|
+
"transaction_type": "on-us",
|
|
15
|
+
"settlement_time": "2026-11-19 10:13:05",
|
|
16
|
+
"issuer": "gopay",
|
|
17
|
+
"acquirer": "gopay",
|
|
18
|
+
"confirmed": {
|
|
19
|
+
"gateway_ref": "INV-2026-00012",
|
|
20
|
+
"status": "cancel",
|
|
21
|
+
"status_code": "200",
|
|
22
|
+
"paid": false,
|
|
23
|
+
"paid_amount": "750000.00",
|
|
24
|
+
"channel": "qris",
|
|
25
|
+
"transaction_id": "9f1c7a52-3b8e-4d61-a2f4-000000000012",
|
|
26
|
+
"refund_amount": null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"transaction_time": "2026-11-19 10:12:40",
|
|
3
|
+
"transaction_status": "settlement",
|
|
4
|
+
"transaction_id": "9f1c7a52-3b8e-4d61-a2f4-000000000008",
|
|
5
|
+
"status_message": "midtrans payment notification",
|
|
6
|
+
"status_code": "200",
|
|
7
|
+
"signature_key": "(hex SHA-512, see signature_vector.txt)",
|
|
8
|
+
"payment_type": "bank_transfer",
|
|
9
|
+
"order_id": "INV-2026-00008~2",
|
|
10
|
+
"merchant_id": "G000000001",
|
|
11
|
+
"gross_amount": "400000.00",
|
|
12
|
+
"fraud_status": "accept",
|
|
13
|
+
"currency": "IDR",
|
|
14
|
+
"settlement_time": "2026-11-19 11:02:11",
|
|
15
|
+
"va_numbers": [
|
|
16
|
+
{
|
|
17
|
+
"va_number": "812785002530231",
|
|
18
|
+
"bank": "bca"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"payment_amounts": [],
|
|
22
|
+
"confirmed": {
|
|
23
|
+
"gateway_ref": "INV-2026-00008~2",
|
|
24
|
+
"status": "settlement",
|
|
25
|
+
"status_code": "200",
|
|
26
|
+
"paid": true,
|
|
27
|
+
"paid_amount": "400000.00",
|
|
28
|
+
"channel": "bank_transfer",
|
|
29
|
+
"transaction_id": "9f1c7a52-3b8e-4d61-a2f4-000000000008",
|
|
30
|
+
"refund_amount": null
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
4c2b157a97326e6e42210b9583b0325e80af105c63a7c29634ea9208c829ee2c294c4606d7ca7b3063752886108f162fb18dc2bcb83e758b9ef4319a2ce1a33d
|
|
2
|
+
# hex(SHA-512('INV-2026-00001' + '200' + '750000.00' + 'SB-Mid-server-dummy-test-0001')), the vector rangka-os
|
|
3
|
+
# kernel/internal/server/connectors_bodysig_test.go and tests/check_midtrans_mock.py both check
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""A local stand-in for the Midtrans sandbox (Snap, Core API charge, status), for demos and tests without an account.
|
|
3
|
+
|
|
4
|
+
MIDTRANS_MOCK_SERVER_KEY=SB-Mid-server-dummy-demo python3 midtrans/mock/midtrans_mock.py --port 8903 \
|
|
5
|
+
--notify-url http://127.0.0.1:8080/hooks/<org>/midtrans/payment_notified
|
|
6
|
+
|
|
7
|
+
Dummy keys only. The mock signs any notification it is asked for (/simulate/*), without authentication: it is a
|
|
8
|
+
signing oracle for its key. So it listens on 127.0.0.1 only, reads the key from MIDTRANS_MOCK_SERVER_KEY (not argv,
|
|
9
|
+
which `ps` shows), and refuses a key that does not say it is a dummy (a part "dummy" or "test" between - _ or .).
|
|
10
|
+
Never give it a server key from the Midtrans dashboard, sandbox or production.
|
|
11
|
+
|
|
12
|
+
Stdlib only. What it does, in Midtrans's formats (rangka connector midtrans, research in Juragan's
|
|
13
|
+
reports/keputusan-riset/midtrans-connector.md):
|
|
14
|
+
|
|
15
|
+
- POST /snap/v1/transactions Basic auth (server key as the user name, empty password); answers 201 with token and
|
|
16
|
+
redirect_url. An order id that was used before is 400, as at Midtrans (one transaction per order id).
|
|
17
|
+
- GET /snap/v3/redirection/<token> a small page standing in for the Snap payment page (a pay button).
|
|
18
|
+
- POST /v2/charge payment_type qris, bank_transfer (bca, bni, bri, cimb answer va_numbers; permata answers
|
|
19
|
+
permata_va_number) or gopay: status_code 201, transaction_status pending, actions / qr_string / expiry_time.
|
|
20
|
+
- GET /v2/<order_id>/status the transaction as Midtrans reports it (with signature_key); 404 when unknown.
|
|
21
|
+
- POST /simulate/pay/<order_id>[?payment_type=qris][&status=deny|expire|cancel] marks the payment and sends the
|
|
22
|
+
notification to --notify-url, the way the sandbox simulator does; answers with the notification's HTTP status.
|
|
23
|
+
- POST /simulate/refund/<order_id>[?amount=N] a settled payment refunded (all, or N: partial_refund): a notification
|
|
24
|
+
of transaction_status refund or partial_refund, status_code 200. Not money in.
|
|
25
|
+
- POST /simulate/resend/<order_id> the last notification of that order once more (Midtrans retries).
|
|
26
|
+
- POST /simulate/notify body {"order_id", "gross_amount", "transaction_status", "payment_type"}: a notification for
|
|
27
|
+
an order the mock never saw (a payment made outside Snap and the Core API).
|
|
28
|
+
- GET /calls every request it received (for tests).
|
|
29
|
+
|
|
30
|
+
A notification's signature_key is hex(SHA-512(order_id + status_code + gross_amount + server key)): sign() below is
|
|
31
|
+
the reference the kernel's body-field verification is checked against (rangka-os contract 0002, 19 Nov 2026).
|
|
32
|
+
The kernel only sends requests that carry a secret over https to the hosts the connector declares (rangka-os contract
|
|
33
|
+
0017 §5), so a local kernel never calls this mock: the mock is the payer's side, and its API endpoints are what a
|
|
34
|
+
test calls with the requests the connector describes.
|
|
35
|
+
"""
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import argparse
|
|
39
|
+
import base64
|
|
40
|
+
import hashlib
|
|
41
|
+
import hmac
|
|
42
|
+
import html
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
45
|
+
import re
|
|
46
|
+
import sys
|
|
47
|
+
import threading
|
|
48
|
+
import urllib.error
|
|
49
|
+
import urllib.parse
|
|
50
|
+
import urllib.request
|
|
51
|
+
import uuid
|
|
52
|
+
from datetime import datetime, timedelta, timezone
|
|
53
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
54
|
+
|
|
55
|
+
WIB = timezone(timedelta(hours=7))
|
|
56
|
+
ORDER_ID = re.compile(r"^[A-Za-z0-9._~-]{1,50}$") # Midtrans: letters, digits, dash, underscore, tilde and dot
|
|
57
|
+
# status_code per transaction_status, as Midtrans sends it: 200 success, 201 pending, 202 denied, 407 expired
|
|
58
|
+
STATUS_CODE = {"settlement": "200", "capture": "200", "refund": "200", "partial_refund": "200", "cancel": "200",
|
|
59
|
+
"pending": "201", "deny": "202", "expire": "407"}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def sign(order_id: str, status_code: str, gross_amount: str, server_key: str) -> str:
|
|
63
|
+
"""Midtrans signature_key: hex(SHA-512(order_id + status_code + gross_amount + server key)), no separators."""
|
|
64
|
+
return hashlib.sha512((order_id + status_code + gross_amount + server_key).encode()).hexdigest()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def now_wib() -> str:
|
|
68
|
+
return datetime.now(WIB).strftime("%Y-%m-%d %H:%M:%S")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def money(amount: int) -> str:
|
|
72
|
+
return f"{int(amount)}.00"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class State:
|
|
76
|
+
"""The mock's memory. server_key is a dummy key: whoever reaches the mock can have anything signed with it."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, server_key, notify_url, merchant_id="G000000001"):
|
|
79
|
+
self.server_key, self.notify_url, self.merchant_id = server_key, notify_url, merchant_id
|
|
80
|
+
self.orders = {} # order_id -> {transaction_id, gross_amount, payment_type, status, refunded, extra, last}
|
|
81
|
+
self.tokens = {} # snap token -> order_id
|
|
82
|
+
self.calls = []
|
|
83
|
+
self.lock = threading.Lock()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def body_of(state: State, order_id: str, o: dict, status: str, **more) -> dict:
|
|
87
|
+
"""A notification (and status answer) for an order, signed."""
|
|
88
|
+
code = STATUS_CODE.get(status, "200")
|
|
89
|
+
gross = money(o["gross_amount"])
|
|
90
|
+
d = {"transaction_time": o["time"], "transaction_status": status, "transaction_id": o["transaction_id"],
|
|
91
|
+
"status_message": "midtrans payment notification", "status_code": code,
|
|
92
|
+
"signature_key": sign(order_id, code, gross, state.server_key), "payment_type": o["payment_type"],
|
|
93
|
+
"order_id": order_id, "merchant_id": state.merchant_id, "gross_amount": gross, "fraud_status": "accept",
|
|
94
|
+
"currency": "IDR"}
|
|
95
|
+
if status in ("settlement", "refund", "partial_refund"):
|
|
96
|
+
d["settlement_time"] = o.get("settled") or now_wib()
|
|
97
|
+
d.update(o.get("extra") or {})
|
|
98
|
+
d.update(more)
|
|
99
|
+
return d
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def post(url: str, body: dict) -> int:
|
|
103
|
+
"""Send one notification as Midtrans does; returns the HTTP status (0 when unreachable)."""
|
|
104
|
+
req = urllib.request.Request(url, data=json.dumps(body, separators=(",", ":")).encode(), method="POST",
|
|
105
|
+
headers={"Content-Type": "application/json", "User-Agent": "Veritrans (mock)"})
|
|
106
|
+
try:
|
|
107
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
108
|
+
return r.status
|
|
109
|
+
except urllib.error.HTTPError as e:
|
|
110
|
+
return e.code
|
|
111
|
+
except OSError:
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def notify(state: State, order_id: str, o: dict, status: str, **more) -> int:
|
|
116
|
+
body = body_of(state, order_id, o, status, **more)
|
|
117
|
+
o["last"] = body
|
|
118
|
+
return post(state.notify_url, body)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def handler(state: State):
|
|
122
|
+
class H(BaseHTTPRequestHandler):
|
|
123
|
+
def log_message(self, *a):
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
def send(self, code, obj, ctype="application/json"):
|
|
127
|
+
raw = obj.encode() if isinstance(obj, str) else json.dumps(obj).encode()
|
|
128
|
+
self.send_response(code)
|
|
129
|
+
self.send_header("Content-Type", ctype)
|
|
130
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
131
|
+
self.end_headers()
|
|
132
|
+
self.wfile.write(raw)
|
|
133
|
+
|
|
134
|
+
def body(self) -> bytes:
|
|
135
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
136
|
+
return self.rfile.read(n) if n else b""
|
|
137
|
+
|
|
138
|
+
def authorized(self) -> bool:
|
|
139
|
+
want = "Basic " + base64.b64encode((state.server_key + ":").encode()).decode()
|
|
140
|
+
return hmac.compare_digest(self.headers.get("Authorization", ""), want)
|
|
141
|
+
|
|
142
|
+
def refuse(self):
|
|
143
|
+
self.send(401, {"status_code": "401", "status_message": "Transaction cannot be authorized with the current client/server key.",
|
|
144
|
+
"id": str(uuid.uuid4())})
|
|
145
|
+
|
|
146
|
+
def host(self) -> str:
|
|
147
|
+
return self.headers.get("Host", "127.0.0.1")
|
|
148
|
+
|
|
149
|
+
def do_GET(self):
|
|
150
|
+
path = urllib.parse.urlparse(self.path).path
|
|
151
|
+
if path == "/calls":
|
|
152
|
+
with state.lock:
|
|
153
|
+
return self.send(200, state.calls)
|
|
154
|
+
if path.startswith("/snap/v3/redirection/"):
|
|
155
|
+
order_id = state.tokens.get(path.rsplit("/", 1)[-1])
|
|
156
|
+
o = state.orders.get(order_id)
|
|
157
|
+
if not o:
|
|
158
|
+
return self.send(404, {"error_messages": ["token not found"]})
|
|
159
|
+
return self.send(200, f"<!doctype html><meta charset=utf-8><title>Midtrans Snap (mock)</title>"
|
|
160
|
+
f"<h1>Bayar {html.escape(order_id)}</h1><p>Rp {o['gross_amount']:,}</p>"
|
|
161
|
+
f"<form method=post action=/simulate/pay/{urllib.parse.quote(order_id, safe='')}><button>Simulasi bayar QRIS</button></form>",
|
|
162
|
+
"text/html; charset=utf-8")
|
|
163
|
+
m = re.match(r"^/v2/(qris|gopay)/([^/]+)/qr-code$", path)
|
|
164
|
+
if m:
|
|
165
|
+
for o in state.orders.values():
|
|
166
|
+
if o["transaction_id"] == m.group(2):
|
|
167
|
+
return self.send(200, o.get("qr_string", ""), "text/plain; charset=utf-8")
|
|
168
|
+
return self.send(404, {"status_code": "404", "status_message": "Transaction doesn't exist.", "id": str(uuid.uuid4())})
|
|
169
|
+
m = re.match(r"^/v2/([^/]+)/status$", path)
|
|
170
|
+
if m:
|
|
171
|
+
if not self.authorized():
|
|
172
|
+
return self.refuse()
|
|
173
|
+
order_id = urllib.parse.unquote(m.group(1))
|
|
174
|
+
o = state.orders.get(order_id)
|
|
175
|
+
if not o or not o.get("status"):
|
|
176
|
+
return self.send(404, {"status_code": "404", "status_message": "Transaction doesn't exist.", "id": str(uuid.uuid4())})
|
|
177
|
+
more = {"status_message": "Success, transaction is found"}
|
|
178
|
+
if o.get("refunded"):
|
|
179
|
+
more["refund_amount"] = money(o["refunded"])
|
|
180
|
+
return self.send(200, body_of(state, order_id, o, o["status"], **more))
|
|
181
|
+
self.send(404, {"status_code": "404", "status_message": "The requested resource is not found"})
|
|
182
|
+
|
|
183
|
+
def new_order(self, order_id, amount, payment_type, status, **extra):
|
|
184
|
+
"""One transaction per order id; None when the id was used before."""
|
|
185
|
+
with state.lock:
|
|
186
|
+
if order_id in state.orders:
|
|
187
|
+
return None
|
|
188
|
+
o = {"transaction_id": str(uuid.uuid4()), "gross_amount": amount, "payment_type": payment_type,
|
|
189
|
+
"status": status, "refunded": 0, "time": now_wib(), "extra": extra}
|
|
190
|
+
state.orders[order_id] = o
|
|
191
|
+
return o
|
|
192
|
+
|
|
193
|
+
def do_POST(self):
|
|
194
|
+
u = urllib.parse.urlparse(self.path)
|
|
195
|
+
q = urllib.parse.parse_qs(u.query)
|
|
196
|
+
raw = self.body()
|
|
197
|
+
with state.lock:
|
|
198
|
+
state.calls.append({"method": "POST", "path": u.path, "headers": {k: v for k, v in self.headers.items() if k.lower() != "authorization"},
|
|
199
|
+
"body": raw.decode(errors="replace")})
|
|
200
|
+
if u.path in ("/snap/v1/transactions", "/v2/charge"):
|
|
201
|
+
if not self.authorized():
|
|
202
|
+
return self.refuse()
|
|
203
|
+
try:
|
|
204
|
+
req = json.loads(raw)
|
|
205
|
+
td = req["transaction_details"]
|
|
206
|
+
order_id, amount = str(td["order_id"]), int(float(td["gross_amount"]))
|
|
207
|
+
except (ValueError, KeyError, TypeError):
|
|
208
|
+
return self.send(400, {"status_code": "400", "status_message": "One or more parameters in the payload is invalid.",
|
|
209
|
+
"error_messages": ["transaction_details.order_id is required"]})
|
|
210
|
+
if not ORDER_ID.match(order_id) or amount <= 0:
|
|
211
|
+
return self.send(400, {"status_code": "400", "status_message": "One or more parameters in the payload is invalid.",
|
|
212
|
+
"error_messages": ["transaction_details.order_id format is invalid" if amount > 0 else "transaction_details.gross_amount is not equal to the sum of item_details"]})
|
|
213
|
+
if u.path == "/snap/v1/transactions":
|
|
214
|
+
# no payment method yet: the payer picks one on the page (the mock's button pays by QRIS)
|
|
215
|
+
if self.new_order(order_id, amount, "qris", "") is None:
|
|
216
|
+
return self.send(400, {"error_messages": ["transaction_details.order_id sudah digunakan"]})
|
|
217
|
+
token = str(uuid.uuid4())
|
|
218
|
+
state.tokens[token] = order_id
|
|
219
|
+
return self.send(201, {"token": token, "redirect_url": f"http://{self.host()}/snap/v3/redirection/{token}"})
|
|
220
|
+
ptype = req.get("payment_type")
|
|
221
|
+
if ptype not in ("qris", "bank_transfer", "gopay"):
|
|
222
|
+
return self.send(400, {"status_code": "400", "status_message": "One or more parameters in the payload is invalid.",
|
|
223
|
+
"error_messages": ["payment_type is not supported by the mock"]})
|
|
224
|
+
extra = {}
|
|
225
|
+
if ptype == "bank_transfer":
|
|
226
|
+
bank = str((req.get("bank_transfer") or {}).get("bank") or "")
|
|
227
|
+
if bank not in ("bca", "bni", "bri", "cimb", "permata"):
|
|
228
|
+
return self.send(400, {"status_code": "400", "status_message": "One or more parameters in the payload is invalid.",
|
|
229
|
+
"error_messages": ["bank_transfer.bank is invalid"]})
|
|
230
|
+
va = "8127" + f"{int(hashlib.sha256(order_id.encode()).hexdigest(), 16) % 10**11:011d}"
|
|
231
|
+
extra = {"permata_va_number": va} if bank == "permata" else {"va_numbers": [{"bank": bank, "va_number": va}]}
|
|
232
|
+
if ptype == "qris":
|
|
233
|
+
extra = {"acquirer": str((req.get("qris") or {}).get("acquirer") or "gopay")}
|
|
234
|
+
o = self.new_order(order_id, amount, ptype, "pending", **extra)
|
|
235
|
+
if o is None:
|
|
236
|
+
return self.send(406, {"status_code": "406", "status_message": "The request could not be completed due to a conflict with the current state of the target resource, please try again",
|
|
237
|
+
"id": str(uuid.uuid4())})
|
|
238
|
+
tid, base = o["transaction_id"], f"http://{self.host()}"
|
|
239
|
+
exp = req.get("custom_expiry") or {}
|
|
240
|
+
minutes = int(exp.get("expiry_duration") or (1440 if ptype == "bank_transfer" else 15))
|
|
241
|
+
ans = {"status_code": "201", "transaction_id": tid, "order_id": order_id, "merchant_id": state.merchant_id,
|
|
242
|
+
"gross_amount": money(amount), "currency": "IDR", "payment_type": ptype, "transaction_time": o["time"],
|
|
243
|
+
"transaction_status": "pending", "fraud_status": "accept",
|
|
244
|
+
"expiry_time": (datetime.now(WIB) + timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M:%S")}
|
|
245
|
+
ans.update(extra)
|
|
246
|
+
if ptype == "qris":
|
|
247
|
+
o["qr_string"] = f"00020101021226MOCK{tid.replace('-', '')}5303360540{len(str(amount))}{amount}5802ID6304MOCK"
|
|
248
|
+
ans.update({"status_message": "QRIS transaction is created", "qr_string": o["qr_string"],
|
|
249
|
+
"actions": [{"name": "generate-qr-code", "method": "GET", "url": f"{base}/v2/qris/{tid}/qr-code"}]})
|
|
250
|
+
elif ptype == "gopay":
|
|
251
|
+
o["qr_string"] = f"gopay-mock-{tid}"
|
|
252
|
+
ans.update({"status_message": "GO-PAY billing created",
|
|
253
|
+
"actions": [{"name": "generate-qr-code", "method": "GET", "url": f"{base}/v2/gopay/{tid}/qr-code"},
|
|
254
|
+
{"name": "deeplink-redirect", "method": "GET", "url": f"{base}/snap/v3/redirection/gopay-{tid}"},
|
|
255
|
+
{"name": "get-status", "method": "GET", "url": f"{base}/v2/{tid}/status"},
|
|
256
|
+
{"name": "cancel", "method": "POST", "url": f"{base}/v2/{tid}/cancel"}]})
|
|
257
|
+
else:
|
|
258
|
+
ans["status_message"] = "Success, Bank Transfer transaction is created"
|
|
259
|
+
return self.send(200, ans)
|
|
260
|
+
m = re.match(r"^/simulate/(pay|refund|resend)/(.+)$", u.path)
|
|
261
|
+
if m:
|
|
262
|
+
kind, order_id = m.group(1), urllib.parse.unquote(m.group(2))
|
|
263
|
+
o = state.orders.get(order_id)
|
|
264
|
+
if not o:
|
|
265
|
+
return self.send(404, {"error": "no such order"})
|
|
266
|
+
if kind == "pay":
|
|
267
|
+
status = q.get("status", ["settlement"])[0]
|
|
268
|
+
if status not in STATUS_CODE or status in ("refund", "partial_refund"):
|
|
269
|
+
return self.send(400, {"error": "status is settlement, capture, pending, deny, expire or cancel"})
|
|
270
|
+
if o["status"] in ("settlement", "capture", "refund", "partial_refund"):
|
|
271
|
+
return self.send(409, {"error": "already paid: use /simulate/resend for a repeated notification"})
|
|
272
|
+
if "payment_type" in q:
|
|
273
|
+
o["payment_type"] = q["payment_type"][0]
|
|
274
|
+
o["status"] = status
|
|
275
|
+
if status == "settlement":
|
|
276
|
+
o["settled"] = now_wib()
|
|
277
|
+
return self.send(200, {"notified": notify(state, order_id, o, status), "status": status})
|
|
278
|
+
if kind == "refund":
|
|
279
|
+
if o["status"] not in ("settlement", "capture", "partial_refund"):
|
|
280
|
+
return self.send(404, {"error": "not paid"})
|
|
281
|
+
if o["payment_type"] == "bank_transfer":
|
|
282
|
+
return self.send(412, {"status_code": "412", "status_message": "Merchant cannot modify the status of the transaction"})
|
|
283
|
+
left = o["gross_amount"] - o["refunded"]
|
|
284
|
+
amount = int(q.get("amount", [str(left)])[0])
|
|
285
|
+
if amount <= 0 or amount > left:
|
|
286
|
+
return self.send(400, {"error": "amount is more than what is left to refund"})
|
|
287
|
+
o["refunded"] += amount
|
|
288
|
+
o["status"] = "refund" if o["refunded"] == o["gross_amount"] else "partial_refund"
|
|
289
|
+
code = notify(state, order_id, o, o["status"], refund_amount=money(o["refunded"]),
|
|
290
|
+
refunds=[{"refund_chargeback_id": 1, "refund_amount": money(amount), "created_at": now_wib(),
|
|
291
|
+
"reason": "refund from the mock", "refund_key": "refund-" + uuid.uuid4().hex[:10]}])
|
|
292
|
+
return self.send(200, {"notified": code, "status": o["status"], "amount": amount})
|
|
293
|
+
if not o.get("last"):
|
|
294
|
+
return self.send(404, {"error": "nothing was notified for this order"})
|
|
295
|
+
return self.send(200, {"notified": post(state.notify_url, o["last"]), "status": o["last"]["transaction_status"]})
|
|
296
|
+
if u.path == "/simulate/notify":
|
|
297
|
+
try:
|
|
298
|
+
req = json.loads(raw or b"{}")
|
|
299
|
+
order_id, status = str(req["order_id"]), str(req.get("transaction_status", "settlement"))
|
|
300
|
+
o = {"transaction_id": str(req.get("transaction_id") or uuid.uuid4()), "gross_amount": int(req["gross_amount"]),
|
|
301
|
+
"payment_type": str(req.get("payment_type", "qris")), "time": now_wib(), "extra": {}}
|
|
302
|
+
more = {k: req[k] for k in ("fraud_status", "status_code", "refund_amount") if k in req}
|
|
303
|
+
if "status_code" in more: # a chosen status code is signed as sent
|
|
304
|
+
more["signature_key"] = sign(order_id, str(more["status_code"]), money(o["gross_amount"]), state.server_key)
|
|
305
|
+
except (ValueError, KeyError, TypeError):
|
|
306
|
+
return self.send(400, {"error": "order_id and gross_amount are needed"})
|
|
307
|
+
return self.send(200, {"notified": post(state.notify_url, body_of(state, order_id, o, status, **more))})
|
|
308
|
+
self.send(404, {"status_code": "404", "status_message": "The requested resource is not found"})
|
|
309
|
+
return H
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def dummy_key(key: str) -> bool:
|
|
313
|
+
"""True for a key that says it is a dummy: the mock signs whatever it is asked, so a real key must never reach it."""
|
|
314
|
+
return bool(re.search(r"(^|[-_.])(dummy|test)([-_.]|$)", key, re.IGNORECASE))
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def main(argv=None):
|
|
318
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
319
|
+
ap.add_argument("--port", type=int, default=8903)
|
|
320
|
+
ap.add_argument("--notify-url", required=True, help="the kernel hook: http://<kernel>/hooks/<org>/midtrans/payment_notified")
|
|
321
|
+
a = ap.parse_args(argv)
|
|
322
|
+
key = os.environ.get("MIDTRANS_MOCK_SERVER_KEY") or ""
|
|
323
|
+
if not dummy_key(key):
|
|
324
|
+
ap.error("set MIDTRANS_MOCK_SERVER_KEY to a dummy key (a part dummy or test, e.g. SB-Mid-server-dummy-demo); never a real Midtrans key")
|
|
325
|
+
srv = ThreadingHTTPServer(("127.0.0.1", a.port), handler(State(key, a.notify_url)))
|
|
326
|
+
print(f"midtrans mock on http://127.0.0.1:{srv.server_address[1]} (notifications to {a.notify_url})", flush=True)
|
|
327
|
+
try:
|
|
328
|
+
srv.serve_forever()
|
|
329
|
+
except KeyboardInterrupt:
|
|
330
|
+
pass
|
|
331
|
+
return 0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
if __name__ == "__main__":
|
|
335
|
+
sys.exit(main())
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# rangka_whatsapp: WhatsApp from Rangka Cloud
|
|
2
|
+
|
|
3
|
+
A **host connector** (rangka-os contract 0063 §2 and §7): the business sends WhatsApp template messages from its own
|
|
4
|
+
number, which Rangka Cloud provides under Rangka's Meta setup. The owner signs up with nobody and enters no key: every
|
|
5
|
+
auth field is written by the host with a `secrets:host` token, and a kernel serves the connector only when whoever runs
|
|
6
|
+
it names it in `RANGKA_HOST_CONNECTORS`. A self-hosted owner uses [`whatsapp_business`](../whatsapp_business) with
|
|
7
|
+
their own Meta account instead.
|
|
8
|
+
|
|
9
|
+
**Status: spec, tested against a local mock only.** Rangka has no Meta account yet; no message can be sent. `hosts:`
|
|
10
|
+
is a placeholder under the reserved `.example` domain until Rangka Cloud has a public service address, so no bearer can
|
|
11
|
+
leave for a real host before then.
|
|
12
|
+
|
|
13
|
+
## How it works (option B: host relay)
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
flow ─ call rangka_whatsapp.send_template ─► kernel job ─► POST https://{api_host}/svc/whatsapp/v1/messages
|
|
17
|
+
│ Rangka Cloud: kill switch → service state → message
|
|
18
|
+
│ type → template approved → opt-out → daily cap →
|
|
19
|
+
│ number throttle → send once per idempotency_key
|
|
20
|
+
▼
|
|
21
|
+
Meta
|
|
22
|
+
kernel /hooks/<org>/rangka_whatsapp/{message_status|message_received|opted_out} ◄── Rangka Cloud, signed per business
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
What the kernel holds works for this business only and is not Meta's:
|
|
26
|
+
|
|
27
|
+
| Field | What | Secret |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| `api_host` | Rangka Cloud's service host | no |
|
|
30
|
+
| `service_token` | the business's relay bearer | yes |
|
|
31
|
+
| `webhook_key` | the key the host signs this business's events with | yes |
|
|
32
|
+
|
|
33
|
+
## Actions
|
|
34
|
+
|
|
35
|
+
`send_template {to, template, type, components, idempotency_key}` → `{message_id, status}`.
|
|
36
|
+
|
|
37
|
+
- `type` is the business's message type: `receipt`, `reminder`, `order_ready`, `appointment`. Each can be switched off
|
|
38
|
+
on its own.
|
|
39
|
+
- `components` is one body component with text parameters, in the template's order. The host rebuilds what goes to
|
|
40
|
+
Meta from them; a header, a button or media is refused.
|
|
41
|
+
- `idempotency_key` is `<document>:<type>:<step>`, for example `STRK-KPI-2611-00142:receipt:1`. A key is sent once: the
|
|
42
|
+
kernel never queues the same key twice, and the host answers a repeat with the first message (`duplicate: true`)
|
|
43
|
+
without asking Meta.
|
|
44
|
+
|
|
45
|
+
`set_opt_out {phone}` → `{status: recorded | already}`. The business marked the customer "Tidak mau dikirimi WA". It
|
|
46
|
+
only ever adds to the host's list.
|
|
47
|
+
|
|
48
|
+
## Refusals
|
|
49
|
+
|
|
50
|
+
Every refusal is `{"error": {"code": "...", "field": "..."}}`. The connector retries **only** 429 and 5xx; every other
|
|
51
|
+
code is final and arrives at the kernel again as a `message_status` event with `status: failed` and the code in `error`,
|
|
52
|
+
so the document can say why nothing was sent.
|
|
53
|
+
|
|
54
|
+
| HTTP | Code | Meaning | Retried |
|
|
55
|
+
| --- | --- | --- | --- |
|
|
56
|
+
| 400 | `bad_request` (+ `field`) | malformed: `to`, `type`, `template`, `components`, `idempotency_key`, `body` | no |
|
|
57
|
+
| 401 | `unauthenticated` | no bearer, a wrong one, or a revoked one (switch-off) | no |
|
|
58
|
+
| 403 | `service_stopped` | Rangka stopped the service (kill switch), it is switched off or not provisioned yet | no |
|
|
59
|
+
| 403 | `service_paused` | held: a low quality rating, a re-categorised template, or this message type is off | no |
|
|
60
|
+
| 403 | `quota_exceeded` | the business's daily cap is used up | no |
|
|
61
|
+
| 409 | `template_not_approved` | no approved Utility version of this template for the business | no |
|
|
62
|
+
| 409 | `in_progress` | the same key is being sent right now | no |
|
|
63
|
+
| 409 | `delivery_uncertain` | an earlier send of this key got no answer from Meta: it may have arrived, so it is never sent again | no |
|
|
64
|
+
| 422 | `recipient_opted_out` | the customer asked this business to stop | no |
|
|
65
|
+
| 422 | `send_failed` | Meta refused the message for good (for example the number is not on WhatsApp) | no |
|
|
66
|
+
| 429 | `rate_limited` | try again after `Retry-After` | yes |
|
|
67
|
+
| 502 | `upstream_unavailable` | Meta is down or unreachable; nothing was sent | yes |
|
|
68
|
+
| 503 | `unavailable` | the host could not check (its store or the kill switch) | yes |
|
|
69
|
+
|
|
70
|
+
## Triggers
|
|
71
|
+
|
|
72
|
+
Every event is one JSON object, signed over the raw body: `X-Rangka-Signature: sha256=<hex HMAC-SHA256 with webhook_key>`.
|
|
73
|
+
|
|
74
|
+
| Trigger | Fields | When |
|
|
75
|
+
| --- | --- | --- |
|
|
76
|
+
| `message_status` | `message_id`, `idempotency_key`, `type`, `status` (`sent`, `delivered`, `read`, `failed`), `at`, `error` | Meta reported a status, or the host refused a send (`failed`, `message_id` empty, the code in `error`) |
|
|
77
|
+
| `message_received` | `message_id`, `from`, `text`, `profile_name`, `at` | a customer wrote to the number (it only sends in phase 1) |
|
|
78
|
+
| `opted_out` | `phone`, `at`, `source` (`keyword`, `meta`, `staff`) | a customer replied `BERHENTI` or `STOP`, or Meta reported a block |
|
|
79
|
+
|
|
80
|
+
A status never carries the phone: the flow finds its document by `idempotency_key`.
|
|
81
|
+
|
|
82
|
+
## Templates
|
|
83
|
+
|
|
84
|
+
The canonical library is Rangka Cloud's (`internal/whatsapp/templates/library.yaml`); all are category Utility,
|
|
85
|
+
language `id`, and end with *Balas BERHENTI untuk berhenti menerima pesan.*
|
|
86
|
+
|
|
87
|
+
| Name | Type | Body (`{{n}}` = parameter) |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `struk_pembayaran` | `receipt` | Terima kasih, {{1}}. Struk {{2}} dari {{3}}: {{4}}. Total {{5}}, dibayar {{6}}. |
|
|
90
|
+
| `tagihan_terbit` | `reminder` | Halo {{1}}, berikut tagihan {{2}} no. {{3}} sebesar {{4}}, jatuh tempo {{5}}. Pembayaran ke {{6}}. Mohon tulis {{3}} di berita transfer. Terima kasih. |
|
|
91
|
+
| `pengingat_jatuh_tempo` | `reminder` | Halo {{1}}, kami mengingatkan faktur {{2}} sebesar {{3}} sudah lewat {{4}} hari dari jatuh tempo ({{5}}). Pembayaran ke {{6}}. Mohon tulis {{2}} di berita transfer. Abaikan pesan ini kalau sudah membayar. Terima kasih. |
|
|
92
|
+
| `terima_kasih_lunas` | `reminder` | Halo {{1}}, terima kasih. Pembayaran faktur {{2}} sudah kami terima dan faktur ini sudah lunas. |
|
|
93
|
+
| `pesanan_siap` | `order_ready` | Halo {{1}}, pesanan {{2}} di {{3}} sudah siap diambil. Sebutkan nomor pesanan saat mengambil. Terima kasih. |
|
|
94
|
+
| `pengingat_janji` | `appointment` | Halo {{1}}, kami mengingatkan {{2}} di {{3}} pada {{4}}. Kalau perlu mengubah jadwal, hubungi kami sebelum waktunya. Terima kasih. |
|
|
95
|
+
|
|
96
|
+
## Local mock
|
|
97
|
+
|
|
98
|
+
`mock/rangka_whatsapp_mock.py` stands in for the relay (dummy keys only, from `RANGKA_WHATSAPP_MOCK_TOKEN` and
|
|
99
|
+
`RANGKA_WHATSAPP_MOCK_WEBHOOK_KEY`; 127.0.0.1 only; stdlib). It answers both actions with every refusal above, sends a
|
|
100
|
+
key once, and posts signed events to `--hook-url`; `/simulate/*` routes change statuses, send inbound messages
|
|
101
|
+
(`BERHENTI` opts out), stop or pause the service, unapprove a template, queue a rate limit or an outage, and redeliver
|
|
102
|
+
the last event. `python3 tests/check_rangka_whatsapp_mock.py` (needs PyYAML) builds the requests from `connector.rk`
|
|
103
|
+
itself and checks every answer and event against it.
|
|
104
|
+
|
|
105
|
+
Rangka Cloud has its own stand-in with the real relay code behind a fake Meta: `rangka-cloud wa-dev`.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# yaml-language-server: $schema=https://rangka-os.github.io/rangka-os/schema/0.5/connector.json
|
|
2
|
+
# WhatsApp from Rangka Cloud: a host connector (rangka-os contract 0063 §2 and §7). The business gets its own
|
|
3
|
+
# WhatsApp number under Rangka's Meta setup; the owner signs up with nobody and enters no key.
|
|
4
|
+
# - Every auth field is written by the host with a secrets:host token. A kernel serves this connector only when
|
|
5
|
+
# whoever runs it names it in RANGKA_HOST_CONNECTORS; a self-hosted kernel uses `whatsapp_business` instead.
|
|
6
|
+
# - Sends go to the host's relay, never to Meta (option B of the WhatsApp plan): the relay checks the kill switch,
|
|
7
|
+
# the service's state, the message type, the template's approval, the customer's opt-out and the caps before it
|
|
8
|
+
# asks Meta, and sends a key once. What the kernel holds works for this business only and is not Meta's.
|
|
9
|
+
# - Events come from the host, signed with this business's own key: delivery statuses (and refusals, as status
|
|
10
|
+
# failed with the relay's code), inbound messages, and opt-outs.
|
|
11
|
+
# README.md has the refusal codes; fixtures/ are synthetic.
|
|
12
|
+
name: rangka_whatsapp
|
|
13
|
+
label: {id: WhatsApp dari Rangka Cloud, en: WhatsApp from Rangka Cloud}
|
|
14
|
+
summary:
|
|
15
|
+
id: Kirim struk, pengingat tagihan dan kabar pesanan ke pelanggan dari nomor WhatsApp bisnismu yang disediakan Rangka Cloud.
|
|
16
|
+
en: Send receipts, payment reminders and order updates to customers from the WhatsApp number Rangka Cloud provides for your business.
|
|
17
|
+
category: messaging
|
|
18
|
+
icon: send-plane-line
|
|
19
|
+
version: 0.1.0
|
|
20
|
+
vendor: Rangka Cloud
|
|
21
|
+
docs: https://github.com/rangka-os/rangka-connectors/blob/main/rangka_whatsapp/README.md
|
|
22
|
+
# The host's public service address. A placeholder under the reserved .example domain until Rangka Cloud has one:
|
|
23
|
+
# no bearer can leave for a real host before this line names it (rangka-os contract 0017 §5).
|
|
24
|
+
hosts: [cloud.rangka.example]
|
|
25
|
+
experimental:
|
|
26
|
+
provided_by: host
|
|
27
|
+
auth:
|
|
28
|
+
type: token
|
|
29
|
+
fields:
|
|
30
|
+
- name: api_host
|
|
31
|
+
label: {id: Alamat layanan Rangka Cloud, en: Rangka Cloud service host}
|
|
32
|
+
- name: service_token
|
|
33
|
+
label: {id: Token layanan, en: Service token}
|
|
34
|
+
secret: true
|
|
35
|
+
- name: webhook_key
|
|
36
|
+
label: {id: Kunci tanda tangan kabar, en: Event signing key}
|
|
37
|
+
secret: true
|
|
38
|
+
triggers:
|
|
39
|
+
# What happened to a message this business sent: sent, delivered, read or failed. A send the host refused
|
|
40
|
+
# arrives as failed with the refusal's code in `error` and no message_id. `idempotency_key` is the key the flow
|
|
41
|
+
# sent, so the flow finds its document without knowing any id of Meta's.
|
|
42
|
+
- name: message_status
|
|
43
|
+
label: {id: Status pesan terkirim, en: Sent message status}
|
|
44
|
+
via: webhook
|
|
45
|
+
verify:
|
|
46
|
+
signature:
|
|
47
|
+
header: X-Rangka-Signature
|
|
48
|
+
prefix: sha256=
|
|
49
|
+
alg: hmac-sha256
|
|
50
|
+
key: auth.webhook_key
|
|
51
|
+
emit:
|
|
52
|
+
message_id: message_id
|
|
53
|
+
idempotency_key: idempotency_key
|
|
54
|
+
type: type
|
|
55
|
+
status: status
|
|
56
|
+
at: at
|
|
57
|
+
error: error
|
|
58
|
+
# A customer wrote to the number. The number only sends (phase 1), so this is for the business to see.
|
|
59
|
+
- name: message_received
|
|
60
|
+
label: {id: Pesan masuk, en: Incoming message}
|
|
61
|
+
via: webhook
|
|
62
|
+
verify:
|
|
63
|
+
signature:
|
|
64
|
+
header: X-Rangka-Signature
|
|
65
|
+
prefix: sha256=
|
|
66
|
+
alg: hmac-sha256
|
|
67
|
+
key: auth.webhook_key
|
|
68
|
+
emit:
|
|
69
|
+
message_id: message_id
|
|
70
|
+
from: from
|
|
71
|
+
text: text
|
|
72
|
+
profile_name: profile_name
|
|
73
|
+
at: at
|
|
74
|
+
# A customer asked to stop (they replied BERHENTI or STOP, or Meta reported a block). The host already refuses
|
|
75
|
+
# sends to them; the flow marks the customer so staff see it.
|
|
76
|
+
- name: opted_out
|
|
77
|
+
label: {id: Pelanggan minta berhenti, en: Customer opted out}
|
|
78
|
+
via: webhook
|
|
79
|
+
verify:
|
|
80
|
+
signature:
|
|
81
|
+
header: X-Rangka-Signature
|
|
82
|
+
prefix: sha256=
|
|
83
|
+
alg: hmac-sha256
|
|
84
|
+
key: auth.webhook_key
|
|
85
|
+
emit:
|
|
86
|
+
phone: phone
|
|
87
|
+
at: at
|
|
88
|
+
source: source
|
|
89
|
+
actions:
|
|
90
|
+
- name: send_template
|
|
91
|
+
label: {id: Kirim pesan template, en: Send a template message}
|
|
92
|
+
request:
|
|
93
|
+
method: POST
|
|
94
|
+
url: https://{auth.api_host}/svc/whatsapp/v1/messages
|
|
95
|
+
headers: {Authorization: 'Bearer {auth.service_token}'}
|
|
96
|
+
body:
|
|
97
|
+
to: '{input.to}'
|
|
98
|
+
template: '{input.template}'
|
|
99
|
+
type: '{input.type}'
|
|
100
|
+
components: '{input.components}'
|
|
101
|
+
idempotency_key: '{input.idempotency_key}'
|
|
102
|
+
input:
|
|
103
|
+
- {name: to, type: phone, required: true}
|
|
104
|
+
- {name: template, type: data, required: true}
|
|
105
|
+
# receipt | reminder | order_ready | appointment: which of the business's message types this is
|
|
106
|
+
- {name: type, type: data, required: true}
|
|
107
|
+
- {name: components, type: json}
|
|
108
|
+
# <document>:<type>:<step>, e.g. STRK-KPI-2611-00142:receipt:1. The same key is sent once, by the kernel
|
|
109
|
+
# (the job's unique key) and again by the host.
|
|
110
|
+
- {name: idempotency_key, type: data, required: true}
|
|
111
|
+
output:
|
|
112
|
+
message_id: message_id
|
|
113
|
+
status: status
|
|
114
|
+
# Only rate_limited (429) and a host or Meta outage (5xx) are worth another try. Every other refusal is final:
|
|
115
|
+
# recipient_opted_out, template_not_approved, service_stopped, service_paused, quota_exceeded, send_failed.
|
|
116
|
+
retry:
|
|
117
|
+
max: 5
|
|
118
|
+
backoff: exponential
|
|
119
|
+
on: [429, 500, 502, 503, 504]
|
|
120
|
+
idempotency: input.idempotency_key
|
|
121
|
+
# The business marked a customer "Tidak mau dikirimi WA". It only ever adds to the host's list: a customer comes
|
|
122
|
+
# off it by their own action, never by a call from here.
|
|
123
|
+
- name: set_opt_out
|
|
124
|
+
label: {id: Catat pelanggan yang tidak mau dikirimi WA, en: Record a customer who opted out}
|
|
125
|
+
request:
|
|
126
|
+
method: POST
|
|
127
|
+
url: https://{auth.api_host}/svc/whatsapp/v1/opt-outs
|
|
128
|
+
headers: {Authorization: 'Bearer {auth.service_token}'}
|
|
129
|
+
body:
|
|
130
|
+
phone: '{input.phone}'
|
|
131
|
+
input:
|
|
132
|
+
- {name: phone, type: phone, required: true}
|
|
133
|
+
output:
|
|
134
|
+
status: status
|
|
135
|
+
retry:
|
|
136
|
+
max: 5
|
|
137
|
+
backoff: exponential
|
|
138
|
+
on: [429, 500, 502, 503, 504]
|
|
139
|
+
limits:
|
|
140
|
+
rate: The host throttles each number below Meta's limit and caps each business per day
|
|
141
|
+
note: {id: 'Biaya per pesan: belum ditetapkan', en: 'Fee per message: not set yet'}
|