npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wechat-jssdk

v5.1.0

Published

WeChat JS-SDK integration with NodeJS and Web

Downloads

1,208

Readme

wechat-jssdk

npm node Coverage Status npm code style: prettier

微信JSSDK与NodeJS及Web端整合 WeChat JS-SDK integration with NodeJS and Web.

English | Release Notes

wechat-jssdk-demo

主要功能

使用方法

npm install wechat-jssdk --save
# 或者
yarn add wechat-jssdk
const {Wechat} = require('wechat-jssdk');
const wx = new Wechat(wechatConfig);

Wechat 配置项

wechatConfig 为以下格式:

{
  //第一个为设置网页授权回调地址
  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",
  }
}

其他支持的设置都有默认值,基本都是微信API的地址,且基本不会改变, 可以查看 ./lib/config.js.

设置微信环境

1.去微信公众平台

下载类似 MP_verify_XHZon7GAGRdcAFxx.txt 这样的文件放到网站根目录, 如http://yourdomain.com/MP_verify_XHZon7GAGRdcAFxx.txt,微信会验证这个链接.

2.然后在你的express/koa app中提供一个接口给浏览器获取验证信息, @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.获取签名后,进入下一步浏览器端使用方法.

浏览器端

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应该为:

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);
  });

验证签名成功后, 就可以自定义你的分享内容了:

sdk默认只注册了updateAppMessageShareDataupdateTimelineShareDataonMenuShareTimeline(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'
});

要获取原始的微信对象 wx,可以通过wechatObj.getOriginalWx()来获取。
如果第一次验证失败,可以在error回调里更新签名信息,并重新发验证请求:
wechatObj.signSignature(newSignatureConfig);, newSignatureConfig只需包含:

{
  'nonceStr': 'xxx',
  'signature': 'xxx',
  'timestamp': 'xxx',
}

调用其他微信接口:
wechatObj.callWechatApi(apiName, apiConfig)
apiNameapiConfig请参考微信官方接口文档

OAuth

默认生成微信授权URL为 wx.oauth.snsUserInfoUrlwx.oauth.snsUserBaseUrl,其中的默认回调URL为 wechatConfig 中配置的 wechatRedirectUrl. 你也可以通过调用 wx.oauth. generateOAuthUrl(customUrl, scope, state)来自定义回调地址

//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: 确保上面的重定向地址域名已经在微信里的授权回调地址设置里设置过。

微信卡券

在wechatConfig设置 card: true 来支持卡券功能的服务端支持, 参考demo.
要查看卡券 APIs, 参考 cards apis

微信支付

在wechatConfig设置 payment: true 来支持微信支付功能的服务端支持, 其他一些支付必须的配置也需要一同设置.
参考 demo.
要查看支付 APIs, 参考 payment apis

小程序

使用小程序的服务端支持(看接口), 在配置里设置小程序的appIdappSecret:

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",
  }
})

使用Stores

Store用来自定义存储token持久化(如文件,数据库等待),实现自己的Store, 请查看API
自带 Store: FileStore, MongoStore,默认为FileStore, 存储到wechat-info.json文件.

APIs

查看 API wiki

Demo

在v3.1.0后,demo页面增加卡券和支付的用例测试, Copy demo/wechat-config-sample.jsdemo/wechat-config.js,
然后在里面里面修改 appId, appSecret, 及其他的配置 如支付的其他配置如果需要使用支付功能的话.

./demo/index.js中设置你自己的appId, appSecret, 然后 npm startnpm run dev, 使用微信开发者工具测试。

Buy me a coffee

如果您觉得这个项目对您有用,可以请我喝杯咖啡 reward-me

LICENSE

MIT @ 2016-present jason