koa-weixin-jssdk
koa weixin jssdk middleware
Quick Start
import koa from ' koa ' ;
import weixinJSSDK from ' ../src ' ;
const port = process . env . PORT || 3000 ;
const app = koa ( ) ;
app . use ( weixinJSSDK ( {
appId : ' <YOUR_APP_ID> ' ,
secret : ' <YOUR_SECRET> ' ,
pathName : ' /jssdk ' ,
onError : ( err , ctx , next ) => {
console . error ( err ) ;
ctx . body = ' error ' ;
} ,
} ) ) ;
app . listen ( port ) ;
Advanced Usage
Custom store access_token
and ticket
By default, it would cache access_token
and ticket
in runtime memory, but you can store them in somewhere else.
app . use ( weixinJSSDK ( {
appId : ' <YOUR_APP_ID> ' ,
secret : ' <YOUR_SECRET> ' ,
async onGetToken ( url ) {
return redis . getAsync ( ' ACCESS_TOKEN ' ) ;
} ,
async onSetToken ( token , expiresIn ) {
return redis . setSync ( ' ACCESS_TOKEN ' , token , { expiresIn } ) ;
} ,
async onGetTicket ( url ) {
return redis . getAsync ( ' TICKET ' ) ;
} ,
async onSetTicket ( ticket , expiresIn ) {
return redis . setSync ( ' TICKET ' , ticket , { expiresIn } ) ;
} ,
} ) ) ;
Third-party weixin service
Maybe you already have a Third-party weixin service and have a access token, you could use custom fetchTicket
or fetchToken
function instead of secret
.
app . use ( weixinJSSDK ( {
appId : ' <YOUR_APP_ID> ' ,
async fetchToken ( ) {
return { access_token : ' <MY_ACCESS_TOKEN> ' , expires_in : 7200 } ;
} ,
} ) ) ;
Or fetchTicket
app . use ( weixinJSSDK ( {
appId : ' <YOUR_APP_ID> ' ,
async fetchTicket ( ) {
return { ticket : ' TICKET ' , expires_in : 7200 } ;
} ,
} ) ) ;
Installation
Using npm :
$ npm install koa-weixin-jssdk --save
License
MIT