HBuilder基础上APP调用支付宝、微信支付(PHP)

版权声明:转发原创文章请复制文章链接地址 https://blog.csdn.net/weixin_42579642/article/details/83536696

支付宝后端代码:

  /**
     * @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类就是生成、验证签名的方法,就不完全上传了,可以自己根据官方文档生成、验证(并不复杂),最后预祝大家调试成功

猜你喜欢

转载自blog.csdn.net/weixin_42579642/article/details/83536696
今日推荐