uni-app h5调用微信支付方法

uni-app h5调用微信支付方法

首先微信支付的形式要好多种如需可查看https://pay.weixin.qq.com/wiki/doc/api/index.html,这里主要用的是JSAPI的支付形式。
想要公众号、h5页面直接调起微信支付窗口实现支付形式,首先必须是微信浏览器或微信环境下才可以直接调起。也就是我们的链接要是https的,下面是我支付的整个流程:
思路:
1.首先我们要先获取openid,如何获取openid,可通过从url中获取code,再返回给后台处理来获取openid
2.获取openid后,点击支付调用自己的支付接口回调后调起微信支付API(一般我们在开发环境下都是点击按钮后跳转到订单页面之类的(如http:localhost:8080/order/inder),但是如果想要开发时调用微信支付必须跳转的页面为https的也就是说是部署后的地址(https://www.xxx.com/orser/index)),这样才可以去支付
3.成功调起微信支付窗口然后支付–支付成功
代码如下:

car.vue页面

<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 页面

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)
					}
				});
			});
		});
	}

效果图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41262185/article/details/109384456