调用API
<?php
//調用API生成一個錢包地址
$url = "https://api.ubao.io/mch/address/create";
$merchantId = "12345"; //商戶號
$api_key = "123456789"; //商戶密鑰
$timestamp = time();
//結果:1725607713
$nonce = rand(100000,999999);
//結果:212343
$body_data = array('chainType'=>160,'type'=>0,'callUrl'=>'http://www.xxx.com/xxx.html');
//把body數組轉為JSON字符串
$str = json_encode($body_data);
//結果:{"chainType":160,"type":0,"callUrl":"http:\/\/www.xxx.com\/xxx.html"}
//再用base64編碼,得到最終的body字符串
$body = base64_encode($str);
//結果:eyJjaGFpblR5cGUiOjE2MCwidHlwZSI6MCwiY2FsbFVybCI6Imh0dHA6XC9cL3d3dy54eHguY29tXC94eHguaHRtbCJ9
//簽名
$sign = md5($body . $api_key . $nonce . $timestamp);
//結果:5eab870f6a4fea6caabc6e0be4308bf0
//提交給網關的數據
$data = array('merchantId'=>$merchantId,'timestamp'=>$timestamp,'nonce'=>$nonce,'sign'=>$sign,'body'=>$body);
//用POST方式提交給網關
$res = curlPost($url,$data);
//結果:{"code":200,"message":"SUCCESS","address":"TQcK2oKpeVAE1mvYEudYJHgCr47F5ba8hk","chainType":160}
//得到執行結果後的業務處理
//......
function curlPost($url, $post_data = array(),$timeout = 5, $header = array("content-type: application/x-www-form-urlencoded"), $data_type = "") {
$header = empty($header) ? '' : $header;
if($data_type == 'json'){
$post_string = json_encode($post_data);
}elseif($data_type == 'array') {
$post_string = $post_data;
}elseif(is_array($post_data)){
$post_string = http_build_query($post_data, '', '&');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
充值回調處理 ubao_callback.php
<?php
$api_key = "123456789"; //商戶密鑰
$body = $_POST['body'];
$sign = $_POST['sign'];
$nonce = $_POST['nonce'];
$timestamp = $_POST['timestamp'];
$msg = "";
try {
$sign2 = md5($body . $api_key . $nonce . $timestamp);
if($sign2 != $sign){
$msg = "sign error";
throw new Exception();
}
$json = json_decode(base64_decode($body),true);
$decimals = $json['decimals'];
$amount = number_format($json['amount']/pow(10,$decimals),3,'.','') + 0;
if($json['callbackType'] == 'recharge'){
//充幣的業務邏輯處理
}
if($json['callbackType'] == 'transfer'){
//提幣或轉賬的業務邏輯處理
if($json['result'] == 1){
//轉賬成功
}
else{
//轉賬失敗
$msg = $json['message'];
}
}
if($json['callbackType'] == 'balance'){
//得到地址余額的業務邏輯處理
}
$msg = "SUCCESS";
}
catch (Exception $e) {
//
}
echo $msg;
?>