uni-app h5 calls WeChat payment method

uni-app h5 calls WeChat payment method

First of all, there are many forms of WeChat payment. If you need to, you can check https://pay.weixin.qq.com/wiki/doc/api/index.html . The payment form of JSAPI is mainly used here.
If you want the official account or h5 page to directly invoke the WeChat payment window to realize the payment form, you must first use the WeChat browser or WeChat environment to directly invoke it. That is, if our link is https, the following is the whole process of my payment:
ideas:
1. First, we need to obtain the openid. How to obtain the openid, we can obtain the openid by obtaining the code from the url, and then return it to the background processing.
2. After obtaining the openid, click the payment to call your own payment interface callback and then call the WeChat payment API (generally, in the development environment, we click the button and jump to the order page (such as http:localhost:8080/order/inder) , but if you want to call WeChat payment during development, the page you must jump to is https, that is, the address after deployment (https://www.xxx.com/orser/index)), so that you can pay
3. Successfully call up the WeChat payment window and then pay – the payment is successful.
The code is as follows:

car.vue page

<button @click="gopay">去购买<button>

goPay() {
				var local = 'https://www.xxx.com/order/index';   //你自己的需要跳转到的页面
				var APPID = 'xxxxxxxxx';
				window.location.href =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
					APPID +
					'&redirect_uri=' +
					encodeURIComponent(local) +
					'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
			}

order.vue page

onload(){  
//先获取code 来获取openid (其实有的可以不用回去openid 看你的支付方式 JSAPI是需要openid的),如果不是uni-app,可写在初始化方法里面按自己需求来
var code = this.getCode(); //先获取code 判断一下code不为空才能获取openid
			if (this.code != null && this.code != "" ) {
			  this.onBridgeReady(this.code); //把code传给后台获取用户信息
			 }
 }

**先获取code (我是从url上截取的)**
     getCode() {
		    var context = '';
		    var name = 'code';
	    	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		   var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
		   if (r != null) context = r[2];
	             	return context;
	       },
	
** 根据返回的code 来获取openid**
	   onBridgeReady(code) {
		    var _this = this;
		    let token
		    getAppToken(code)    //自己后台写的接口
			     .then(res => {
			       	if ('999999' == res.code) {
				     	alert(res.errMsg);
					    return;
				  } else {
					if (res.data != null) {
						uni.setStorageSync('openId', res.data);
						uni.setStorageSync('NoPush', false)
						token = res.data;
					} else {
						token = uni.getStorageSync('openId');
					}
					**this.prepay(this, token);  //去支付**
				}
			})
			.then(res => {
				var code = res.code;
				alert('openid', '失败')
				if ('999999' == res.code) {
					alert(res.errMsg);
				}
			});
	},

**去支付 调用自己的接口 获取相应参数**	
        prepay(_this, openid) {
		//var _this = this;
		let form = {
			amount: _this.totalPrice * 100,    //金额
			distId: _this.addressList.id,
			tradeType: 'JSAPI',
			items: _this.list,     //这里的参数是后面调微信支付api需要入的参数信息 如签名,随机字符串,appid等
			openid: openid
		};
		_this.addressList.id;
		prepay(form).then(payRes => {  //自己的接口
			if ('999999' == payRes.code) {
				alert(payRes.errMsg);
				return;
			} else {
				**_this.wxPayInvoke(_this, payRes, openid);**
			}
		});
	},
	
 ** 调起微信支付API**
	  wxPayInvoke(self, payRes, openid) {
	        	var url = window.location.href;
		        let that = this
		      //获取js签名
		        getSignature({
			          address: url
		         }).then(res => {
			       wx.config({
				       debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				      appId: payRes.data.appid, // 必填,公众号的唯一标识
				      timestamp: payRes.data.timestamp, // 必填,生成签名的时间戳
				      nonceStr: payRes.data.nonceStr, // 必填,生成签名的随机串
				     signature: payRes.data.signature, // 必填,签名
				     jsApiList: ['chooseWXPay'], // 必填,需要使用的JS接口列表
				    openId: openid
		    	});
			    //发起微信支付
			      wx.ready(function() {
				      wx.chooseWXPay({
				          	appId: payRes.data.appid,
					        timestamp: payRes.data.timestamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					        nonceStr: payRes.data.noncestr, // 支付签名随机串,不长于 32
					        package: 'prepay_id=' + payRes.data.prepayid, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
					        signType: 'HMAC-SHA256', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
					        paySign: payRes.data.sign, // 支付签名
					     success: function(res) {
					           	uni.showToast({
						       	icon: 'none',
						    	title: '支付成功'
					    	})
						   setTimeout(() => {
						      window.history.go(-1) //跳转到上一页
						   }, 1000)

				    	},
					 cancel: function(res) {
						//提示引用的是mint-UI里toast
						
						setTimeout(() => {
							uni.showToast({
								icon: 'none',
								title: '已取消支付'
							})
							
						}, 2000)
						 window.history.go(-1) //跳转到上一页
					},
					fail: function(res) {						
					 window.history.go(-1) //跳转到上一页
						setTimeout(() => {
							uni.showToast({
								icon: 'none',
								title: '支付失败,请重试'
							})
						}, 2000)
					}
				});
			});
		});
	}

renderings
insert image description here

Guess you like

Origin blog.csdn.net/weixin_41262185/article/details/109384456