How to connect H5 website or uni-app packaged H5 to WeChat official account for payment

How to connect H5 website or uni-app packaged H5 to WeChat official account for payment

http://www.linfengya.cn/?post=39

Here I take an H5 website packaged by uniapp as an example (ordinary H5 websites are still common, and it is ok if it is better than a gourd)

There is no encapsulated payment interface in the documentation on the uniapp official website, so even if H5 is written in uniapp, you still have to follow the normal H5 access public account payment process.

Prerequisite preparation:

① Make sure the WeChat official account has applied for WeChat payment

②Appid of WeChat official account

③The secret of the WeChat official account (generally, the front end does not need to use this, but the backend needs to use this)

④ Configure a secure domain name for the official account

Process: ①Get the code through authorization

② Use the parameter openid to get the parameters required for payment through code.

③Inject permission verification configuration through wx.config interface

​ ④ If the pre-order signature verification passes, proceed to step 5 (there will be many errors in this step, such as missing parameters, wrong signature, illegal calls, etc.)

⑤Use WeixinJSBridge.invoke to activate payment via H5 in WeChat and it will be ok.

Let’s start pasting the code:

First use npm to install WeChat's jsApi (you should be able to do this, just like vue uses npm to install dependencies)

初始化:
npm init -y
安装微信模块:
npm install jweixin-module --save



H5的话 要引入js
 <script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>

Then use WeChat authorization (because I am logging in and registering with an account and do not need to obtain the user’s WeChat information, so I use silent authorization). By the way, let’s learn about the two authorizations of WeChat (my Google): There are two types of official account authorization One method is silent authorization. The user is unaware, but the user's basic information cannot be obtained. If you want to obtain user information, you need to use another authorization method. Since this method involves privacy, the user's consent is required. Just fine.

The way to obtain it is

https://open.weixin.qq.com/connect/oauth2/authorize?appid=KaTeX parse error: Expected 'EOF', got '&' at position 8: {appid}&̲redirect_uri={uri}&response_type=code&scope=${scope}&state=123#wechat_redirect

  //登录成功后跳转的首页域名  有些文章中写的这个地址需要进行encodeURIComponent()加密   我这里没有进行加密
var uri = 'http://www.linfeng******.com/index.html';  
//公众号的appid
var appid = 'wx2aec******62811f';

window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid +'&redirect_uri='+uri+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect');

By following the link, you can parse the URL after jumping to the homepage and get the code.

Calling this method on the homepage will return a string. If there is a value, the value is code.

function urlGetCode(){
    var indexUrl = location.search.substr(1);//截取到当前的地址
    var items = indexUrl.split('&');
    var item;
    var code;
    for (let a = 0; a < items.length; a++) {
        item = items[a].split("=");
        if (item[0] == 'code') {
            code = item[1];
            return code;
        }
    }
}

After we get the code, we need to call the interface and use the code in exchange for an openid.

获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

Parameter Description

parameter Is it necessary illustrate
appid yes The unique identifier of the official account
secret yes The appsecret of the official account
code yes Fill in the code parameters obtained in the first step
grant_type yes Fill in authorization_code

The front end can call this interface, but it will be cross-domain, so this interface is usually encapsulated by the backend. You only need to pass the code to the backend and let the backend return an openid to you, and then store the openid in the cache, because the preset You need to use this openid before placing an order and paying.

For details, please see the WeChat development documentation: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1

Then we go to the order payment page and call the payment interface. After that, the background will return you some pre-order parameters, such as

{
	"appId": "wx2*********62811f",
	"nonceStr": "b0c2e4491a8a5f06a1f4c0d81cd3c40c",
	"orderNo": 122816*********7682,
	"package": "prepay_id=wx14120839*********6f960fd1318413600",
	"sign": "F581AD6144487*********4B1CBC0AB3",
	"signType": "MD5",
	"timeStamp": 1581653318,
	"totalFee": 190
}

Then we get these parameters and verify the configuration by injecting permissions through the config interface.

wx.config({
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '', // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的JS接口列表
});

For details, see WeChat development documentation: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#4

If debug is true, a pop-up window will be alerted. If the pop-up window content is {"errMsg": "config:ok"}, it means that the verification is passed.

Next, you can activate payment in H5 within WeChat.

WeixinJSBridge.invoke(
    'getBrandWCPayRequest', {
    appId: appId, //公众号名称,由商户传入
    timeStamp: timestamp, //时间戳,自1970年以来的秒数
    nonceStr: nonceStr, //随机串
    package: data.package,
    signType: 'MD5', //微信签名方式:
    paySign: sign //微信签名
},
    function (res) {
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示:
            //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
            callback(res)
        } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            errorCallback(res)
        }
    }
)

For details, please see WeChat payment documentation: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7

At this step, if the parameters and signature verification pass, it is complete. If the signature is wrong, you can use the signature verification tool.

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=20_1

Complete code

The last complete code needs to be used in more than one place because of business requirements. For example, payment is also used when an order is pending payment, and it is also used in the order details. Therefore, it is recommended that you encapsulate the payment, which can reduce a lot of code. quantity

1. First use npm to install WeChat’s jsApi (you should be able to do this, just like vue uses npm to install dependencies)

初始化:
npm init -y
安装微信模块:
npm install jweixin-module --save



H5的话 要引入js
 <script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>

2. Create a new wxApi.js file under common of uniapp

wxApi.js

/*
    微信(公众号)支付方法
*/
const wx = require('jweixin-module');
const wexinPay = (data, callback, errorCallback) => {
	let [appId, timestamp, nonceStr, signature, packages, sign] = [data.appId, data.timeStamp, data.nonceStr, data.sign,
		data.package, data.sign
	];
	
	wx.config({
		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
		appId, // 必填,公众号的唯一标识
		timestamp, // 必填,生成签名的时间戳
		nonceStr, // 必填,生成签名的随机串
		signature, // 必填,签名,见附录1
		jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
	});
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
			appId: appId, //公众号名称,由商户传入
			timeStamp: timestamp, //时间戳,自1970年以来的秒数
			nonceStr: nonceStr, //随机串
			package: data.package,
			signType: 'MD5', //微信签名方式:
			paySign: sign //微信签名
		},
		function(res) {
			if (res.err_msg == 'get_brand_wcpay_request:ok') {
				// 使用以上方式判断前端返回,微信团队郑重提示:
				//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
				//支付成功回调
				callback(res)
			} else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
				//支付失败回调
				errorCallback(res)
			}
		}
	)
}

export default {
	wexinPay
}

3. Import and mount it in main.js (must use conditional compilation, otherwise it will report 'jweixin' of undefined when packaging the APP or running it on the mobile phone base, causing a white screen on the mobile phone)

// #ifdef H5
//导入 //(一定要用条件编译,否则在打包APP或在手机基座运行时会报 ‘jweixin’ of undefined,造成手机白屏)
import wxApi from './common/wxApi.js'
//挂载
Vue.prototype.$wxPay = wxApi.wexinPay
// #endif

4. Call payment pay.vue on the page

this.$wxPay(payInfo, function (res) {
    /*成功的回调*/
    console.log("支付成功")
}, function (e) {
    /**失败的回调*/
     console.log("支付失败或取消支付")
})


//该方法的第一个参数payInfo为调用后台支付返回的预下单参数
//打印payInfo
//{
//	"appId": "wx2*********62811f",
//	"nonceStr": "b0c2e4491a8a5f06a1f4c0d81cd3c40c",
//	"orderNo": 122816*********7682,
//	"package": "prepay_id=wx14120839*********6f960fd1318413600",
//	"sign": "F581AD6144487*********4B1CBC0AB3",
//	"signType": "MD5",
//	"timeStamp": 1581653318,
//	"totalFee": 190
//}
//第二个参数是成功回调  第三个参数是失败回调

Reprinted from: Xiao Fengfeng is not crazy

Original address: "How to connect H5 packaged by H5 website or uni-app to WeChat official account for payment" Published on 2020-2-14

Guess you like

Origin blog.csdn.net/m0_52459016/article/details/122088889