代码示例(SDK)
您可以轻松地从常见的后端语言调用创建发票 API(/payment/crypto)。
如果您的后端不使用以下语言之一,只需向 https://api.payerscan.com/payment/crypto 发送 POST 请求,附带 JSON body 和 x-api-key header 即可。
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: 'Premium Sneakers',
description: 'Team sponsorship.',
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('发票已创建:', response.data.data.url_payment);
// 将用户浏览器重定向到上方的 url_payment 链接
} catch (error) {
if (error.response) {
console.error('API 错误:', error.response.data);
} else {
console.error('请求失败:', error.message);
}
}
}
createCryptoPayment();
Python (Requests 库)
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": "Premium Sneakers",
"description": "Team sponsorship.",
"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() # HTTP 4xx/5xx 时抛出错误
data = response.json()
print(f"发票 URL: {data['data']['url_payment']}")
except requests.exceptions.RequestException as e:
print(f"API 错误: {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' => 'Premium Sneakers',
'description' => 'Team sponsorship.',
'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('cURL 错误: ' . $error);
}
curl_close($ch);
$response = json_decode($result, true);
if ($httpCode === 200 && $response['status'] === 'success') {
echo '支付 URL: ' . $response['data']['url_payment'];
} else {
echo '错误: ' . ($response['message'] ?? '未知错误');
}
?>
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(())
}