WeChat JSSDK integration with NodeJS and Web WeChat JS-SDK integration with NodeJS and Web.
English | Release Notes
npm install wechat-jssdk --save
# 或者
yarn add wechat-jssdk
const { Wechat } = require ( 'wechat-jssdk' ) ;
const wx = new Wechat ( wechatConfig ) ;
wechatConfig
is in the following format:
{
//第一个为设置网页授权回调地址
wechatRedirectUrl : "http://yourdomain.com/wechat/oauth-callback" ,
wechatToken : "xxx" , //第一次在微信控制台保存开发者配置信息时使用
appId : "xxx" ,
appSecret : "xxx" ,
card : true , //开启卡券支持,默认关闭
payment : true , //开启支付支持,默认关闭
merchantId : '' , //商户ID
paymentSandBox : true , //沙箱模式,验收用例
paymentKey : '' , //必传,验签密钥,TIP:获取沙箱密钥也需要真实的密钥,所以即使在沙箱模式下,真实验签密钥也需要传入。
//pfx 证书
paymentCertificatePfx : fs . readFileSync ( path . join ( process . cwd ( ) , 'cert/apiclient_cert.p12' ) ) ,
//默认微信支付通知地址
paymentNotifyUrl : `http://your.domain.com/api/wechat/payment/` ,
//小程序配置
"miniProgram" : {
"appId" : "mp_appid" ,
"appSecret" : "mp_app_secret" ,
}
}
Other supported settings have default values, which are basically the addresses of the WeChat API and will not change. You can check ./lib/config.js
.
1. Go to WeChat public platform
Download a file like MP_verify_XHZon7GAGRdcAFxx.txt
and put it in the root directory of the website, such as http://yourdomain.com/MP_verify_XHZon7GAGRdcAFxx.txt
. WeChat will verify the link.
2. Then provide an interface in your express/koa app for the browser to obtain verification information, @see demo
//express app:
router . get ( '/get-signature' , ( req , res ) => {
wx . jssdk . getSignature ( req . query . url ) . then ( signatureData => {
res . json ( signatureData ) ;
} ) ;
} ) ;
//koa2/koa-router app:
router . get ( '/get-signature' , async ctx => {
ctx . body = await wx . jssdk . getSignature ( ctx . request . query . url ) ;
} ) ;
3. After obtaining the signature, proceed to the next step of how to use the browser.
const WechatJSSDK = require ( 'wechat-jssdk/dist/client.umd' ) ;
//ES6 import
import WechatJSSDK from 'wechat-jssdk/dist/client.umd' ;
//没有打包的话直接script扔到html,然后从`window`获取, e.g:
const wechatObj = new window . WechatJSSDK ( config )
config
should be:
const config = {
//前4个是微信验证签名必须的参数,第2-4个参数为类似上面 '/get-signature' 从node端获取的结果
'appId' : 'xxx' ,
'nonceStr' : 'xxx' ,
'signature' : 'xxx' ,
'timestamp' : 'xxx' ,
//下面为可选参数
'debug' : true , //开启 debug 模式
'jsApiList' : [ ] , //设置所有想要使用的微信jsapi列表, 默认值为 ['updateAppMessageShareData','updateTimelineShareData','onMenuShareTimeline', 'onMenuShareAppMessage'],分享到朋友圈及聊天记录
'customUrl' : '' //自定义微信js链接
}
const wechatObj = new WechatJSSDK ( config ) ;
wechatObj . initialize ( )
. then ( w => {
//set up your share info, "w" is the same instance as "wechatObj"
} )
. catch ( err => {
console . error ( err ) ;
} ) ;
After successfully verifying the signature, you can customize your sharing content:
By default, sdk only registers
updateAppMessageShareData
,updateTimelineShareData
,onMenuShareTimeline(wx即将废弃)
,onMenuShareAppMessage(wx即将废弃)
//自定义分享到聊天窗口
//内部调用 `wechatObj.callWechatApi('updateAppMessageShareData', {...})`, 语法糖而已
wechatObj . updateAppMessageShareData ( {
type : 'link' ,
title : 'title' ,
link : location . href ,
imgUrl : '/logo.png' ,
desc : 'description' ,
success : function ( ) { } ,
fail : function ( ) { } ,
complete : function ( ) { } ,
cancel : function ( ) { }
} ) ;
//自定义分享到朋友圈
//语法糖
wechatObj . updateTimelineShareData ( {
type : 'link' ,
title : 'title' ,
link : location . href ,
imgUrl : '/logo.png'
} ) ;
To obtain the original WeChat object wx
, you can obtain it through wechatObj.getOriginalWx()
.
If the first verification fails, you can update the signature information in error
callback and resend the verification request:
wechatObj.signSignature(newSignatureConfig);
, newSignatureConfig
only needs to contain:
{
'nonceStr': 'xxx',
'signature': 'xxx',
'timestamp': 'xxx',
}
Call other WeChat interfaces:
wechatObj.callWechatApi(apiName, apiConfig)
apiName
and apiConfig
please refer to WeChat official interface documentation.
The default generated WeChat authorization URLs are wx.oauth.snsUserInfoUrl
and wx.oauth.snsUserBaseUrl
, and the default callback URL is wechatRedirectUrl
configured in wechatConfig
. You can also customize the callback by calling wx.oauth. generateOAuthUrl(customUrl, scope, state)
address
//callback url handler
//如"wechatRedirectUrl"配置为 "http://127.0.0.1/wechat/oauth-callback", 你的路由需要为:
router . get ( '/wechat/oauth-callback' , function ( req , res ) {
//得到code,获取用户信息
wx . oauth . getUserInfo ( req . query . code )
. then ( function ( userProfile ) {
console . log ( userProfile )
res . render ( "demo" , {
wechatInfo : userProfile
} ) ;
} ) ;
} ) ;
TIP: Make sure that the above redirect address domain name has been set in the authorized callback address settings in WeChat.
Set card: true
in wechatConfig to support server-side support for card and coupon functions, refer to demo.
To view card and coupon APIs, refer to cards apis
Set payment: true
in wechatConfig to support server-side support for WeChat payment function. Other necessary configurations for payment also need to be set together.
Reference demo.
To view payment APIs, refer to payment apis
Use the server-side support of the mini program (see the interface), and set appId
and appSecret
of the mini program in the configuration:
const { Wechat , MiniProgram } = require ( 'wechat-jssdk' ) ;
const wechatConfig = {
"appId" : "appid" ,
"appSecret" : "app_secret" ,
//...other configs
//...
//小程序配置
"miniProgram" : {
"appId" : "mp_appid" ,
"appSecret" : "mp_app_secret" ,
}
} ;
const wx = new Wechat ( wechatConfig ) ;
//调用小程序接口
wx . miniProgram . getSession ( 'code' ) ;
//手动实例化 MiniProgram
const miniProgram = new MiniProgram ( {
miniProgram : {
"appId" : "mp_appid" ,
"appSecret" : "mp_app_secret" ,
}
} )
Store is used to customize storage token persistence (such as files, databases, etc.) and implement your own Store. Please view the API.
Comes with Store: FileStore
, MongoStore
, the default is FileStore
, stored in the wechat-info.json
file.
View the API wiki
After v3.1.0, the demo page adds use case tests for coupons and payments, Copy demo/wechat-config-sample.js
to demo/wechat-config.js
,
Then modify appId
, appSecret
, and other configurations such as payment configurations if you need to use the payment function.
Set your own appId
and appSecret
in ./demo/index.js
, then npm start
or npm run dev
, and use WeChat developer tools to test.
If you find this project useful, buy me a coffee
MIT @ 2016-present jason