Skip to content
jason edited this page Jan 15, 2019 · 16 revisions

Welcome to the wechat-jssdk API wiki for NodeJS!

Initialize

//get your wechat info from wechat dashboard
const wechatInfo = {
  appId: "bbb", //required
  appSecret: "ccc", //required
  wechatRedirectUrl: "http://yourdomain.com/wechat/oauth-callback",
  wechatToken: "", // used to pass the verification when save wechat config on wechat dashboard
  card: true, //enable cards & offers node support
  //get your payment configs below from pay.weixin.qq.com
  payment: true, //enable payment node support
  merchantId: '',
  paymentSandBox: true, //dev env for payment
  paymentKey: '', //API key to generate payment signature
  paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),
  //default payment notify url
  paymentNotifyUrl: `http://your.domain.com/api/wechat/payment/`,
  miniProgram: {
    "appId": "mp_appid",
    "appSecret": "mp_app_secret",
  }
}
//composed/simplified one with all sub modules included
const {Wechat} = require('wechat-jssdk');
const wx = new Wechat(wechatInfo);

JSSDK APIs

Default Api usage: wx.jssdk.fun(params...).then(resolveFn, rejectFn), the wx.jssdk is a reference to new JSSDK(options) instance internally,
Instantiate your own JSSDK instance:

const {JSSDK} = require('wechat-jssdk');
const jssdk = new JSSDK(wechatInfo);
jssdk.fun(params...).then(resolveFn, rejectFn);
  • @constructor JSSDK, use new JSSDK(options) to instantiate JSSDK instance, which is automatically called when you do new WeChat(options) above.
  • verifySignature, [query {object}], JSON object containing all the verification properties, including: timestamp, nonce, to generate the signature to compare with query.signature, you need to call this api when you first input the wechat config in wechat dashboard.
  • getSignature, [url {string}, forceNewSignature {boolean}], get the signature from cache or create a new one, usually this is the most used api. If forceNewSignature is true, generate a new signature instead of getting it from cache.
  • jssdk.store, the Store instance for the current jssdk instance.

OAuth APIs

Default Api usage: wx.oauth.fun(params...).then(resolveFn, rejectFn), the wx.oauth is a reference to new OAuth(options) instance internally,
Instantiate your own OAuth instance:

const {OAuth} = require('wechat-jssdk');
const oauth = new OAuth(wechatInfo);
oauth.fun(params...).then(resolveFn, rejectFn);
  • @constructor OAuth, use new OAuth(options) to instantiate OAuth instance, which is automatically called when you do new WeChat(options) above.
  • generateOAuthUrl, [redirectUrl {string}, scope {string}, state {string}], customize your own callback url, pass your custom scope and state(default userAuth) option to original wechat api. The default wx.oauth.snsUserInfoUrl(scope: snsapi_userinfo) and wx.oauth.snsUserBaseUrl(scope: snsapi_base) is generated with the wechatRedirectUrl when you pass to new Wechat(options).
  • getUserInfo, [code {string}, key {string}, returnToken {boolean}], get wechat user info, including nickname, openid, avatar, etc..., if code is a false value('', null, etc...), it will get the access token from cache based on the key parameter, the key(default use the openid from the userinfo result) is used as a unique key for access token info to be stored in Stores, which can be retrieved next time directly from cache instead of getting the code again, if returnToken is true, the result of the token api will be merged with the user profile, and be returned together.
  • getUserBaseInfo, [code {string}, key {string}], get wechat user base info, code param is included in the wechat redirect url.
  • oauth.store, the Store instance for the current oauth instance.

Card APIs(v3.1+)

  • @constructor Card, use new Card(options) to instantiate Card instance, which is automatically called when you do new WeChat(options) above if card option is enabled.
  • static getter CODE_TYPE, qr code, bar code, text, e.g: wx.card.CODE_TYPE.CODE_TYPE_QRCODE.
  • static getter CARD_TYPE, groupon, cash, discount, etc...
  • getCardSignature, [shopId {string=}, cardType {string=}, cardId {string=}], generate card signature info for jssdk's chooseCard api.
  • getCardExt, [cardId {string}, code {string=}, openid {string=}, fixed_begintimestamp {string=}, outer_str {string=}], generate cardExt when addCard.
  • decryptCardCode, [encryptedCode {string}], decrypt the encrypted card code when choose card for later use.

Payment APIs(v3.1+)

  • @constructor Payment, use new Payment(options) to instantiate Payment instance, which is automatically called when you do new WeChat(options) above if payment option is enabled.
  • static getter DOWNLOAD_BILL_TYPE, e.g: wx.payment.DOWNLOAD_BILL_TYPE.SUCCESS.
  • static getter PAYMENT_TYPE, JSAPI, NATIVE, APP, MICROPAY.
  • static getter REFUND_STATUS, SUCCESS, REFUNDCLOSE, PROCESSING, CHANGE.
  • static getter FUND_ACCOUNT_TYPE, BASIC, OPERATION, FEES.
  • static getter SIGN_TYPE, MD5(default), HMAC_SHA256, some apis only support HMAC_SHA256.
  • static getter COUPON_TYPE, CASH, NO_CASH.
  • static func fenToYuan, [input {Number|string}] convert fen to RMB yuan, e.g: 1000(fen) -> 10(yuan)
  • static func yuanToFen, [input {Number|string}] convert RMB to fen, e.g: 10.123(yuan) -> 1012(fen), wechat api only support fen unit, without any decimal.
  • static func formatCurrency, [input {Number|string}], format RMB yuan to number with only 2 decimals(fen), e.g: RMB yuan, 10.123 => 10.12, 10 => 10.00, 10.456 => 10.46.
  • generateGeneralPaymentSignature, [params {object}, signType {string=}], General payment sign generator.
  • generateChooseWXPayInfo, [prepayId {string}], Generate paySign info for jssdk to invoke wechat payment chooseWXPay().
  • simpleTradeNo, Generate simple trade id: out_trade_no, e.g: '20180322171316ZFV883T353'.
  • unifiedOrder, [orderInfo {object}], custom orderInfo, create a unified order on wechat server, and get the prepay_id related info.
  • queryOrder, [queryInfo {object}], query order from wechat server by {out_trade_no: ''} or {transaction_id: ''}.
  • closeOrder, [outTradeNo {string}], close the order on wechat by out_trade_no.
  • refund, [refundInfo {object}], refund the order on wechat server.
  • queryRefund, [queryInfo {object}], query refund status from wechat.
  • downloadBill, [billDate {string}, billType {string=}, noGzip {boolean}]
  • downloadFundFlow, [billDate {string}, accountType[Payment.FUND_ACCOUNT_TYPE] {string=}, noGzip {boolean}], Download fund flow.

    download function will be resolved/reject with:

    {
      //an error object, rejected
      error: new Error(),
      //error msg, , rejected
      msg: '',
      //resolved with download stream,
      //can be piped to other writable stream, e.g: result.data.pipe(fs.createWritableStream('./bill.txt'))
      data: Stream,
      body: String, //response body text
      //sign info from response header
      digest: 'SHA=ec45d7c24492dcd62d92472b0f2816c8d9a2d773',
    }
    
  • parseNotifyData, [xmlData {string}], parse notify data from wechat.
  • getDownloadBillDate, [date {Date|string|Date_in_ms}], format a Date object to like 20180303.
  • decryptRefundNotifyResult, [xmlData {string}], decrypt wechat refund notify result.
  • queryComments, [beginTime {date_in yyyyMMddHHmmss}, endTime, offset {int=}, limit {int=}], batch query user comments.

⚠️WARN: Payment is really a complex process, pls make sure to test all cases from wechat in sandbox env set paymentSandBox: true.

Mini Program(v4+)

  • @constructor const {MiniProgram} = require('wechat-jssdk').
  • getSession, [code {string}, key {string=openid}], get mini program session_key with code.
  • decryptData, [encryptedData {string}, iv {string}, sessionKey {string}, Decrypt data from mini program, like the authed phone data after user permits the auth.
  • genSignature, [rawDataString {string}, sessionKey {string}], generate signature to compare with the one provided by wechat.
Clone this wiki locally