uniapp微信app支付+服务端php处理微信app支付教程

用户端uniapp接入微信app支付,服务端使用php处理。

1、微信支付统一下单

调用接口:https://api.mch.weixin.qq.com/pay/unifiedorder

需提前到微信开放平台(微信开放平台)申请移动应用获得应用Appid;前往微信商户(微信支付 - 中国领先的第三方支付平台 | 微信支付提供安全快捷的支付方式)申请开通App支付权限,获得商户mchid,v2支付秘钥。

2、创建支付订单

在项目controller目录中wxpay.php,并且创建支付订单

    //创建微信支付订单
	public function index(){

		$WX_PAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //统一下单请求链接
		$NOTIFY_URL = "https://xxxx/notify"; //回调链接

		$WX_APPID = ''; //微信开放平台appid
		$WX_MCHID = ''; //商户号
		$WX_MCHKEY = ''; //微信商户v2支付秘钥

		$out_trade_no=$this->getOuttRadeno(); //获取商户内部订单号
		$nonce_str = $this->randCode(); //生成随机字符串
		$data['appid'] = $WX_APPID; //微信开放平台appid
		$data['mch_id'] = $WX_MCHID; //商户号
		$data['body'] = '商品1'; //支付描述
		$data['spbill_create_ip'] = $this->getIp(); //ip地址
		$data['total_fee'] = '100'; //金额:单位分
		$data['out_trade_no'] =$out_trade_no; //商户内部订单号
		$data['nonce_str'] = $nonce_str; //随机字符串
		$data['notify_url'] = $NOTIFY_URL; //回调地址,必须为能直接访问的网址,不能拼接参数
		$data['trade_type'] = 'APP'; //支付方式
		
		$data['sign'] =  $this->getSign($data,$WX_MCHKEY); //获取签名
		$xml =  $this->ToXml($data); //数组转xml
		//发起请求
		$data =  $this->curlHttpRequest($WX_PAY_URL, $xml);
		//返回结果
		if($data){
			//返回成功,将xml数据转换为数组.
			$re = $this->FromXml($data);
			if($re['return_code'] != 'SUCCESS'){
				echo json_encode(array("code"=>0,'msg'=>'签名失败'));die;
			}else{
				//创建新订单
				

                //接收微信返回的数据,传给uniapp客户端
				$arr =array('prepayid' =>$re['prepay_id'],'appid' => $WX_APPID,'partnerid' => $WX_MCHID,'package' => 'Sign=WXPay','noncestr' => $nonce_str,'timestamp' =>time());
				//第二次生成签名
				$sign =  $this->getSign($arr,$WX_MCHKEY);
				$arr['sign'] = $sign;
				echo json_encode(array("code"=>1,'orderinfo'=>$arr));die;

			}
		} else {
			$error = curl_errno($ch);
			curl_close($ch);
			echo json_encode(array("code"=>0,'msg'=>'签名失败'.$error));die;
		}
	}

生成商家内部订单号:$this->getOuttRadeno();

    //生成商家订单号,根据项目自行生成,不必和下面一致
	public function getOuttRadeno(){
		$str = 'YZ'.time().mt_rand(1000,9999);
		return $str;
	}

生成随机字符串:$this->randCode(); 

    //生成32位随机字符串
    public function randCode(){
		$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
		$str = str_shuffle($str);
		$str = substr($str,0,32);
		return $str;
	}

获取用户端Ip地址:$this->getIp();

    //获取ip地址
	public function getIp(){
		if ($_SERVER['REMOTE_ADDR']) {
			$ip = $_SERVER['REMOTE_ADDR'];
		} elseif (getenv("REMOTE_ADDR")) {
			$ip = getenv("REMOTE_ADDR");
		} elseif (getenv("HTTP_CLIENT_IP")) {
			$ip = getenv("HTTP_CLIENT_IP");
		} else {
			$ip = "unknown";
		}
		return $ip;
	}

获取微信支付签名:$this->getSign();

    //获取微信支付签名
	public function getSign($params,$skey){
		ksort($params);
	    $string = '';
	    foreach ($params as $key => $value) {
	        if ($key != 'sign' && $value != '') {
	            $string .= "{$key}={$value}&";
	        }
	    }

	    $string .= "key=" . $skey;
	    return strtoupper(md5($string));
	}

将数组转为xml:$this->ToXml();

    //数组转xml
	public function ToXml($array){
        if(!is_array($array)|| count($array) <= 0){
            return ;
        }
        $xml = '<xml version="1.0">';
        foreach ($array as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

发起请求:$this->curlHttpRequest();

    //发起请求
	public function curlHttpRequest($url,$xml){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL, $url);
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		} else {
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
		}
		//设置header
		curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		//传输文件
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

		$result = curl_exec($ch);  
        curl_close($ch);  
		//返回结果
		return $result;
	}

返回成功,将xml数据转换为数组;$this->FromXml();

    //xml格式转换为数组
	public function FromXml($xml){	
		if(!$xml){
			throw new WxPayException("xml数据异常!");
		}
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
		return $this->values;
	}

最后在微信App支付回调进行交易验签

    // 微信支付回调
	public function notify(){
		$xmlData = file_get_contents('php://input');
        //将xml格式转换为数组
        $data =  $this->FromXml($xmlData);
        $WX_MCHKEY = ''; //微信商户v2支付秘钥

        //为了交易安全需进行验证签名。
        $sign = $data['sign'];
        unset($data['sign']);
        //校验签名
        if($sign == $this->getSign($data,$WX_MCHKEY)){
        	//交易成功
            if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
                //根据返回的订单号做业务逻辑


            	//向微信返回交易成功
                exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
            }else{
                
            }
        }

	}

三、uniapp客户端发起支付

首先uniapp勾选微信支付权限

uniapp创建微信支付

                //orderinfo 服务端返回的订单信息
				uni.requestPayment({
				    "provider": "wxpay", 
				    "orderInfo": {
			        "appid": orderinfo.appid, 
			        "noncestr": orderinfo.noncestr, // 随机字符串
			        "package": "Sign=WXPay",        // 固定值
			        "partnerid": orderinfo.partnerid,     
			        "prepayid": orderinfo.prepayid, 
			        "timestamp": orderinfo.timestamp,  // 时间戳(单位:秒)
			        "sign": orderinfo.sign // 签名
				    },
				    success(res) {
						//console.log('success:' + JSON.stringify(res));
						//支付成功,为了确保支付安全在,请确定服务端支付回调notify验证是否交易成功

				    	//处理其他业务

					},
				    fail(err) {

				    }
				})

以上就是全部教程了。

//微信充值 //支付接口测试 function balance(url, data) { uni.request({ url: cfg.originUrl + '/wx/mp/js_sig.do', data: { route: url }, method: 'GET', success: (res) => { jweixin.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来 appId: res.data.appId, // 必填,公众号的唯一标识 timestamp: res.data.timestamp, // 必填,生成签名的时间戳 nonceStr: res.data.nonceStr, // 必填,生成签名的随机串 signature: res.data.signature, // 必填,签名 jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表 }); jweixin.ready(function() { uni.request({ url: cfg.originUrl + '/wx/recharge/pay.do', method: 'POST', header: { 'Content-type': "application/x-www-form-urlencoded", }, data: JSON.stringify(data), success: function(res) { alert("下单成功"); alert(JSON.stringify(res)); alert(res.data.order_id); all.globalData.orderId = res.data.order_id; uni.setStorageSync('orderId', res.data.order_id); jweixin.chooseWXPay({ timestamp: res.data.payParams.timeStamp, // 支付签名时间戳 nonceStr: res.data.payParams.nonceStr, // 支付签名随机串 package: res.data.payParams.package, // 接口返回的prepay_id参数 signType: res.data.payParams.signType, // 签名方式 paySign: res.data.payParams.paySign, // 支付签名 success: function(e) { alert("支付成功"); alert(JSON.stringify(e)); // 支付成功后的回调函数 } }); } }) }); jweixin.error(function(res) { // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 console.log("验证失败!") }); } }) }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜雨-阑珊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值