The cause of

Recently the development of wechat, encountered all kinds of problems, look at the document to see many times still half-understand, so I try to encapsulate the wechat API, so share, there are problems to submit Issues oh.

The project address

anger-wechat

Anger – wechat 😒 🐷

Directory

  • Global method

    • isWechat Determine whether it is a wechat environment
    • getGlobalAccessToken Get access_token
  • Web is suitable for the development of webpage public number

    • getJsTicket Access to js api_ticket
    • getAuthUrl Get the Auth address
    • getAuthAccessTokenByCode Obtain openID according to code
    • getUserInfo Obtaining User information
    • getJsSdkConfig Get the JS SDK config configuration
  • Mini is suitable for small program development

    • getOpenidByCode Exchange openID and so on according to code
  • AngerPay applies to payments

    • Payment document

Getting started

npm install anger-wechat --save

Use

var AngerWechat = require('anger-wechat')
var weixinApi = new AngerWechat({
    appId: '[your appId]'./ / appId will pass
    appSecret: '[your appSecret]'./ / appSecret will pass
    authUrl: 'http://www.test.cc/get-weixin-code.html'
})
Copy the code

If you need to pay

var AngerWechat = require('anger-wechat')
var weixinApi = new AngerWechat({
    appId: '[your appId]'./ / appId will pass
    appSecret: '[your appSecret]'./ / appSecret will pass
    authUrl: 'http://www.test.cc/get-weixin-code.html'.// Optional wechat Auth2.0 authorization public page
    payment: { // Optional if payment module is required
        mchId: '123456'.partnerKey: '456789'.pfx: path.join(__dirname, 'apiclient_cert.p12'), // [Optional] Certificate path. Most interfaces cannot be dropped without certificate transmission
        notifyUrl: ' ' // [Optional] wechat pay received result '}})Copy the code

Global

getGlobalAccessToken

You are advised to save it in the database

Get access_token stamp I view the official documentation

The access_token is the global unique interface call credential of the public number. The public number needs to use the Access_token to invoke all interfaces. Developers need to keep it safe. The access_token must be stored with a minimum of 512 characters. The validity period of the Access_Token is two hours. The validity period of the access_token must be updated periodically. If the access_token is obtained repeatedly, the access_token obtained last time becomes invalid.

let access_token = await weixinApi.getGlobalAccessToken()
Copy the code
{ 
	"code": 200."msg": "Request successful"."data": { 
		"access_token": "11_oTBrYVsT9wqa_-q3WDNEBOtfz1XKdM7YKIcNBEiu29Wfh5yTnlqaj5W0hMuxZ7C9FlY7CxD0RjR35V1ik1M3Nyi5QENcgFKhh0gYoBnAXEQ2oV93sVtO 7IRqhh1kd9QLG8fwyA3vFRdifpJCOVLgAGAVCS"."expires_in": 7200}}Copy the code





isWechat

Determine whether it is a wechat environment

let ua = request.headers["user-agent"]
let isWeixin = weixinApi.isWechat(ua) / / incoming ` UserAgent ` strings, returning true | false
Copy the code





Web

[AngerWechat.Web]

getJsTicket

You are advised to save it in the database

Get js API_ticket stamp I view the official document

Api_ticket is a temporary ticket used to call wechat card coupon JS API, valid for 7200 seconds, obtained by access_token.

let jsTrickt = await weixinApi.Web.getJsTicket({
    access_token: '11_oTBrYVsT9wqa_-q3WDNEBOtfz1XKdM7YKIcNBEiu29Wfh5yTnlqaj5W0hMuxZ7C9FlY7CxD0RjR35V1ik1M3Nyi5QENcgFKhh0gYoBnAXEQ2oV93sVtO 7IRqhh1kd9QLG8fwyA3vFRdifpJCOVLgAGAVCS' // The access_token obtained in the previous step obtains js API_ticket
  })
Copy the code
{
	"code": 200."msg": "ok"."data": {
		"errcode": 0."errmsg": "ok"."ticket": "HoagFKDcsGMVCIY2vOjf9oKOmI5MRTBgKJJwCDQ2BnyLbfAJHCZXUIs992xQP246Nzp7LCNupv5Jablw8COZ_w"."expires_in": 7200}}Copy the code





getAuthUrl

Gets the Auth address, which is redirected to get the code

let authURl = weixinApi.Web.getAuthUrl({
	redirect_uri: 'http://www.baidu.com'.scope: 'snsapi_userinfo' Snsapi_base: silent authorization, snsapi_userinfo: prompt authorization (you can obtain user information later)
})
console.log(authURl)
// http://www.toolos.cc/get-weixin-code.html?appid=wxf638c1f64239e786&redirect_uri=http://www.baidu.com&scope=snsapi_userin fo&state=STATE
Copy the code





getAuthAccessTokenByCode

Obtain openID according to code

let codeInfo = await weixinApi.Web.getAuthAccessTokenByCode({
    code: '061729xv1BtSAa09g8yv1hr0xv1729xB'
})
Copy the code
{
	"code": 200."msg": "Request successful"."data": {
		"access_token": "11_Vc7D8AoYURWoECzJgD6Q1ccUOOHypO6mU0RQF7BnliKKCY5arfVvl0h3PWURwpK7QFgPLfDkHLX-9Dif6BTntw"."expires_in": 7200."refresh_token": "11_ii3uONcMPA-04RjuLlckMMiwaDGF2MjW2SB5vOI3Sshz39PAVn7kOyC80_pPmmRJxqbfJ3Rdw07WG154AeP83Q"."openid": "oI-Aa04T6FrpFFpTfyAaXR4SKacU"."scope": "snsapi_userinfo"}}Copy the code





getUserInfo

Get user information based on the access_token and openID obtained by getAuthAccessTokenByCode. Note that snsapi_userinfo is passed to the scope of getAuthUrl to get the url callback

let userInfo = await weixinApi.Web.getUserInfo({
	access_token: codeInfo.data.access_token,
	openid: codeInfo.data.openid
})
Copy the code
{
	"code": 200."msg": "Request successful"."data": {
		"openid": "oI-Aa04T6FrpFFpTfyAaXR4SKacU"."nickname": "A fish-eating sail."."sex": 1."language": "zh_CN"."city": "* *"."province": "* *"."country": "China"."headimgurl": "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIS3x9dFdptD1s2ZZMTDCriaiaXiaDPtyZw3vfMmJLyQ8PU8laBv4MNnJh5c9QWtTQey0m4FY UPVEvAQ/132"."privilege": []}}Copy the code





getJsSdkConfig

Obtain js SDK config to configure wechat JS interface signature verification tool

let jsTricktConfig = await weixinApi.Web.getJsSdkConfig({
	ticket: 'HoagFKDcsGMVCIY2vOjf9oKOmI5MRTBgKJJwCDQ2Bnx34ua3MVs9zUZpV0wQPe8h83AwFSZQREHGgmuKpqvdsg'.url: 'http://www.toolos.cc' // Call the js SDK page address
})
Copy the code
{
	"appId": "wxf638c1f64239e786"."signature": "2c18eb8d6adaa5e02a9df517e776f5eef40ed402"."noncestr": "04b21a6a-caea-4878-9fdb-8b2c1ff699b0"."timestamp": 1530636997."jsapi_ticket": "HoagFKDcsGMVCIY2vOjf9oKOmI5MRTBgKJJwCDQ2Bnx34ua3MVs9zUZpV0wQPe8h83AwFSZQREHGgmuKpqvdsg"
}
Copy the code





Mini

[AngerWechat.Mini]

getOpenidByCode

Obtain the openID and other information according to the code sent by the small program. Obtain the session_key and OpenID and other temporary login credentials according to the code.

let info = await weixinApi.Mini.getOpenidByCode({
    code: 'xxxxxxxxxxxxxx'
})
Copy the code
{
    "openid" : "oynY34-0Err_YssQIFsK-Ht1eGs"."session_key" : "sPxOFsssssCP54n6cCfshw=="
}
Copy the code





pay

Poke me to see the document address

The appendix

About the authUrl parameter

Reference GetWeixinCode

Check tools

  • Wechat JS interface signature verification tool
  • Wechat public platform interface debugging tool

Buy me a cup of coffee and support more open source