🔌 Developer API

Kreward External API

Kreward API 讓您將忠誠度計劃直接嵌入任何網站或後端。適用於 Growth (HK$450/月) 和 Enterprise 方案。

Base URL https://api.kreward.net/v1
LLM-friendly plain text ← paste into ChatGPT / Claude

概覽

Kreward API 讓您將忠誠度計劃直接嵌入任何網站或後端。適用於 Growth (HK$450/月) 和 Enterprise 方案。

您可以做什麼
• 註冊客戶並即時獲得錢包卡二維碼
• 即時增減積分 / 印花
• 查詢客戶當前餘額
• 從您的後端觸發兌換

快速開始(3 步驟)

  1. 獲取 API 金鑰 — 前往 Dashboard → API 生成金鑰對,您將獲得一個公鑰和一個私鑰。
  2. 測試連線 — 使用您的公鑰呼叫 GET /v1/ping,應返回 {"ok":true}。
  3. 註冊您的第一位客戶 — 使用電子郵件呼叫 POST /v1/enroll,回應中包含 Apple Wallet 和 Google Wallet 的 QR 碼。

身份驗證

每次請求都需在 Authorization header 中使用 Bearer 方案提供您的 API 金鑰。

PUBLIC

可在前端 JavaScript 中安全使用。僅限註冊操作。可透過網域白名單限制。

SECRET

僅限伺服器端使用。完整存取權限。請勿在前端代碼中暴露。

HTTP
Authorization: Bearer kw_pub_a3f...   # Public key
Authorization: Bearer kw_sk_9xB...    # Secret key (server only)

錯誤

所有錯誤都以帶有 error 欄位的 JSON 格式和相應的 HTTP 狀態碼回應。

{ "error": "customer_not_found" }
StatusMeaning
200Success
400Bad request — missing or invalid parameter
401Missing or invalid API key
403Forbidden — plan not eligible, or origin blocked
404Customer not found
409Conflict — e.g. insufficient balance
429Rate limit exceeded (100 req/min)
500Internal server error

端點

GET/v1/pingPublic or SecretHealth check

Verify the API is reachable and your key is valid.

cURL
curl https://api.kreward.net/v1/ping \
  -H "Authorization: Bearer kw_pub_YOUR_KEY"
{ "ok": true, "merchant": "My Shop" }
GET/v1/meSecret onlyAccount info

Returns your merchant details, active card templates, and current plan.

cURL
curl https://api.kreward.net/v1/me \
  -H "Authorization: Bearer kw_sk_YOUR_SECRET"
{ "merchant": "My Cafe", "plan": "growth", "templates": [
    { "id": "uuid...", "name": "Stamp Card", "type": "stamps", "goal": 8 }
] }
POST/v1/enrollPublic or SecretEnroll + wallet QR

Enroll a customer. Creates account if needed. Returns QR codes for Apple Wallet and Google Wallet.

FieldTypeDescription
emailstring如省略,返回指向您的註冊頁面的 QR 碼。
namestringCustomer display name (optional)
template_iduuidCard template (defaults to first active)
cURL
curl -X POST https://api.kreward.net/v1/enroll \
  -H "Authorization: Bearer kw_pub_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","name":"Jane"}'
JavaScript
const res = await fetch('https://api.kreward.net/v1/enroll', {
  method: 'POST',
  headers: { 'Authorization': 'Bearer kw_pub_YOUR_KEY', 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: '[email protected]', name: 'Jane' }),
});
const data = await res.json();
// data.qr_ios / data.qr_android -> base64 PNG
PHP
$ch = curl_init('https://api.kreward.net/v1/enroll');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,
  CURLOPT_HTTPHEADER=>['Authorization: Bearer kw_sk_SECRET','Content-Type: application/json'],
  CURLOPT_POSTFIELDS=>json_encode(['email'=>'[email protected]','name'=>'Jane'])]);
$data = json_decode(curl_exec($ch),true);
{ "enrolled": true, "card_id": "uuid...", "balance": 0,
  "qr_ios": "data:image/png;base64,...",
  "qr_android": "data:image/png;base64,...",
  "wallet_url_ios": "https://...", "wallet_url_android": "https://..." }

將 qr_ios / qr_android 顯示為 <img src="..."> — 無需文件存儲。或重定向到 wallet_url_ios / wallet_url_android 一鍵安裝。

GET/v1/customerSecret onlyQuery balance
ParamTypeDescription
email requiredstringCustomer email address
template_iduuidSpecific card template
cURL
curl "https://api.kreward.net/v1/[email protected]" \
  -H "Authorization: Bearer kw_sk_YOUR_SECRET"
{ "card_type": "stamps", "balance": 5, "goal": 8, "name": "Jane" }
POST/v1/transactionSecret onlyAdd / deduct
FieldTypeDescription
email requiredstringCustomer email
delta requiredinteger要增加(正數)或扣除(負數)的數量。例如:+1 印花,-50 積分。
notestringOptional note (order ID, etc.)
template_iduuidTarget a specific template
cURL
curl -X POST https://api.kreward.net/v1/transaction \
  -H "Authorization: Bearer kw_sk_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","delta":1,"note":"Order #1234"}'
Node.js
await fetch('https://api.kreward.net/v1/transaction', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${process.env.KREWARD_SECRET_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: order.email, delta: 1, note: order.id }),
});
PHP
wp_remote_post('https://api.kreward.net/v1/transaction', [
  'headers' => ['Authorization'=>'Bearer '.$_ENV['KREWARD_SECRET'],'Content-Type'=>'application/json'],
  'body' => json_encode(['email'=>$email,'delta'=>1,'note'=>'Order #'.$order_id]),
]);
{ "ok": true, "new_balance": 6, "card_type": "stamps", "goal": 8 }
POST/v1/redeemSecret onlyClaim a reward tier

Tiers are milestones identified by their at threshold (see GET /v1/customer). Claiming a tier marks it redeemed — it does not spend balance, except redeeming the final stamp milestone (at == stamps_total) on a stamps card, which loops the card (balance becomes the held overflow, milestones re-arm).

FieldTypeDescription
email requiredstringCustomer email
at requiredintegerThe tier threshold to claim (positive integer)
cURL
curl -X POST https://api.kreward.net/v1/redeem \
  -H "Authorization: Bearer kw_sk_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","at":8}'
{ "ok": true, "redeemed_at": 8, "looped": true, "redeemed_tiers": [],
  "balance_before": 8, "balance_after": 0, "card_type": "stamps" }

純 HTML / JavaScript

僅使用公鑰,在 10 分鐘內為任何靜態網站添加註冊表單。

HTML
<form id="loyalty-form">
  <input type="email" id="lf-email" placeholder="Your email" required>
  <button type="submit">Get my loyalty card</button>
</form>
<div id="loyalty-result" style="display:none"></div>
<script>
document.getElementById('loyalty-form').addEventListener('submit', async e => {
  e.preventDefault();
  const res = await fetch('https://api.kreward.net/v1/enroll', {
    method:'POST',
    headers:{'Authorization':'Bearer kw_pub_YOUR_KEY','Content-Type':'application/json'},
    body: JSON.stringify({ email: document.getElementById('lf-email').value }),
  });
  const d = await res.json();
  if (d.qr_ios) {
    document.getElementById('loyalty-result').innerHTML =
      '<a href="'+d.wallet_url_ios+'"><img src="'+d.qr_ios+'" width="160"></a> '+
      '<a href="'+d.wallet_url_android+'"><img src="'+d.qr_android+'" width="160"></a>';
    document.getElementById('loyalty-result').style.display='block';
  }
});
</script>
提示:在 API 儀表板中設置允許的來源,使您的公鑰只能從您的網域使用。

WordPress / WooCommerce

Step 1 — 將私鑰存儲在 wp-config.php 中(切勿硬編碼在插件文件中):

wp-config.php
define('KREWARD_SECRET_KEY', 'kw_sk_YOUR_SECRET');

Step 2 — 添加到 functions.php 或自定義插件:

PHP
add_action('woocommerce_order_status_completed', function($order_id) {
  $order = wc_get_order($order_id);
  if (!$order->get_billing_email()) return;
  wp_remote_post('https://api.kreward.net/v1/transaction', [
    'headers' => ['Authorization'=>'Bearer '.KREWARD_SECRET_KEY,'Content-Type'=>'application/json'],
    'body' => json_encode(['email'=>$order->get_billing_email(),'delta'=>1,'note'=>'Order #'.$order_id]),
  ]);
});

add_action('woocommerce_created_customer', function($customer_id) {
  $user = get_user_by('id', $customer_id);
  wp_remote_post('https://api.kreward.net/v1/enroll', [
    'headers' => ['Authorization'=>'Bearer '.KREWARD_SECRET_KEY,'Content-Type'=>'application/json'],
    'body' => json_encode(['email'=>$user->user_email,'name'=>$user->display_name]),
  ]);
});

Shopify 整合

選項 A — Shopify Flow(無需代碼)

  1. 從 App Store 安裝 Shopify Flow(免費)。
  2. 創建由「訂單已付款」觸發的工作流程。
  3. 添加「發送 HTTP 請求」動作到 POST /v1/transaction。
  4. 設置 Authorization header 和包含 order.email 的 email 及 delta: 1 的請求體。

選項 B — 自定義 Webhook(Node.js)

Node.js
app.post('/webhooks/shopify/order-paid', async (req, res) => {
  const order = req.body;
  res.sendStatus(200);
  if (!order.email) return;
  await fetch('https://api.kreward.net/v1/transaction', {
    method:'POST',
    headers:{'Authorization':`Bearer ${process.env.KREWARD_SECRET_KEY}`,'Content-Type':'application/json'},
    body:JSON.stringify({ email:order.email, delta:1, note:`Shopify ${order.name}` }),
  });
});

安全最佳實踐

  • 切勿在前端代碼或公共倉庫中暴露私鑰。使用環境變數。
  • 限制公鑰的允許來源,使其只在您的網域上有效。
  • 如懷疑洩露,立即撤銷並生成新金鑰對。
  • 僅使用 HTTPS — API 強制使用 TLS。
  • 私鑰創建時只顯示一次,不可恢復。
  • 速率限制:每個金鑰每分鐘 100 個請求。
⚠️ 您的私鑰可完整存取您的忠誠度計劃——任何持有它的人都可以為任何客戶增減積分。請像對待資料庫密碼一樣保護它。

準備開始?