~~~
<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Cache;
use think\Loader;
use qrcode\QRcode;
class Xinpay extends Controller
{
public function index(){
header('Content-type: text/html; charset=UTF8');
$server_url = $_SERVER['SERVER_NAME']?"http://".$_SERVER['SERVER_NAME']:"http://".$_SERVER['HTTP_HOST'];
$res = $this->request->param();
//獲取請求訂單參數
$price=$res['bpprice'];
$bpid=$res['bpid'];
$key="b6nLz7FO5Bp31YDPMk2TA9a8qCewSHlI";
$data["mch_id"]="856327393158";
$data["merchant_trade_no"]="longtai".time();
//充值表
Db::table('wp_balance')->where('bpid',$res['bpid'])->setField('balance_sn', $data["merchant_trade_no"]);
$data["total_fee"]=10;
$data["total_fee"]=$price*100;
$data["body"]="test";
$data["attach"]="attach";
$data["callback_url"]=$server_url."/api/xinpay/callback";
$data["return_url"]=$server_url."/api/xinpay/refurn";
if($res['paytype']==2){
$data["pay_type"]="WECHATCODEPAY";//微信
}else if($res['paytype']==1){
//$data["pay_type"]="ALICODEPAY";//支付寶
//$data["pay_type"]="ALIWAPPAY";
$data["pay_type"]="QQCODEPAY";//qq掃碼
//$data["pay_type"]="WECHATJSAPIPAY";
}
$data["sign"] = $this->createSign($data,$key);//生成簽名
$url ='http://xin.zhijiankeji.top/payRequest';
$re = $this->http_post($url, $data);
if ($re['return_code']=='SUCCESS' && $re['result_code']=='SUCCESS') {
// 驗證簽名
if($this->checkSign($re,$re["sign"],$key)){
switch ($re['pay_type']) {
case 'ALICODEPAY'://支付寶掃碼
$pay_type = '支付寶';
break;
case 'WECHATCODEPAY'://微信掃碼
$pay_type = '微信';
$re['pay_info'] = $this->qrCode($re['pay_info'],$this->getRandom(),$server_url);//微信掃碼需要自己將收到的pay_info生成二維碼圖片
break;
case 'QQCODEPAY'://qq掃碼
$pay_type = 'QQ';
break;
case 'ALIJSAPIPAY'://支付寶服務窗
$this->ali_jsapi_pay($re['pay_info'],$config['return_url']);exit();
break;
default:
header('Location:'.$re['pay_info']);exit();
break;
}
$this->assign('pay_type',$pay_type);
$this->assign('data',$data);
//halt($re);
$this->assign('re',$re);
return $this->fetch('pay');
}else{
//驗證簽名失敗
echo "簽名驗證失敗";
exit();
}
}else{
echo $re['return_msg'];
}
}
public function callback(){
$key="b6nLz7FO5Bp31YDPMk2TA9a8qCewSHlI";
$param = $_POST;
if (!$param) {
exit("FAIL");
//echo "FAIL";
}
// 驗證簽名
if($this->checkSign($param,$param["sign"],$key)){
//調試將接收到的數據寫入文件查看
$this->writelog('--post='.json_encode($param),'huidiao2');
//接收支付回調結果 return_code和result_code都為SUCCESS的時候才代表支付成功 返回SUCCESS即可
if($param['return_code']=="SUCCESS"&& $param['result_code']=="SUCCESS"){
/*此處商戶自行處理業務邏輯判斷和操作
*
*驗證訂單是否已支付,如果已支付直接輸出SUCCESS,避免重復操作,
*如果未支付則根據回調結果進行訂單處理
**/
// 詳情返回參數見 回調API接口文檔
// 支付類型
$pay_type = $param["pay_type"];
$notify_fee =$param["total_fee"]/100; //實際支付金額
$times =time(); //支付時間
$sdorderno=$param["merchant_trade_no"]; //用戶自己的訂單號
$ispay=Db::table('wp_balance')->where('balance_sn',$sdorderno)->value('bptype');
if($ispay==1){
exit("SUCCESS");
}else{
$uid=Db::table('wp_balance')->where('balance_sn',$sdorderno)->value('uid');
$money=Db::table('wp_userinfo')->where('uid',$uid)->value('usermoney');
$money1=$money+$notify_fee;
//用戶表
$res1= Db::table('wp_userinfo')->where('uid',$uid)->setField('usermoney',$money1);
if($res1!=0){
//充值表
$aaaa=['isverified'=>1,'cltime'=>$times,'bptype'=>1,'bptime'=>$times,'bpprice'=>$notify_fee,'remarks'=>'會員充值','bpbalance'=>$money1,'btime'=>$times,'reg_par'=>0];
$res2= Db::table('wp_balance')->where('balance_sn',$sdorderno)->update($aaaa);
if($res2!=0){
$this->writelog('充值成功','huidiao');
exit("SUCCESS");
//echo "SUCCESS";
}
}
}
}else{
//驗證簽名失敗
exit("FAIL");
//echo "FAIL";
}
}
}
public function query(){
$res = $this->request->param();
//獲取請求訂單參數
$sn=$res['out_trade_no'];
$ispay=Db::table('wp_balance')->where('balance_sn',$sn)->value('bptype');
if($ispay==1){
return ['status'=>1, 'message'=>'支付成功'];
}else{
return ['status'=>0, 'message'=>'支付失敗'];
}
}
//獲取隨機字符串+數字組合
function getRandom() {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = mt_rand(6,12);
$str = substr(str_shuffle($chars),0,$length);
return $str;
}
/**
* 系統簽名驗證
* @param array $param 返回參數
* @param string $sign 待驗證簽名
* @param string $key 商戶秘鑰
* @return bool
*/
function checkSign($param=array(),$sign="",$key = ""){
unset($param["sign"]);
//簽名步驟一:按字典序排序參數
ksort($param);
$string = $this->ToUrlParams($param);
//簽名步驟二:在string后加入KEY
$string = $string ."&key=".$key;
//簽名步驟三:MD5加密
$string = md5($string);
//簽名步驟四:所有字符轉為大寫
$result = strtoupper($string);
if(md5($result)!=md5($sign)){
return false;
}else{
return true;
}
}
/**
* 生成簽名
* @param array $param
* @param string $secret
* @return string
*/
function createSign($param=array(),$key = ""){
if (isset($param["sign"])) {
unset($param["sign"]);
}
//簽名步驟一:按字典序排序參數
ksort($param);
$string = $this->ToSignParams($param);
//簽名步驟二:在string后加入KEY
$string = $string ."&key=".$key;
//簽名步驟三:MD5加密
$string = md5($string);
//簽名步驟四:所有字符轉為大寫
$sign = strtoupper($string);
return $sign;
}
/**
* 格式化生成sign的參數
*/
function ToSignParams($data=array()){
$buff = "";
foreach ($data as $k => $v){
$buff .= trim($k) . "=" . trim($v) . "&";
}
$buff = trim($buff, "&");
return $buff;
}
/**
* 格式化url參數
*/
function ToUrlParams($data=array()){
$buff = "";
foreach ($data as $k => $v) {
$buff .= $k . "=" . $v . "&";
}
$buff = trim($buff, "&");
return $buff;
}
function http_post($url, $param){
if(!is_array($param)){
return array("return_code"=>"FALL","return_msg"=>"參數必須為array");
}
$httph =curl_init($url);
curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
curl_setopt($httph, CURLOPT_POST, 1);//設置為POST方式
curl_setopt($httph, CURLOPT_POSTFIELDS, $param);
curl_setopt($httph, CURLOPT_RETURNTRANSFER,1);
curl_setopt($httph, CURLOPT_HEADER,0);
curl_setopt($httph, CURLOPT_FOLLOWLOCATION, 1);
$rst=curl_exec($httph);
curl_close($httph);
if($rst){
ob_clean();
return json_decode($rst,true);
}else{
return array("return_code"=>"FALL","return_msg"=>"服務器請求失敗");
}
}
/**
* 生成二維碼
* @param string $data
* @param string $title
*/
function qrCode($data="",$title="",$server_url){
Loader::import('xinpay.phpqrcode.phpqrcode');
//生成二維碼圖片
$object = new QRcode();
$url=$data;//網址或者是文本內容
$level=3;
$size=10;
$errorCorrectionLevel =intval($level) ;//容錯級別
$matrixPointSize = intval($size);//生成圖片大小
if (!file_exists('./qrcode')) {
mkdir('./qrcode',777);
}
$file_path = './qrcode/'.$title.".png";
$qrcode_path = $server_url."/qrcode/".$title.".png";
$object->png($url, $file_path, $errorCorrectionLevel, $matrixPointSize, 2);
return $qrcode_path;
}
public function refurn(){
return $this->fetch('refurn');
}
public function writelog($text, $aType='')
{
$text = $this->characet1($text);
file_put_contents (dirname ( __FILE__ )."/fb1log_".$aType._. date( "Y-m-d" ).".txt", date ( "Y-m-d H:i:s" ) . " " . $text . "\r\n", FILE_APPEND );
}
function characet1($data)
{
if (! empty ( $data ))
{
$fileType = mb_detect_encoding ( $data, array (
'UTF-8',
'GBK',
'GB2312',
'LATIN1',
'BIG5'
) );
if ($fileType != 'UTF-8')
{
$data = mb_convert_encoding ( $data, 'UTF-8', $fileType );
}
}
return $data;
}
function ali_jsapi_pay($tradeNO,$callback_url){
$html = <<<EOF
<html>
<head>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style='display:none;border-radius:52px;height:104px;width:104px;background-color:#10AEFF;border:none;font-size:4em;font-weight:bold;color:#fff;margin:30px auto;text-align:center;line-height:104px' id='icon'>i</div>
<h3 style='display:none;text-align:center' id='title'>請在支付寶客戶端打開鏈接!</h3>
<script type="text/javascript">
function isAlipay() {
var userAgent = navigator.userAgent.toLowerCase();
if(userAgent.match(/Alipay/i) != "alipay") {
document.getElementById('title').style.display="block";
document.getElementById('icon').style.display="block";
}
}
isAlipay();
var options = {"tradeNO":'$tradeNO'};
AlipayJSBridge.call('tradePay', options ,function(result){
if(result.resultCode == '9000'){
location.href="$callback_url";//支付成功后跳轉處理
}
});
</script>
</body>
</html>
EOF;
echo $html;die;
}
function wechat_jsapi_pay($jsApiParameters,$callback_url){
$html = <<<EOF
<meta http-equiv='Content-Type:content='text/html;charset=utf-8'>
<script type="text/javascript">
//調用微信JS api 支付
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',$jsApiParameters,
function(res){
//WeixinJSBridge.log(res.err_msg);
if(res.err_msg == "get_brand_wcpay_request:ok") {
alert('支付成功');
location.href='$callback_url';
}else{
alert(res.err_desc+res.err_msg);
}
}
);
}
function callpay()
{
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
jsApiCall();
}
}
callpay();
</script>
EOF;
echo $html;die;
}
}
~~~