Next-Generation WeChat JS-SDK integration with NodeJS.
The next major version(v4) will drop node v4 support(may still work, but won't test against v4)
- 💓Server-Side
- 💗Browser-Side
- 🔓OAuth
- 🍟Cards and Offers(v3.1+)
- 💳Wechat Payment(v3.1+)
- 💿Using Stores
- 🎥Full Featured Demo
npm install wechat-jssdk --save
or
yarn add wechat-jssdk
const Wechat = require('wechat-jssdk');
const wx = new Wechat(wechatConfig);
wechatConfig
info:
{
//set your oauth redirect url, defaults to localhost
"wechatRedirectUrl": "http://yourdomain.com/wechat/oauth-callback",
//"wechatToken": "wechat_token", //not necessary required
"appId": "appid",
"appSecret": "app_secret",
card: true, //enable cards
payment: true, //enable payment support
merchantId: '', //
paymentSandBox: true, //dev env
paymentKey: '', //API key to gen payment sign
paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),
//default payment notify url
paymentNotifyUrl: `http://your.domain.com/api/wechat/payment/`,
}
1.Set your own URL in Wechat Website
Usually wechat will provide you a MP_verify_XHZon7GAGRdcAFxx.txt
like file to ask you to put that on your website root,
which will be accessed by wechat on http://yourdomain.com/MP_verify_XHZon7GAGRdcAFxx.txt
to verify that you own the domain.
2.You should also provide a api for your browser to get token for the current url, see demo
//express app for example:
router.get('/get-signature', async (req, res) => {
wx.jssdk.getSignature(req.query.url).then(signatureData => {
res.json(signatureData);
});
//use async/await
//const signatureData = await wx.jssdk.getSignature(req.query.url);
//res.json(signatureData);
});
3.Now you can get to the next step in your browser to pass the verification.
const WechatJSSDK = require('wechat-jssdk/dist/client');
//ES6 import
import WechatJSSDK from 'wechat-jssdk/dist/client';
//or import the original ES6 module from 'lib/client',
// in which case you may need to include this into your webpack babel-loader process
import WechatJSSDK from 'wechat-jssdk/lib/client';
const wechatObj = new WechatJSSDK(config)
// or if you do not have a bundle process, just add the script tag, and access "WechatJSSDK" from window, e.g:
const wechatObj = new window.WechatJSSDK(config)
where config will be:
const config = {
//below are mandatory options to finish the wechat signature verification
//the 4 options below should be received like api '/get-signature' above
'appId': 'app_id',
'nonceStr': 'your_nonceStr',
'signature': 'url_signature',
'timestamp': 'your_timestamp',
//below are optional
//invoked if wechat signature sign succeeds,
//'this' will be the jssdk instance if it's a normal function,
// in v3.0.10+, jssdk instance will be passed to the callback, (wxObj) => {}
// in the up coming v4, "success"/"error" init callback will be replace by #initialize() which will return Promise, see below
'success': jssdkInstance => {},
//invoked if sign failed, in v3.0.10+, jssdk instance will be pass to the func, (err, wxObj) => {}
'error': (err, jssdkInstance) => {},
//enable debug mode, same as debug
'debug': true,
'jsApiList': [], //optional, pass all the jsapi you want, the default will be ['onMenuShareTimeline', 'onMenuShareAppMessage']
'customUrl': '' //set custom weixin js script url, usually you don't need to add this js manually
}
const wechatObj = new WechatJSSDK(config);
//in the up coming v4, use "initialize" as Promise:
const wechatObj2 = new WechatJSSDK(config);
wechatObj2.initialize()
.then(w => {
//set up your share info just like in "success" function in config above
})
.catch(err => {
console.error(err);
});
after signature signed successfully, you can customize the share information:
//customize share on chat info
//sugar method for `wechatObj.callWechatApi('onMenuShareAppMessage', {...})`
wechatObj.shareOnChat({
type: 'link',
title: 'title',
link: location.href,
imgUrl: '/logo.png',
desc: 'description',
success: function (){},
cancel: function (){}
});
//customize share on timeline info
//sugar method
wechatObj.shareOnMoment({
type: 'link',
title: 'title',
link: location.href,
imgUrl: '/logo.png'
});
You can also access the original wechat object wx
from wechatObj.getOriginalWx()
.
Call other wechat apis: wechatObj.callWechatApi(apiName, config)
:
wechatObj.callWechatApi('onMenuShareAppMessage', {
type: 'link',
title: 'title',
link: location.href,
imgUrl: '/logo.png',
desc: 'description',
success: function (){},
cancel: function (){}
});
or with the original one:
wechatObj.getOriginalWx().onMenuShareAppMessage(config)
Wechat support web OAuth to get user profile in wechat app.
In your page, provide a link, which you can get by wx.oauth.snsUserInfoUrl
which is the default oauth url, to the wechat OAuth page,
also you need provide a callback url(as show below) to get the wechat code after user click Agree button, the callback url is configured in the wechatConfig
object above while initializing,
but you can customize your own callback url by using wx.oauth.generateOAuthUrl(customUrl, scope, state)
api.
//in node:
const wx = new Wechat(config);
const url = wx.oauth.generateOAuthUrl('http://mycustom.com/oauth-callback', 'snsapi_userinfo', 'custom_state');
res.render("oauth-page", {
wechatOAuthUrl: url,
});
//insert "wechatOAuthUrl" into your html:
//custom callback url, agree clicked by user, come back here:
router.get('/oauth-callback', function (req, res) {
wx.oauth.getUserInfo(req.query.code)
.then(function(userProfile) {
console.log(userProfile)
res.render("demo", {
wechatInfo: userProfile
});
});
});
Set card: true
in config to enable the cards support on server side, see demo.
For cards APIs, see cards apis
Set payment: true
in config to enable the payment support on server side, you should also provide payment related info.
See demo.
For payment APIs, see payment apis
New in V3
Store are used to save url signatures into files, dbs, etc..., but also keep a copy in memory for better performence.
The default store used is FileStore
which will persist tokens and signatures into wechat-info.json
file every 10 minutes, also it will load these info from the file in next initialization.
Built in Stores: FileStore
, MongoStore
,
...
const Wechat = require('wechat-jssdk');
const MongoStore = Wechat.MongoStore;
const FileStore = Wechat.FileStore;
const wx = new Wechat({
appId: 'xxx',
...,
//file store
//store: new FileStore(),
//======
//pass the MongoStore instance to config
//default 127.0.0.1:27017/wechat db, no need to pass anything to constructor
store: new MongoStore({
//dbName: 'myWechat', //default wechat
dbAddress: 'mongodb://127.0.0.1:27017/wechat', //set the whole connection uri by yourself
dbOptions: {}, //set mongoose connection config
})
})
You can also create own Store to store tokens anywhere you want, by doing that, you may need to extend the base Store
class, and reimplement the apis you need:
const Store = require('wechat-jssdk').Store;
class CustomStore extends Store {
constructor (options) {
super();
console.log('using my own store!');
}
}
see API wiki
Add DEBUG=wechat*
when start your app to enable wechat-jssdk debug
DEBUG=wechat* node your-app.js
In v3.1.0, the demo page is updated to test the new added Cards & Offers
and Payment
support.
Copy the demo/wechat-config-sample.js
to demo/wechat-config.js
,
and use your own appId
, appSecret
, and other configs like payment if your want to enable them.
Use npm start
or npm run dev
to start the demo.
MIT @ 2016-2018 jason