ตัวอย่าง 2

หากคุณใช้ 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
});

ตัวอย่าง PHP

<?php

define('API_URL', 'https://api.example.com');
define('SECRET', 'secretkeysecretkeysecretkeysecretkeysecretkeysecretkey');
define('MERCHANT_ID', 'AA12345678');
define('TOKEN', 'testtokentesttokentesttokentesttokentesttoken');

function sendRequest($path, $data) {
    $postData = json_encode($data);
    $signature = hash_hmac('sha256', $postData, SECRET);

    $curl = curl_init(API_URL . $path);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-Signature: ' . $signature
    ]);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($curl);
    curl_close($curl);

    return $response;
}

echo "ผลลัพธ์ Balance:\n";
echo sendRequest('/balance', [
    "merchant_id" => MERCHANT_ID,
    "token" => TOKEN,
    "time" => time()
]);

echo "\n\nผลลัพธ์สร้างคำสั่งชำระเงิน:\n";
echo sendRequest('/payment-flex/create', [
    "merchant_id" => MERCHANT_ID,
    "token" => TOKEN,
    "time" => time(),
    "merchant_order_id" => "ORDER" . time(),
    "amount" => "1000.00",
    "bank" => "KBANK",
    "account_name" => "สมชาย ใสสว่าง",
    "account_no" => "1234567890",
    "notify_url" => "https://merchant.com/callback/payment"
]);




ตัวอย่าง NodeJS

const axios = require('axios');
const crypto = require('crypto');

const API_URL = 'https://api.example.com';
const SECRET = 'secretkeysecretkeysecretkeysecretkeysecretkeysecretkey';
const MERCHANT_ID = 'AA12345678';
const TOKEN = 'testtokentesttokentesttokentesttokentesttoken';

async function sendRequest(path, data) {
    const postData = JSON.stringify(data);
    const signature = crypto.createHmac('sha256', SECRET).update(postData).digest('hex');

    const headers = {
        'Content-Type': 'application/json',
        'X-Signature': signature
    };

    const response = await axios.post(API_URL + path, data, { headers });
    return response.data;
}

(async () => {
    console.log('ผลลัพธ์ Balance:');
    console.log(await sendRequest('/balance', {
        merchant_id: MERCHANT_ID,
        token: TOKEN,
        time: Math.floor(Date.now() / 1000)
    }));

    console.log('\nผลลัพธ์สร้างคำสั่งชำระเงิน:');
    console.log(await sendRequest('/payment-flex/create', {
        merchant_id: MERCHANT_ID,
        token: TOKEN,
        time: Math.floor(Date.now() / 1000),
        merchant_order_id: 'ORDER' + Date.now(),
        amount: "1000.00",
        bank: "KBANK",
        account_name: "สมชาย ใสสว่าง",
        account_no: "1234567890",
        notify_url: "https://merchant.com/callback/payment"
    }));
})();



ตัวอย่าง 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.time.Instant;

public class ApiClient {
    private static final String API_URL = "https://api.example.com";
    private static final String SECRET = "secretkeysecretkeysecretkeysecretkeysecretkeysecretkey";
    private static final String MERCHANT_ID = "AA12345678";
    private static final String TOKEN = "testtokentesttokentesttokentesttokentesttoken";

    public static void main(String[] args) throws Exception {
        System.out.println("ผลลัพธ์ Balance:");
        System.out.println(sendRequest("/balance",
            "{\"merchant_id\":\"" + MERCHANT_ID + "\",\"token\":\"" + TOKEN + "\",\"time\":" + Instant.now().getEpochSecond() + "}"));

        System.out.println("\nผลลัพธ์สร้างคำสั่งชำระเงิน:");
        String paymentData = String.format(
            "{\"merchant_id\":\"%s\",\"token\":\"%s\",\"time\":%d,\"merchant_order_id\":\"ORDER%d\",\"amount\":\"1000.00\",\"bank\":\"KBANK\",\"account_name\":\"สมชาย ใสสว่าง\",\"account_no\":\"1234567890\",\"notify_url\":\"https://merchant.com/callback/payment\"}",
            MERCHANT_ID, TOKEN, Instant.now().getEpochSecond(), Instant.now().getEpochSecond());

        System.out.println(sendRequest("/payment-flex/create", paymentData));
    }

    private static String sendRequest(String path, String postData) throws Exception {
        String signature = generateSignature(postData, SECRET);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_URL + path))
            .header("Content-Type", "application/json")
            .header("X-Signature", signature)
            .POST(HttpRequest.BodyPublishers.ofString(postData))
            .build();

        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    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);
    }

    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();
    }
}


ตัวอย่าง C


using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Security.Cryptography;

class Program
{
    private const string API_URL = "https://api.example.com";
    private const string SECRET = "secretkeysecretkeysecretkeysecretkeysecretkeysecretkey";
    private const string MERCHANT_ID = "AA12345678";
    private const string TOKEN = "testtokentesttokentesttokentesttokentesttoken";

    static async Task Main(string[] args)
    {
        Console.WriteLine("ผลลัพธ์ Balance:");
        Console.WriteLine(await SendRequest("/balance", new {
            merchant_id = MERCHANT_ID,
            token = TOKEN,
            time = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
        }));

        Console.WriteLine("\nผลลัพธ์สร้างคำสั่งชำระเงิน:");
        Console.WriteLine(await SendRequest("/payment-flex/create", new {
            merchant_id = MERCHANT_ID,
            token = TOKEN,
            time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
            merchant_order_id = "ORDER" + DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
            amount = "1000.00",
            bank = "KBANK",
            account_name = "สมชาย ใสสว่าง",
            account_no = "1234567890",
            notify_url = "https://merchant.com/callback/payment"
        }));
    }

    public static async Task<string> SendRequest(string path, object data)
    {
        var postData = JsonConvert.SerializeObject(data);
        var signature = GenerateHmacSha256(postData, SECRET);

        using (var client = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Post, API_URL + path);
            request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
            request.Headers.Add("X-Signature", signature);

            var response = await client.SendAsync(request);
            return await response.Content.ReadAsStringAsync();
        }
    }

    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();
        }
    }
}


ตัวอย่าง Golang

package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	API_URL     = "https://api.example.com"
	SECRET      = "secretkeysecretkeysecretkeysecretkeysecretkeysecretkey"
	MERCHANT_ID = "AA12345678"
	TOKEN       = "testtokentesttokentesttokentesttokentesttoken"
)

func main() {
	balanceResp, _ := sendRequest("/balance", map[string]interface{}{
		"merchant_id": MERCHANT_ID,
		"token":       TOKEN,
		"time":        time.Now().Unix(),
	})
	fmt.Println("ผลลัพธ์ Balance:", balanceResp)

	paymentResp, _ := sendRequest("/payment-flex/create", map[string]interface{}{
		"merchant_id":       MERCHANT_ID,
		"token":             TOKEN,
		"time":              time.Now().Unix(),
		"merchant_order_id": fmt.Sprintf("ORDER%d", time.Now().Unix()),
		"amount":            "1000.00",
		"bank":              "KBANK",
		"account_name":      "สมชาย ใสสว่าง",
		"account_no":        "1234567890",
		"notify_url":        "https://merchant.com/callback/payment",
	})
	fmt.Println("ผลลัพธ์สร้างคำสั่งชำระเงิน:", paymentResp)
}

func sendRequest(path string, data map[string]interface{}) (string, error) {
	jsonData, _ := json.Marshal(data)
	signature := generateHmacSha256(string(jsonData), SECRET)

	client := &http.Client{}
	req, _ := http.NewRequest("POST", API_URL+path, bytes.NewBuffer(jsonData))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Signature", signature)

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), nil
}

func generateHmacSha256(data, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(data))
	return hex.EncodeToString(h.Sum(nil))
}

ตัวอย่าง Python

import requests
import json
import hmac
import hashlib
import time

API_URL = "https://api.example.com"
SECRET = "secretkeysecretkeysecretkeysecretkeysecretkeysecretkey"
MERCHANT_ID = "AA12345678"
TOKEN = "testtokentesttokentesttokentesttokentesttoken"

def send_request(path, data):
    post_data = json.dumps(data)
    signature = hmac.new(SECRET.encode(), post_data.encode(), hashlib.sha256).hexdigest()

    headers = {
        'Content-Type': 'application/json',
        'X-Signature': signature
    }

    response = requests.post(API_URL + path, data=post_data, headers=headers)
    return response.text

if __name__ == "__main__":
    balance_response = send_request("/balance", {
        "merchant_id": MERCHANT_ID,
        "token": TOKEN,
        "time": int(time.time())
    })
    print("ผลลัพธ์ Balance:", balance_response)

    payment_response = send_request("/payment-flex/create", {
        "merchant_id": MERCHANT_ID,
        "token": TOKEN,
        "time": int(time.time()),
        "merchant_order_id": f"ORDER{int(time.time())}",
        "amount": "1000.00",
        "bank": "KBANK",
        "account_name": "สมชาย ใสสว่าง",
        "account_no": "1234567890",
        "notify_url": "https://merchant.com/callback/payment"
    })
    print("ผลลัพธ์สร้างคำสั่งชำระเงิน:", payment_response)