import hashlib, hmac, json, os, time, requests
def tungkao(method, path, body=None):
raw = json.dumps(body, separators=(",", ":")) if body else ""
ts = str(int(time.time()))
msg = f"{ts}.{method}.{path}.{hashlib.sha256(raw.encode()).hexdigest()}"
sig = hmac.new(os.environ["TUNGKAO_SIGNING_SECRET"].encode(), msg.encode(), hashlib.sha256).hexdigest()
return requests.request(method, "https://api.tungkao.com" + path, data=raw or None, timeout=30, headers={
"Authorization": f"Bearer {os.environ['TUNGKAO_KEY']}", "Content-Type": "application/json",
"X-Tungkao-Timestamp": ts, "X-Tungkao-Signature": sig}).json()
print(tungkao("GET", "/v1/account"))
모든 응답은 success와 request_id가 있는 JSON입니다. 오류 시 error.code(예: KEY_EXPIRED, INSUFFICIENT_CREDITS)가 포함됩니다 — /errors 참고.
error.user_message is the text to show your own end users (“The system cannot connect to the tungkao.com API. Please contact the administrator.”). It comes with errors an end user cannot fix: HTTP 5xx, SERVICE_PAUSED, INSUFFICIENT_CREDITS and key problems, in the Accept-Language language. Keys with white-label enabled get a message without the tungkao.com name. If the API cannot be reached at all (timeout/network down), show the same text from your own code.
키는 선택한 기간(1–24개월 또는 무기한)에 만료됩니다. 30/7/1일 전에 api_key.expiring webhook으로 알립니다. 포털에서 갱신하면 키 문자열은 그대로입니다.
도메인 인증: live 키마다 웹사이트 하나에 연결됩니다. API key → '도메인 인증' → 도메인 입력, tungkao-verify-….html을 https://내도메인/에 업로드(또는 DNS TXT _tungkao-verify.내도메인 추가) 후 인증. 미인증 키는 DOMAIN_NOT_VERIFIED, 인증된 도메인은 변경 불가이며 다른 계정이 사용할 수 없습니다.
비밀 키 유출? '즉시 교체'를 누르세요 — 무제한, 기존 키는 바로 중지. 키는 자기 서비스에서만 작동합니다 (아니면 WRONG_PRODUCT).
고급(선택): 키에서 '요청 서명'을 켜면 tksign_… 비밀 값을 받고, 모든 요청에 X-Tungkao-Timestamp와 X-Tungkao-Signature = HMAC-SHA256(비밀, ts.METHOD.path.sha256(body))가 필요합니다. 키만 유출돼서는 쓸 수 없습니다.
🧪 Test mode (tk_test_… keys) is free and limited to 2 calls per service per day (non-GET requests only; resets at midnight Bangkok time). Beyond that you get HTTP 429 RATE_LIMITED with a message — use a live key for unlimited calls.
Accept-Language(th, en, lo, my, zh-CN, ko, ja, vi, km, id)를 보내 메시지 언어를 선택하세요.
🧾
은행 영수증 확인
slip_verify
영수증이 진짜인지, 금액이 맞는지, 내 계좌로 입금됐는지, 사용된 적 없는지 확인 — 고객이 영수증을 첨부하는 가게에 적합.
➡️ HTTP 503 and nothing is charged. Ask the customer to retry later, or queue it for manual review
Idempotency-Key header(예: 주문 번호)를 보내면 재시도해도 두 번 과금되지 않습니다.
영수증은 키당 한 번만 VALID입니다 (두 번째는 DUPLICATE).
Several sites receiving into the same account? Put their keys in the same group under “Duplicate-slip protection between keys” on the API Keys page. A slip that passed on one key then returns DUPLICATE on every key in the group (default: this key only).
TrueMoney Wallet 이체 영수증 확인
truewallet_verify
TrueMoney Wallet 이체 영수증이 진짜인지, 금액이 맞는지, 내 전자지갑 번호로 들어왔는지, 이미 사용되지 않았는지 확인합니다.
진행 방법
받는 지갑을 한 번 설정하세요 (PUT /v1/truewallet/profile 또는 포털의 key 카드): 지갑 휴대폰 번호 또는 e-Wallet ID, 태국어/영어 이름, 받는 QR 이미지.
고객에게 QR 이미지(qr_image_url)를 보여 결제하게 한 뒤 영수증 이미지를 올리게 하세요.
영수증 이미지(image_base64)와 예상 금액을 API로 보내세요. 번호와 이름은 저장된 프로필에서 가져옵니다 (또는 요청에 wallet_number / ewallet_id 전송).
aaa.com에서 통과한 영수증은 bbb.com에서 DUPLICATE — 한 사이트에서만 사용 ✅
2개 사이트가 같은 계좌지만 key는 분리 (기본값)
두 key 모두: 이 key만
영수증 하나가 두 사이트에서 모두 통과 ⚠️ 고객이 두 번 충전할 수 있음 — key를 연결하세요
2개 사이트의 받는 계좌가 다름
이 key만 (기본값)
한 사이트의 영수증은 다른 사이트에서 이미 RECEIVER_MISMATCH ✅
2개 사이트가 다른 tungkao 계정(소유자 다름)이지만 받는 계좌는 같음
tungkao 계정 간에는 key를 연결할 수 없음
영수증 하나가 양쪽에서 통과 ⚠️ — 한 tungkao 계정에서 key 두 개를 사서 연결하세요
한 사이트에서 key 2개 사용 (예: 웹사이트 + 앱)
두 key 모두: 같은 그룹
웹사이트든 앱이든 영수증은 한 번만 사용 가능 ✅
DUPLICATE는 QR의 참조 번호로 즉시 감지합니다. API Keys 페이지의 “key 간 중복 영수증 방지” 카드에서 설정하세요 (새 key 기본값: 이 key만).
📚 사용 예시
예시 1
받는 지갑을 한 번 설정
상황: 가게가 TrueMoney 081-234-5678 (Somchai)로 받고 받는 QR이 있음
요청
PUT /v1/truewallet/profile
{
"receive_by": "wallet_number",
"wallet_number": "0812345678",
"name_en": "Somchai Jaidee",
"qr_image_base64": "<base64 of the QR image>"
}
모든 webhook에는 X-Tungkao-Signature: t=…,v1=…가 있습니다. 데이터를 믿기 전에 확인하세요 (URL 설정 시 webhook 비밀 값 표시).
import crypto from "node:crypto";
// use the raw body only — never re-JSON.stringify it
function verify(rawBody, header, secret) {
const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header || "");
if (!m || Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false;
const want = crypto.createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest("hex");
return crypto.timingSafeEqual(Buffer.from(want), Buffer.from(m[2]));
}
상황: A member tries to deposit again with the same slip
응답 예시
{
"success": false,
"status": "DUPLICATE"
}
➡️ DUPLICATE; no new deposit is created
🔐
Sign-in for your website (Google, LINE, Facebook, Apple, TikTok, Discord, Telegram, X, Microsoft, GitHub + 14 more)
Add 'Sign in with …' to your site without registering with each provider. Get name, email, photo, a stable member id, and a member list with sign-in history. One service per provider: google_login, line_login, facebook_login, tiktok_login, discord_login, telegram_login, x_login, microsoft_login, github_login.
진행 방법
제공자 키를 만든 뒤 '로그인 회원'에서 사이트 이름과 돌아갈 주소(https, 정확히 일치)를 설정하세요.
로그인 버튼은 사용자를 client_id(키 ID), redirect_uri, state(매번 새 무작위 값, 세션에 저장)와 함께 /oauth/authorize로 보냅니다.
사용자가 redirect_uri?code=…&state=…로 돌아오면 state 확인 → 서버가 2분 안에 POST /v1/login/token 호출.
data.user(예: 7F3K9QX2-yourshopcom)를 회원 ID로 쓰세요 — 같은 사람은 항상 같은 ID.
One site, 2 keys of the same provider (e.g. website + app, both Google)
Both keys: Combined (default)
The same person gets the same user ID in both ✅
One site, 2 keys of the same provider, counted as separate accounts
Both keys: Separate
The same person gets a different user ID on each key
2 sister sites sharing members
Both keys: Group A
A member has the same user ID on both sites ✅
2 unrelated sites that must not link members
Both keys: Separate
Different user IDs, so the sites can't link their members ✅
A Google key and a LINE key (different providers)
Any setting
Always different user IDs — they are different provider accounts
A key that already has sign-ins needs a different group
Not allowed (locked 🔒)
Create a new key in the wanted group, so member IDs on your site never change
Set it on the “Sign-in user IDs between keys” card on the API Keys page before go-live (new keys default: Combined). Several keys may use the same domain.
전체 예제 (버튼 + 콜백 + code 교환)
// npm i express express-session
import express from "express";
import session from "express-session";
import crypto from "node:crypto";
const KEY = process.env.TUNGKAO_KEY; // API key (tk_live_…) server-side only
const CLIENT_ID = process.env.TUNGKAO_CLIENT_ID; // the key id (shown in the portal), not a secret
const REDIRECT = "https://yourshop.com/auth/callback"; // must match the registered URL exactly
const app = express();
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { secure: true, sameSite: "lax" } }));
// 1) your "Sign in" button links here
app.get("/auth/login", (req, res) => {
req.session.state = crypto.randomBytes(24).toString("base64url");
const u = new URL("https://api.tungkao.com/oauth/authorize");
u.search = new URLSearchParams({ client_id: CLIENT_ID, redirect_uri: REDIRECT, state: req.session.state });
res.redirect(u);
});
// 2) the user comes back with a code
app.get("/auth/callback", async (req, res) => {
if (!req.query.state || req.query.state !== req.session.state) return res.status(400).send("state mismatch");
delete req.session.state;
if (req.query.error) return res.redirect("/login?cancelled=1");
// 3) exchange the code for the user (within 2 minutes)
const r = await fetch("https://api.tungkao.com/v1/login/token", {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ code: req.query.code, redirect_uri: REDIRECT }),
});
const j = await r.json();
if (!j.success) return res.status(400).send(j.error.message);
req.session.user = j.data; // j.data.user = permanent member id, e.g. 7F3K9QX2-yourshopcom
res.redirect("/");
});
app.listen(3000);
<?php
// login.php — your "Sign in" button links to this file
session_start();
$CLIENT_ID = getenv("TUNGKAO_CLIENT_ID");
$REDIRECT = "https://yourshop.com/callback.php";
$_SESSION["state"] = bin2hex(random_bytes(24));
header("Location: https://api.tungkao.com/oauth/authorize?" . http_build_query([
"client_id" => $CLIENT_ID, "redirect_uri" => $REDIRECT, "state" => $_SESSION["state"],
]));
<?php
// callback.php — the user comes back here
session_start();
$REDIRECT = "https://yourshop.com/callback.php";
if (empty($_GET["state"]) || !hash_equals($_SESSION["state"] ?? "", $_GET["state"])) { http_response_code(400); exit("state mismatch"); }
unset($_SESSION["state"]);
if (!empty($_GET["error"])) { header("Location: /login.php?cancelled=1"); exit; }
$ch = curl_init("https://api.tungkao.com/v1/login/token");
curl_setopt_array($ch, [
CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("TUNGKAO_KEY"), "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["code" => $_GET["code"], "redirect_uri" => $REDIRECT]),
]);
$j = json_decode(curl_exec($ch), true);
if (!$j["success"]) { http_response_code(400); exit($j["error"]["message"]); }
$_SESSION["user"] = $j["data"]; // $j["data"]["user"] = permanent member id
header("Location: /");
# pip install flask requests
import os, secrets, requests
from urllib.parse import urlencode
from flask import Flask, session, request, redirect, abort
app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]
KEY = os.environ["TUNGKAO_KEY"]
CLIENT_ID = os.environ["TUNGKAO_CLIENT_ID"]
REDIRECT = "https://yourshop.com/auth/callback"
@app.get("/auth/login")
def login():
session["state"] = secrets.token_urlsafe(24)
return redirect("https://api.tungkao.com/oauth/authorize?" + urlencode({"client_id": CLIENT_ID, "redirect_uri": REDIRECT, "state": session["state"]}))
@app.get("/auth/callback")
def callback():
if not request.args.get("state") or not secrets.compare_digest(request.args["state"], session.pop("state", "")):
abort(400)
if request.args.get("error"):
return redirect("/login?cancelled=1")
r = requests.post("https://api.tungkao.com/v1/login/token", headers={"Authorization": f"Bearer {KEY}"},
json={"code": request.args["code"], "redirect_uri": REDIRECT}, timeout=30).json()
if not r["success"]:
abort(400, r["error"]["message"])
session["user"] = r["data"] # r["data"]["user"] = permanent member id
return redirect("/")
제공자
서비스
제공 정보
Google
google_login
이름, 인증된 이메일, 사진
LINE
line_login
이름, 사진, 이메일(동의 시)
Facebook
facebook_login
이름, 사진, 이메일
TikTok
tiktok_login
닉네임, 아바타 (이메일 없음)
Discord
discord_login
이름, 아바타, 이메일
Telegram
telegram_login
name, username, photo
X (Twitter)
x_login
name, username, photo
Microsoft
microsoft_login
name, email (Hotmail/Outlook)
GitHub
github_login
name, email, avatar
Apple
apple_login
permanent member ID (no name or email in this mode)
Steam
steam_login
name, avatar and SteamID (no email)
Twitch
twitch_login
name, email, avatar
LinkedIn
linkedin_login
name, email, photo
Kakao
kakao_login
name, photo (email once Kakao approves it)
NAVER
naver_login
name, email, photo
Zalo
zalo_login
name, photo (no email)
Spotify
spotify_login
name, email, photo
Reddit
reddit_login
username, avatar (no email)
GitLab
gitlab_login
name, email, avatar
Roblox
roblox_login
name, avatar (no email)
Epic Games
epicgames_login
display name (no email)
Yahoo
yahoo_login
name, email, photo
Slack
slack_login
name, email, photo
Amazon
amazon_login
name, email
📚 사용 예시
예시 1
A “Sign in with Google” button on your site
상황: A visitor taps Sign in with Google on your site
요청
GET /oauth/authorize?client_id=<CLIENT_ID>&redirect_uri=https://yourshop.com/auth/callback&state=xyz
➡️ The user signs in with Google and returns to redirect_uri with a code and the same state
예시 2
Exchange the code for the user (server side)
상황: Your server receives the code on the callback page (exchange within 2 minutes)
요청
POST /v1/login/token
{
"code": "<code from the callback>",
"redirect_uri": "https://yourshop.com/auth/callback"
}
➡️ Same user every time → look up the member and sign them in
예시 4
One site, two Google keys (website + app)
상황: Separate keys for website and app, same members
➡️ Keep both keys “Combined” (default) before go-live → same user for the same person. Choose “Separate” to keep them apart
예시 5
List members who signed in
상황: You want to browse or search members of this key
요청
GET /v1/login/users?q=somchai&limit=50
➡️ Returns members with last sign-in time and count
예시 6
The user cancels during sign-in
상황: The user cancels on the Google screen
➡️ Returns to redirect_uri with error instead of code; show a retry button
User IDs between keys: new keys default to “Combined (whole account)”, so the same person signing in through keys of the same provider in one account gets the same ID. Change it to group A–E or “Separate” on the API Keys page before the first sign-in; after that the group is locked so member IDs never change.
로그인 성공 시마다, 그리고 신규 회원당 한 번 크레딧이 차감됩니다 — 현재 가격은 서비스 카드 참고.
test 모드 키는 http://localhost 리디렉션을 허용하며 무료입니다.
API 키를 링크나 페이지에 넣지 마세요 — /oauth/authorize에는 공개 가능한 client_id(키 ID)만 필요합니다.
✈️
Telegram 알림
telegram_notify
TUNGKAO 봇으로 사용자에게 Telegram 메시지를 보냅니다 — 봇을 직접 만들 필요 없음. 예: 입금 확인, 주문 상태, OTP.
진행 방법
ref is your own name for a recipient (use your member id, e.g. member-1001): A-Z a-z 0-9 _ . : @ - up to 128 chars. Every call refers to the recipient by this ref.
Add a recipient: your server calls POST /v1/telegram/link {ref} → gets data.url (a t.me/…?start=… link) → show it as a “Connect Telegram” button on the member's profile page (valid 30 minutes, single use; request again any time).
The member opens the link → presses Start in Telegram → the bot confirms (Telegram does not let a bot message someone who never pressed Start, so this step cannot be skipped).
Check the connection: GET /v1/telegram/recipients (status = active) — use it to switch your button to “Connected ✓”.
Send: POST /v1/telegram/send with one ref or up to 100 refs; bold text (parse_mode: HTML) and a link button are supported. Per-recipient results are in data.results: sent / not_linked / failed.
Remove a recipient: DELETE /v1/telegram/recipients/{ref}. Members can also send /stop to the bot. If a member blocks the bot, that recipient is paused until they connect again.
Try it without code: TUNGKAO API key page → this key's card → “Set up notifications” has a create-link button (with QR) and a send-test button.
POST /v1/telegram/send
{
"refs": [
"member-1001",
"member-1002",
"member-1003"
],
"text": "New promotion today"
}
➡️ Sent to each member; check results with GET /v1/telegram/messages
예시 5
A member stops notifications
상황: The member asks to disconnect
요청
DELETE /v1/telegram/recipients/member-1001
➡️ The link is removed; no more messages are sent
전달된 메시지만 과금 — 실패(예: 사용자가 봇 차단)는 환불되고 해당 수신자는 일시 중지됩니다.
🔔
Discord 알림
discord_notify
내 또는 고객의 Discord 채널에 메시지를 보냅니다 — 예: 팀에 새 주문 알림.
진행 방법
Create a channel webhook in Discord (needs Manage Webhooks): desktop right-click the channel → Edit Channel → Integrations → Webhooks → New Webhook → name it → Copy Webhook URL (mobile: long-press the channel → Edit Channel).
ref is your own name for the channel, e.g. orders-room (A-Z a-z 0-9 _ . : @ - up to 128 chars). One key can hold many channels, each with its own ref.
Add a channel: POST /v1/discord/webhooks {ref, url} — url must start with https://discord.com/api/webhooks/…; it is stored encrypted and never returned. Posting the same ref again replaces that channel's link.
Send: POST /v1/discord/send {ref, text} (up to 2000 chars; @everyone / @here are disabled automatically). Results are in data.results: sent / not_linked / failed.
List channels: GET /v1/discord/recipients. Remove: DELETE /v1/discord/recipients/{ref}. If the webhook is deleted in Discord, the channel is paused and the undelivered message is refunded.
Try it without code: TUNGKAO API key page → this key's card → “Set up notifications”: paste the webhook link, add the channel and send a test.
Do not confuse this with the key's “Webhook URL” setting: that is your server address for receiving events from TUNGKAO, not a Discord channel link.
POST /v1/email/send
{
"to": [
"[email protected]"
],
"subject": "Order #1001 confirmed",
"html": "<h1>Thanks for your order</h1>",
"text": "Thanks for your order",
"from_name": "My Shop",
"reply_to": "[email protected]"
}
➡️ Always send html and text; replies go to reply_to
예시 2
Send an email OTP
상황: A new sign-up must confirm their email
요청
POST /v1/email/otp/send
{
"to": "[email protected]",
"brand": "My Shop",
"lang": "th",
"length": 6,
"ttl_seconds": 300
}
➡️ Always check the address matches the network; wrong-network transfers can't be recovered
💸 Withdrawal fees: funds received through the API pay 3.5% per withdrawal; wallets you create yourself in the merchant portal pay 2.5%. Taken from the withdrawn coin, not credits; deposits are free (live rate: withdraw_fee_percent in GET /v1/crypto/assets).
🚦 시스템 상태 (GET /status)
API 정상 여부를 언제든 확인 — 키 불필요
GET https://api.tungkao.com/status
🟢 ok = 정상
🟠 busy = 이용자 많음
🔴 slow = 약간 지연
최근 5분 실제 요청 기준, 서비스별(services[]) 측정. 영수증 확인/입금은 모든 백업 제공자를 합산하며 경로별 상태는 routes[]
API 키 불필요, 브라우저에서 호출 가능(CORS 허용), 15초 캐시 — 1분에 한 번 이하로 조회 권장
busy/slow일 때 타임아웃을 15–20초로 늘리고 같은 Idempotency-Key로 재시도하세요 — 중복 과금 없음