1. 程式人生 > >HBuilder基礎上APP呼叫支付寶、微信支付(PHP)

HBuilder基礎上APP呼叫支付寶、微信支付(PHP)

支付寶後端程式碼:

  /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 訂單頁面支付(支付寶支付)
     */
    public function pay(Request $request){
        $callback = $request->get('callback');
     
        $pri_key = '私鑰';
        $arr = [
            'app_id' => '自己的APPID',
            'method' => 'alipay.trade.app.pay',
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'notify_url' => '自己的回撥地址',
            'biz_content' => '',
        ];
        $arr_param = [
            'subject' => '測試',
            'out_trade_no' => $order_number,
            'total_amount' =>strval($sum_price),
            'product_code' => 'QUICK_MSECURITY_PAY',
        ];
        $arr['biz_content'] = json_encode($arr_param,JSON_UNESCAPED_UNICODE);
        ksort($arr);
        $str = urldecode(http_build_query($arr));
        $rsa = new \RSA();
        $arr['sign'] =  $rsa->rsaSign($str, $pri_key);
        $content =  json_encode(['error_code'=>0,'content'=>http_build_query($arr)]);
        return $callback."(".$content.")";
    }

支付寶非同步回撥程式碼:

 /**
     * 支付寶非同步
     */
    public function notify(Request $request){
        $pub_key = '自己的公鑰';
        //獲取支付寶傳送的資料
        $params = $request -> all();
        //file_put_contents('./test.php', print_r($params,true) . "\r\n",FILE_APPEND);
        $sign = $params['sign'];
        //除去sign、sign_type
        unset($params['sign']);
        unset($params['sign_type']);
        //排序
        ksort($params);
        //拼接字串
        $str = urldecode(http_build_query($params));
        //使用公鑰驗籤
        $rsa = new \RSA();
        $stat = $rsa->rsaCheck($str, $pub_key, $sign);
        if($stat){
            //判斷支付狀態
            //file_put_contents('test.php',$params,FILE_APPEND);
            if($params['trade_status'] == 'TRADE_SUCCESS' ||  $params['trade_status'] == 'TRADE_FINISHED'){
                $data = DB::table('order')->where('order_number',$params['out_trade_no'])->first();
                //根據訂單號 判斷訂單金額是否一致
                if($data->sum_price == $params['total_amount']){
                    //update order stat 更新訂單狀態
                    $res = DB::table('order')->where('order_number',$params['out_trade_no'])->where('status',1)->update(['status'=>2]);
                    if($res > 0){
                        echo 'success';
                    }
                }
            }
        }
    }

支付寶前段程式碼:

function plusReady(){
	    // 獲取支付通道
	    plus.payment.getChannels(function(channels){
	        channel=channels[0];
	    },function(e){
	        alert("獲取支付通道失敗:"+e.message);
	    });
	}
	document.addEventListener('plusready',plusReady,false);
	$('#zhifu').click(function(){
		var order_num = sessionStorage.getItem('order_num');
		var sum_price = sessionStorage.getItem('sum_price');
		var token = localStorage.getItem('token');
		
		$.ajax({
            method: "get",
            url: "http://lmy.jinxiaofei.xyz/pay",
            data: {token:token,order_number:order_num,sum_price:sum_price},
            dataType:'jsonp'
       }).done(function( msg ) {
        	if(msg.error_code == 0){
	       		plus.payment.request(channel,msg.content,function(result){
		        plus.nativeUI.alert("支付成功!",function(){
		            location.href = './index.html';
		        }); 
			    },function(error){
			        plus.nativeUI.alert("支付失敗:" + error.code);
			    });
        		 
        	}else{
        		layerUtil.tip(msg.content);
        	}
		})
  	})

微信支付後端:

/**
     * 微信支付
     */
    public function weixin(Request $request){
        $callback = $request->get('callback');
        $key = 'K8djgYUIQDMCXdr0855kgjdjDGUJDDoi';
        $param = [
            'appid' => 'wx372200381123eeb2',
            'mch_id' => '1517545941',
            'nonce_str' => uniqid(),
            'body' => 'APP支付測試',
            'out_trade_no' => time().rand(1000,9999),
            'total_fee' => 1,
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'notify_url' => 'http://lmy.jinxiaofei.xyz/wx_notify',
            'trade_type' => 'APP',
        ];
        $sign = $this -> get_sign($param);
        $param['sign'] = $sign;
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $xml = $this -> ArrToXml($param);
        $data_xml = $this -> postStr($url,$xml);
        $data = $this -> XmlToArr($data_xml);
        $arr = [
            'appid' => 'wx372200381123eeb2',
            'partnerid' => '1517545941',
            'prepayid' => $data['prepay_id'],
            'package' => 'Sign=WXPay',
            'noncestr' => uniqid(),
            'timestamp' => time(),
        ];
       $sign2 = $this -> get_sign($arr);
       $arr['sign'] = $sign2;
       return  $callback."({content:".json_encode($arr)."})";
    }
    public function get_sign($arr){
        $key = 'K8djgYUIQDMCXdr0855kgjdjDGUJDDoi';
        ksort($arr);
        $str = urldecode(http_build_query($arr)).'&key='.$key;
        $sign = strtoupper(md5($str));
        return $sign;
    }
    /**
     * 微信非同步
     */
    public function wx_notify(){

    }
    //Xml 檔案轉陣列
    public function XmlToArr($xml)
    {
        if($xml == '') return '';
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }
    //陣列轉XML
    public function ArrToXml($arr)
    {
        if(!is_array($arr) || count($arr) == 0) return '';

        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    //post 字串到介面
    public function postStr($url,$postfields){
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //請求url地址
        $params[CURLOPT_HEADER] = false; //是否返回響應頭資訊
        $params[CURLOPT_RETURNTRANSFER] = true; //是否將結果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_SSL_VERIFYPEER] = false;//禁用證書校驗
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_POSTFIELDS] = $postfields;
        curl_setopt_array($ch, $params); //傳入curl引數
        $content = curl_exec($ch); //執行
        curl_close($ch); //關閉連線
        return $content;
    }

微信支付前段:

function plusReady(){
	    // 獲取支付通道
	    plus.payment.getChannels(function(channels){
	        channel=channels[1];
	    },function(e){
	        alert("獲取支付通道失敗:"+e.message);
	    });
	}
	document.addEventListener('plusready',plusReady,false);
	$('#zhifu').click(function(){
		
		$.ajax({
            method: "get",
            url: "http://lmy.jinxiaofei.xyz/weixin",
            data: {},
            dataType:'jsonp'
      }).done(function( msg ) {
	       		plus.payment.request(channel,msg.content,function(result){
		        plus.nativeUI.alert("支付成功!",function(){
		            location.href = './index.html';
		        }); 
			    },function(error){
			        plus.nativeUI.alert("支付失敗:" + error.code);
			    });
		})
  	})

注意:不管支付寶支付還是微信支付都需要在HBuilder中的配置檔案(manifest.json)的SDK配置中開通支付寶、微信支付

RSA類就是生成、驗證簽名的方法,就不完全上傳了,可以自己根據官方文件生成、驗證(並不複雜),最後預祝大家除錯成功