Code mẫu đấu nối website
Đặt SHOP_API_URL bằng URL ở trên và SHOP_API_KEY bằng khóa API của shop. Với Node.js, dùng phiên bản 18 trở lên. Đặt TARGET_UID để gửi đơn trong ví dụ PHP, Python và Node.js.
<?php
$apiUrl = getenv('SHOP_API_URL'); // URL lấy từ mục API của shop
$apiKey = getenv('SHOP_API_KEY');
if (!$apiUrl || !$apiKey) {
exit("Cần đặt SHOP_API_URL và SHOP_API_KEY.\n");
}
function callShop(string $action, ?array $body = null, array $query = []): array {
global $apiUrl, $apiKey;
$url = $apiUrl . '&' . http_build_query(['a' => $action] + $query);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
],
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode((string) $response, true);
if (!is_array($result)) {
throw new RuntimeException("API trả HTTP $http nhưng không có JSON.");
}
if ($http >= 400 || isset($result['error'])) {
throw new RuntimeException($result['error'] ?? "Lỗi HTTP $http");
}
return $result;
}
print_r(callShop('balance'));
// Chỉ gửi đơn khi chủ động đặt biến TARGET_UID.
$target = getenv('TARGET_UID');
if ($target) {
$order = callShop('order', ['target' => $target, 'qty' => 1000, 'note' => 'Đơn #101']);
print_r(callShop('orders', null, ['id' => $order['id']]));
}
import json
import os
from urllib.parse import urlencode
from urllib.request import Request, urlopen
base = os.environ["SHOP_API_URL"]
key = os.environ["SHOP_API_KEY"]
def call_shop(action, payload=None, **query):
url = base + "&" + urlencode({"a": action, **query})
data = None if payload is None else json.dumps(payload).encode()
request = Request(url, data=data, headers={
"Authorization": "Bearer " + key,
"Content-Type": "application/json",
})
with urlopen(request, timeout=20) as response:
return json.load(response)
print(call_shop("balance"))
target = os.getenv("TARGET_UID")
if target:
order = call_shop("order", {"target": target, "qty": 1000})
print(call_shop("orders", id=order["id"]))
const { SHOP_API_URL, SHOP_API_KEY, TARGET_UID } = process.env;
if (!SHOP_API_URL || !SHOP_API_KEY) throw new Error('Thiếu biến môi trường API');
async function callShop(action, body, query = {}) {
const url = new URL(SHOP_API_URL);
url.searchParams.set('a', action);
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
const response = await fetch(url, {
method: body ? 'POST' : 'GET',
headers: { Authorization: 'Bearer ' + SHOP_API_KEY, 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(20000)
});
const data = await response.json();
if (!response.ok || data.error) throw new Error(data.error || 'HTTP ' + response.status);
return data;
}
async function main() {
console.log(await callShop('balance'));
if (TARGET_UID) {
const order = await callShop('order', { target: TARGET_UID, qty: 1000 });
console.log(await callShop('orders', undefined, { id: order.id }));
}
}
main().catch(console.error);
# SHOP_API_URL có dạng https://ten-mien-cua-ban/api.php?client=api
curl -sS --max-time 20 -H "Authorization: Bearer $SHOP_API_KEY" "$SHOP_API_URL&a=balance"
curl -sS --max-time 20 -H "Authorization: Bearer $SHOP_API_KEY" "$SHOP_API_URL&a=orders&size=8"
# Tạo đơn thật khi bạn chủ động bật SEND_ORDER=1.
if [ "$SEND_ORDER" = "1" ]; then
curl -sS --max-time 20 -X POST "$SHOP_API_URL&a=order" \
-H "Authorization: Bearer $SHOP_API_KEY" -H "Content-Type: application/json" \
--data '{"target":"VeBenA","qty":1000,"note":"Don #101"}'
fi