Chuyển tới nội dung chính

Code Examples (Mã lệnh SDK)

Bạn có thể dễ dàng gọi API Tạo Hóa Đơn (/payment/crypto) từ các ngôn ngữ phổ biến trên Backend.

Trường hợp Backend của bạn không có ngôn ngữ dưới đây, bạn chỉ cần gửi request POST tới https://api.payerscan.com/payment/crypto với JSON body và header x-api-key.

JavaScript / Node.js (Axios)

const axios = require('axios');

async function createCryptoPayment() {
try {
const response = await axios.post(
'https://api.payerscan.com/payment/crypto',
{
merchant_id: 'MID-XXXXXXXXXX',
amount: 100,
request_id: `ORDER_${Date.now()}`,
name: 'Giày Thể Thao',
description: 'Tài trợ cho team.',
callback_url: 'https://shop.com/webhook',
completed_url: 'https://shop.com/success',
expired_url: 'https://shop.com/cancel'
},
{
headers: {
'Content-Type': 'application/json',
'x-api-key': 'YOUR_API_KEY_HERE'
}
}
);

console.log('Invoice Created:', response.data.data.url_payment);
// Chuyển hướng trình duyệt người dùng tới đường link url_payment trên
} catch (error) {
if (error.response) {
console.error('API Error:', error.response.data);
} else {
console.error('Request Failed:', error.message);
}
}
}

createCryptoPayment();

Python (Requests Library)

import requests
import time

def create_crypto_payment():
url = "https://api.payerscan.com/payment/crypto"

headers = {
"Content-Type": "application/json",
"x-api-key": "YOUR_API_KEY_HERE"
}

payload = {
"merchant_id": "MID-XXXXXXXXXX",
"amount": 100,
"request_id": f"ORDER_{int(time.time())}",
"name": "Giày Thể Thao",
"description": "Tài trợ cho team.",
"callback_url": "https://shop.com/webhook",
"completed_url": "https://shop.com/success",
"expired_url": "https://shop.com/cancel"
}

try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status() # Báo lỗi nếu HTTP 4xx/5xx
data = response.json()

print(f"Invoice URL: {data['data']['url_payment']}")

except requests.exceptions.RequestException as e:
print(f"API Error: {e}")

if __name__ == "__main__":
create_crypto_payment()

PHP (cURL)

<?php

$url = 'https://api.payerscan.com/payment/crypto';
$apiKey = 'YOUR_API_KEY_HERE';

$data = [
'merchant_id' => 'MID-XXXXXXXXXX',
'amount' => 100,
'request_id' => 'ORDER_' . time(),
'name' => 'Giày Thể Thao',
'description' => 'Tài trợ cho team.',
'callback_url' => 'https://shop.com/webhook',
'completed_url' => 'https://shop.com/success',
'expired_url' => 'https://shop.com/cancel'
];

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . $apiKey
]
]);

$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($result === false) {
$error = curl_error($ch);
curl_close($ch);
die('Lỗi cURL: ' . $error);
}
curl_close($ch);

$response = json_decode($result, true);

if ($httpCode === 200 && $response['status'] === 'success') {
echo 'URL Thanh toán: ' . $response['data']['url_payment'];
} else {
echo 'Lỗi: ' . ($response['message'] ?? 'Lỗi không xác định');
}

?>

Java / Spring Boot (RestClient)

import org.springframework.http.*;
import org.springframework.web.client.RestClient;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.Instant;
import java.util.Map;

public class PayerScanExample {

public static void main(String[] args) throws Exception {
RestClient restClient = RestClient.create();
ObjectMapper mapper = new ObjectMapper();

Map<String, Object> payload = Map.of(
"merchant_id", "MID-XXXXXXXXXX",
"amount", 100,
"request_id", "ORDER_" + Instant.now().toEpochMilli(),
"name", "Premium Sneakers",
"description", "Team sponsorship.",
"callback_url", "https://shop.com/webhook",
"completed_url", "https://shop.com/success",
"expired_url", "https://shop.com/cancel"
);

try {
String body = restClient.post()
.uri("https://api.payerscan.com/payment/crypto")
.header("x-api-key", "YOUR_API_KEY_HERE")
.contentType(MediaType.APPLICATION_JSON)
.body(mapper.writeValueAsString(payload))
.retrieve()
.body(String.class);

JsonNode json = mapper.readTree(body);
System.out.println("Payment URL: " + json.at("/data/url_payment").asText());
} catch (Exception e) {
System.err.println("API Error: " + e.getMessage());
}
}
}

Ruby (Net::HTTP)

require 'net/http'
require 'json'
require 'uri'

url = URI('https://api.payerscan.com/payment/crypto')

payload = {
merchant_id: 'MID-XXXXXXXXXX',
amount: 100,
request_id: "ORDER_#{Time.now.to_i}",
name: 'Premium Sneakers',
description: 'Team sponsorship.',
callback_url: 'https://shop.com/webhook',
completed_url: 'https://shop.com/success',
expired_url: 'https://shop.com/cancel'
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url.path)
request['Content-Type'] = 'application/json'
request['x-api-key'] = 'YOUR_API_KEY_HERE'
request.body = payload.to_json

begin
response = http.request(request)
data = JSON.parse(response.body)

if response.code == '200' && data['status'] == 'success'
puts "Payment URL: #{data['data']['url_payment']}"
else
puts "Error: #{data['message'] || 'Unknown error'}"
end
rescue StandardError => e
puts "Request failed: #{e.message}"
end

Go (net/http)

package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)

func main() {
payload := map[string]interface{}{
"merchant_id": "MID-XXXXXXXXXX",
"amount": 100,
"request_id": fmt.Sprintf("ORDER_%d", time.Now().UnixMilli()),
"name": "Premium Sneakers",
"description": "Team sponsorship.",
"callback_url": "https://shop.com/webhook",
"completed_url": "https://shop.com/success",
"expired_url": "https://shop.com/cancel",
}

body, _ := json.Marshal(payload)

req, err := http.NewRequest("POST", "https://api.payerscan.com/payment/crypto", bytes.NewBuffer(body))
if err != nil {
fmt.Println("Request error:", err)
return
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", "YOUR_API_KEY_HERE")

resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("HTTP error:", err)
return
}
defer resp.Body.Close()

respBody, _ := io.ReadAll(resp.Body)

var result map[string]interface{}
json.Unmarshal(respBody, &result)

if resp.StatusCode == 200 {
if data, ok := result["data"].(map[string]interface{}); ok {
fmt.Println("Payment URL:", data["url_payment"])
}
} else {
fmt.Println("Error:", result["message"])
}
}

Rust (reqwest)

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde_json::{json, Value};
use std::time::{SystemTime, UNIX_EPOCH};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)?
.as_millis();

let payload = json!({
"merchant_id": "MID-XXXXXXXXXX",
"amount": 100,
"request_id": format!("ORDER_{}", timestamp),
"name": "Premium Sneakers",
"description": "Team sponsorship.",
"callback_url": "https://shop.com/webhook",
"completed_url": "https://shop.com/success",
"expired_url": "https://shop.com/cancel"
});

let mut headers = HeaderMap::new();
headers.insert(
HeaderName::from_static("x-api-key"),
HeaderValue::from_static("YOUR_API_KEY_HERE"),
);

let client = reqwest::Client::new();
let response = client
.post("https://api.payerscan.com/payment/crypto")
.headers(headers)
.json(&payload)
.send()
.await?;

let status = response.status();
let body: Value = response.json().await?;

if status.is_success() {
println!("Payment URL: {}", body["data"]["url_payment"]);
} else {
eprintln!("Error: {}", body["message"]);
}

Ok(())
}