For H5 phone side classmates WeChat is a indispensable entrance, naturally we need to call WeChat provides various interfaces of H5 or JS, so we should according to the requirement of the WeChat to do all sorts of signature verification, can reach our demand, finally making the library also has a lot on this above can be used, However, they are always more or less unable to fully meet the needs, or they need to pay a lot of extra development. Therefore, I also developed a library, weike-JSSDK, to maximally meet the functions of wechat JSSDK. This library only focuses on the functions provided by JSSDK, and provides various server-side (NodeJS) verification support. And automatic management of various token, ticket expiration processing, so that developers can pay more attention to the business itself. Ok, having said WHY, here is HOW:
Main Function set
- π server
- π browser side
- πOAuth web page authorization
- π wechat card coupons
- π³ wechat Pay
- πΏ use Stores
- Complete Demo π₯
Method of use
NPM install Witch-jssdk –save or yarn add Witch-jssdk
//require and initialize
const Wechat = require('wechat-jssdk');
const wx = new Wechat(wechatConfig);
Copy the code
Wechat Config
WechatConfig is in the following format:
{
// The first is to set the page authorization callback address
wechatRedirectUrl: "http://yourdomain.com/wechat/oauth-callback".wechatToken: "xxx".// Optional, used when saving developer configuration information on wechat console for the first time
appId: "xxx".appSecret: "xxx".card: true.// Enable card coupon support, disabled by default
payment: true.// Enable payment support, disabled by default
merchantId: ' './ / merchant ID
paymentSandBox: true.// In sandbox mode, check the use case
paymentKey: ' '.// Required, check key, TIP: Obtaining the sandbox key also requires the real key, so even in sandbox mode, the real check key needs to be passed in.
/ / PFX certificate
paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),
// Default wechat pay notification address
paymentNotifyUrl: `http://your.domain.com/api/wechat/payment/`,}Copy the code
Set up wechat environment
1. Now generally directly give a mp_verify_xxx. TXT file in the root directory of your website, let wechat automatically to verify
2. You also need to provide an API for the browser to get the signature of the current address
/ / express style
router.get('/get-signature'.function(req, res) {
wx.jssdk.getSignature(req.query.url).then(function(signatureDate) {
res.json(signatureDate);
});
});
Copy the code
3. After obtaining the signature, go to the next step.
The browser
In the front end js:
//ES6
import WechatJSSDK from 'wechat-jssdk/dist/client';
//commonjs
const WechatJSSDK = require('wechat-jssdk/dist/client'); Const wechatObj = new WechatJSSDK(config); // Others window.WechatJSSDKCopy the code
Config should be:
const config = {
// The first four parameters are required to verify the signature of wechat, and the second to fourth parameters are similar to the above '/get-signature' obtained from the node
'appId': 'xxx'.'nonceStr': 'xxx'.'signature': 'xxx'.'timestamp': 'xxx'.// The following parameters are optional
'success': function(wechatObj){}, // wechat signature successCallback function, same as 'successCallback'
'error': function(err, wechatObj){}, // Wechat signature failed callback function, same as 'errorCallback'
'debug': true.// Enable the debug mode
'jsApiList': [].// Set the list of all desired wechat Jsapi. The default value is ['onMenuShareTimeline', 'onMenuShareAppMessage'], and share to moments and chat history
'customUrl': ' ' // Customize wechat JS links
}
Copy the code
After verifying the signature successfully, you can customize your share content:
// Customize sharing to chat window
// internally call 'wechatobj. callWechatApi' ('onMenuShareAppMessage', {... }) ', grammar sugar only
wechatObj.shareOnChat({
type: 'link'.title: 'title'.link: location.href,
imgUrl: '/logo.png'.desc: 'description'.success: function (){},
cancel: function (){}});// Custom share to moments
/ / syntactic sugar
wechatObj.shareOnMoment({
type: 'link'.title: 'title'.link: location.href,
imgUrl: '/logo.png'
});
Copy the code
To get the original wechat object wx, wechatobj.getoriginalWx (). If the first authentication fails, you can update the signature information in the error callback and re-send the authentication request wechatobj. signSignature(newSignatureConfig). NewSignatureConfig only needs to contain:
{
'nonceStr': 'xxx'.'signature': 'xxx'.'timestamp': 'xxx',}Copy the code
Call other wechat interfaces: wechatObj. CallWechatApi (apiName, apiConfig) Please refer to the official wechat interface documentation for apiName and apiConfig
OAuth
The default generated wechat authorization urls are wx.oauth.snsUserInfoUrl and wx.oauth.snsUserBaseUrl. The default callback urls are wechatRedirectUrl configured in wechatConfig. You can also by calling the wx. Request. GenerateOAuthUrl (customUrl, scope, state) from defining callback address
//callback url handler
/ / such as "wechatRedirectUrl configured for" http://127.0.0.1/wechat/oauth-callback ", "your routing need to:
router.get('/wechat/oauth-callback'.function (req, res) {
// get the code to get the user information
wx.oauth.getUserInfo(req.query.code)
.then(function(userProfile) {
console.log(userProfile)
res.render("demo", {
wechatInfo: userProfile
});
});
});
Copy the code
TIP: Make sure that the above redirection address domain name has been set in the authorization callback address Settings in wechat.
WeChat card vouchers
Set card: True in wechatConfig to support server support for card function, see demo. To see the card APIs, refer to the cards APIs
WeChat pay
Set payment: True on wechatConfig to support wechat payment on the server, as well as other payment requirements. Refer to demo. To see the payment APIs, refer to the Payment APIs
The use of Stores
MongoStore: FileStore, MongoStore, default FileStore, Store in a singletoken file, singletoken, singletoken, singletoken, singletoken.
APIs
See the API wiki
Demo
Project: Git clone [email protected]: JasonBoy/wechat – JSSDK. Copy git demo/wechat – config – sample. Js to demo/wechat – config. Js. And then inside that you can modify the appId, appSecret, and all the other things that you can do with payment if you want to use payment. Then NPM start or NPM run dev, use wechat developer tools to test.
conclusion
Well, the general method of use as above, basically meet the most functional requirements of JSSDK, interested can go to Github to try.