ตัวอย่าง
ตัวอย่างการดึงยอดคงเหลือในภาษา PHP:
<?php
define('API_URL', 'https://api.example.com');
define('SECRET', 'secretkeysecretkeysecretkeysecretkeysecretkeysecretkey');
define('MERCHANT_ID', 'THXXXXXXXX');
define('TOKEN', 'tokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentoken');
$req = [
"merchant_id" => MERCHANT_ID,
"token" => TOKEN,
"time" => time()
];
$post_data = json_encode($req);
$signature = hash_hmac("sha256", $post_data, SECRET);
$curl = curl_init(API_URL . "/balance");
$headers = [
'Content-Type: application/json',
'X-Signature: ' . $signature
];
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
ตัวอย่างในภาษา Node.js
const axios = require('axios');
const crypto = require('crypto');
const API_URL = 'https://api.example.com';
const SECRET = 'secretkeysecretkeysecretkeysecretkeysecretkeysecretkey';
const MERCHANT_ID = 'THXXXXXXXX';
const TOKEN = 'tokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentoken';
const req = {
merchant_id: MERCHANT_ID,
token: TOKEN,
time: Math.floor(Date.now() / 1000)
};
const postData = JSON.stringify(req);
const signature = crypto.createHmac('sha256', SECRET)
.update(postData)
.digest('hex');
const headers = {
'Content-Type': 'application/json',
'X-Signature': signature
};
axios.post(API_URL + '/balance', postData, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
ตัวอย่างในภาษา Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;
public class ApiClient {
private static final String API_URL = "https://api.example.com/balance";
private static final String SECRET = "xxxxxx";
private static final String MERCHANT_ID = "TH00000000";
private static final String TOKEN = "yyyyyyyyy";
public static void main(String[] args) {
try {
// เตรียมข้อมูล request
String postData = String.format(
"{\"merchant_id\":\"%s\",\"token\":\"%s\",\"time\":%d}",
MERCHANT_ID, TOKEN, System.currentTimeMillis() / 1000
);
// สร้าง HMAC SHA-256 Signature
String signature = generateSignature(postData, SECRET);
// สร้าง HTTP request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("X-Signature", signature)
.POST(HttpRequest.BodyPublishers.ofString(postData))
.build();
// ส่ง HTTP request
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// จัดการ response
System.out.println(response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
// ฟังก์ชันสร้าง HMAC SHA-256 Signature
private static String generateSignature(String data, String secret) throws Exception {
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256Hmac.init(secretKey);
byte[] hash = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hash);
}
// ฟังก์ชันช่วยแปลง byte array เป็น hex string
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
หากคุณใช้ Postman ในการทดสอบ API สามารถเพิ่มโค้ดนี้ใน Pre-Request Script ได้
var secret_key = 'YOUR_SECRET_KEY_HERE';
var signBytes = CryptoJS.HmacSHA256(pm.request.body.raw, secret_key);
var signHex = CryptoJS.enc.Hex.stringify(signBytes);
pm.request.headers.add({
key: "X-Signature",
value: signHex
});
ตัวอย่างในภาษา C#
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Security.Cryptography;
public class ApiRequestExample
{
private const string API_URL = "https://api.example.com/balance";
private const string SECRET = "secretkeysecretkeysecretkeysecretkeysecretkeysecretkey";
private const string MERCHANT_ID = "THXXXXXXXX";
private const string TOKEN = "tokentokentokentokentoken...";
public static async Task Main(string[] args)
{
var req = new {
merchant_id = MERCHANT_ID,
token = TOKEN,
time = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
};
var postData = JsonConvert.SerializeObject(req);
var signature = GenerateHmacSha256(postData, SECRET);
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, API_URL);
request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
request.Headers.Add("X-Signature", signature);
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
public static string GenerateHmacSha256(string message, string secret)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(secret);
byte[] dataBytes = Encoding.UTF8.GetBytes(message);
using (var hmac = new HMACSHA256(keyBytes))
{
byte[] hashBytes = hmac.ComputeHash(dataBytes);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
}