{"id":13602339,"url":"https://github.com/JasonBoy/wechat-jssdk","last_synced_at":"2025-04-11T08:32:19.234Z","repository":{"id":6077596,"uuid":"54695265","full_name":"JasonBoy/wechat-jssdk","owner":"JasonBoy","description":"🐧微信JSSDK与NodeJS及Web端集成 WeChat JSSDK integration with NodeJS \u0026 Web","archived":false,"fork":false,"pushed_at":"2023-12-08T14:01:55.000Z","size":4325,"stargazers_count":724,"open_issues_count":23,"forks_count":93,"subscribers_count":26,"default_branch":"master","last_synced_at":"2024-11-05T05:02:42.396Z","etag":null,"topics":["nodejs","oauth","wechat","wechat-jssdk","wechat-mini-program","wechat-oauth","weixin","weixin-jssdk"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JasonBoy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2016-03-25T04:49:47.000Z","updated_at":"2024-11-04T08:44:44.000Z","dependencies_parsed_at":"2023-12-08T15:23:19.545Z","dependency_job_id":"27b42045-a26c-4ba6-96c0-b70043b94ac9","html_url":"https://github.com/JasonBoy/wechat-jssdk","commit_stats":{"total_commits":337,"total_committers":6,"mean_commits":"56.166666666666664","dds":"0.035608308605341255","last_synced_commit":"331c8722a89732e22e7910207c8092d332202ca1"},"previous_names":[],"tags_count":61,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JasonBoy%2Fwechat-jssdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JasonBoy%2Fwechat-jssdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JasonBoy%2Fwechat-jssdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JasonBoy%2Fwechat-jssdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JasonBoy","download_url":"https://codeload.github.com/JasonBoy/wechat-jssdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223464655,"owners_count":17149587,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nodejs","oauth","wechat","wechat-jssdk","wechat-mini-program","wechat-oauth","weixin","weixin-jssdk"],"created_at":"2024-08-01T18:01:20.513Z","updated_at":"2024-11-07T05:31:17.307Z","avatar_url":"https://github.com/JasonBoy.png","language":"JavaScript","readme":"# wechat-jssdk\n[![npm](https://img.shields.io/npm/v/wechat-jssdk.svg?style=flat-square)](https://www.npmjs.com/package/wechat-jssdk)\n[![node](https://img.shields.io/node/v/wechat-jssdk.svg?style=flat-square)](https://nodejs.org/)\n[![Coverage Status](https://img.shields.io/coveralls/github/JasonBoy/wechat-jssdk.svg?style=flat-square)](https://coveralls.io/github/JasonBoy/wechat-jssdk)\n[![npm](https://img.shields.io/npm/l/wechat-jssdk.svg?style=flat-square)](https://www.npmjs.com/package/wechat-jssdk)\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)\n\n微信JSSDK与NodeJS及Web端整合\nWeChat JS-SDK integration with NodeJS and Web.\n\n[English](https://github.com/JasonBoy/wechat-jssdk/blob/master/README_EN.md)\n| [Release Notes](https://github.com/JasonBoy/wechat-jssdk/releases)\n\n![wechat-jssdk-demo](https://raw.githubusercontent.com/JasonBoy/wechat-jssdk/master/demo/wechat-jssdk-demo-new.gif)\n\n## 主要功能\n\n- [:heartbeat:服务端](#使用方法)\n- [:heartpulse:浏览器端](#浏览器端)\n- [:unlock:OAuth网页授权](#oauth)\n- [:fries:微信卡券](#微信卡券)\n- [:credit_card:微信支付](#微信支付)\n- [:baby_chick:微信小程序](#小程序)\n- [:cd:使用Stores](#使用Stores)\n- [:movie_camera:完整 Demo](#demo)\n\n## 使用方法\n```bash\nnpm install wechat-jssdk --save\n# 或者\nyarn add wechat-jssdk\n```\n\n```javascript\nconst {Wechat} = require('wechat-jssdk');\nconst wx = new Wechat(wechatConfig);\n```\n### Wechat 配置项\n\n`wechatConfig` 为以下格式:\n```javascript\n{\n  //第一个为设置网页授权回调地址\n  wechatRedirectUrl: \"http://yourdomain.com/wechat/oauth-callback\", \n  wechatToken: \"xxx\", //第一次在微信控制台保存开发者配置信息时使用\n  appId: \"xxx\",\n  appSecret: \"xxx\",\n  card: true, //开启卡券支持，默认关闭\n  payment: true, //开启支付支持，默认关闭\n  merchantId: '', //商户ID\n  paymentSandBox: true, //沙箱模式，验收用例\n  paymentKey: '', //必传，验签密钥，TIP:获取沙箱密钥也需要真实的密钥，所以即使在沙箱模式下，真实验签密钥也需要传入。\n  //pfx 证书\n  paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),\n  //默认微信支付通知地址\n  paymentNotifyUrl: `http://your.domain.com/api/wechat/payment/`,\n  //小程序配置\n  \"miniProgram\": {\n    \"appId\": \"mp_appid\",\n    \"appSecret\": \"mp_app_secret\",\n  }\n}\n```\n\n其他支持的设置都有默认值，基本都是微信API的地址，且基本不会改变, 可以查看 `./lib/config.js`.\n\n## 设置微信环境\n1.去\u003ca href=\"https://mp.weixin.qq.com\" target=\"_blank\"\u003e微信公众平台\u003c/a\u003e\n\n下载类似 `MP_verify_XHZon7GAGRdcAFxx.txt` 这样的文件放到网站根目录, 如`http://yourdomain.com/MP_verify_XHZon7GAGRdcAFxx.txt`，微信会验证这个链接.\n\n2.然后在你的express/koa app中提供一个接口给浏览器获取验证信息, @see [demo](#demo)\n\n  ```javascript\n  //express app:\n  router.get('/get-signature', (req, res) =\u003e {\n    wx.jssdk.getSignature(req.query.url).then(signatureData =\u003e {\n      res.json(signatureData);\n    });\n  });\n  //koa2/koa-router app:\n  router.get('/get-signature', async ctx =\u003e {\n    ctx.body = await wx.jssdk.getSignature(ctx.request.query.url);\n  });\n  ```\n3.获取签名后，进入下一步浏览器端使用方法.\n\n## 浏览器端\n```javascript\nconst WechatJSSDK = require('wechat-jssdk/dist/client.umd');\n//ES6 import\nimport WechatJSSDK from 'wechat-jssdk/dist/client.umd';\n\n//没有打包的话直接script扔到html，然后从`window`获取, e.g:\nconst wechatObj = new window.WechatJSSDK(config)\n```\n\n`config`应该为:\n\n```javascript\nconst config = {\n  //前4个是微信验证签名必须的参数，第2-4个参数为类似上面 '/get-signature' 从node端获取的结果\n  'appId': 'xxx',\n  'nonceStr': 'xxx',\n  'signature': 'xxx',\n  'timestamp': 'xxx',\n  //下面为可选参数\n  'debug': true, //开启 debug 模式\n  'jsApiList': [], //设置所有想要使用的微信jsapi列表, 默认值为 ['updateAppMessageShareData','updateTimelineShareData','onMenuShareTimeline', 'onMenuShareAppMessage']，分享到朋友圈及聊天记录\n  'customUrl': '' //自定义微信js链接\n}\nconst wechatObj = new WechatJSSDK(config);\nwechatObj.initialize()\n  .then(w =\u003e {\n    //set up your share info, \"w\" is the same instance as \"wechatObj\"\n  })\n  .catch(err =\u003e {\n    console.error(err);\n  });\n```\n验证签名成功后, 就可以自定义你的分享内容了:\n\u003e sdk默认只注册了`updateAppMessageShareData`，`updateTimelineShareData`，`onMenuShareTimeline(wx即将废弃)`，`onMenuShareAppMessage(wx即将废弃)`\n```javascript\n//自定义分享到聊天窗口\n//内部调用 `wechatObj.callWechatApi('updateAppMessageShareData', {...})`， 语法糖而已\nwechatObj.updateAppMessageShareData({\n  type: 'link',\n  title: 'title',\n  link: location.href,\n  imgUrl: '/logo.png',\n  desc: 'description',\n  success: function (){},\n  fail: function (){},\n  complete: function (){},\n  cancel: function (){}\n});\n//自定义分享到朋友圈\n//语法糖\nwechatObj.updateTimelineShareData({\n  type: 'link',\n  title: 'title',\n  link: location.href,\n  imgUrl: '/logo.png'\n});\n```\n要获取原始的微信对象 `wx`，可以通过`wechatObj.getOriginalWx()`来获取。  \n如果第一次验证失败，可以在`error`回调里更新签名信息，并重新发验证请求：   \n`wechatObj.signSignature(newSignatureConfig);`, `newSignatureConfig`只需包含：\n```\n{\n  'nonceStr': 'xxx',\n  'signature': 'xxx',\n  'timestamp': 'xxx',\n}\n```\n\n调用其他微信接口：  \n`wechatObj.callWechatApi(apiName, apiConfig)`  \n`apiName`和`apiConfig`请参考微信官方接口文档\n\n## OAuth\n默认生成微信授权URL为 `wx.oauth.snsUserInfoUrl` 和 `wx.oauth.snsUserBaseUrl`，其中的默认回调URL为 `wechatConfig` 中配置的 `wechatRedirectUrl`.\n你也可以通过调用 `wx.oauth. generateOAuthUrl(customUrl, scope, state)`来自定义回调地址\n```javascript\n//callback url handler\n//如\"wechatRedirectUrl\"配置为 \"http://127.0.0.1/wechat/oauth-callback\", 你的路由需要为：\nrouter.get('/wechat/oauth-callback', function (req, res) {\n  //得到code，获取用户信息\n  wx.oauth.getUserInfo(req.query.code)\n          .then(function(userProfile) {\n            console.log(userProfile)\n            res.render(\"demo\", {\n              wechatInfo: userProfile\n            });\n          });\n});\n```\nTIP: 确保上面的重定向地址域名已经在微信里的授权回调地址设置里设置过。\n![](https://cloud.githubusercontent.com/assets/2911620/23061999/f95da3d4-f53e-11e6-9022-29ea33adb126.png)\n\n## 微信卡券\n\n在wechatConfig设置 `card: true` 来支持卡券功能的服务端支持, 参考[demo](#demo).  \n要查看卡券 APIs, 参考 [cards apis](https://github.com/JasonBoy/wechat-jssdk/wiki/API#card-apis)\n\n## 微信支付\n\n在wechatConfig设置 `payment: true` 来支持微信支付功能的服务端支持, 其他一些支付必须的配置也需要一同设置.  \n参考 [demo](#demo).  \n要查看支付 APIs, 参考 [payment apis](https://github.com/JasonBoy/wechat-jssdk/wiki/API#payment-apis)\n\n## 小程序\n\n使用小程序的服务端支持([看接口](https://github.com/JasonBoy/wechat-jssdk/wiki/API#mini-programv4)), 在配置里设置小程序的`appId` 和 `appSecret`:\n```javascript\nconst { Wechat, MiniProgram } = require('wechat-jssdk');\nconst wechatConfig = {\n  \"appId\": \"appid\",\n  \"appSecret\": \"app_secret\",\n  //...other configs\n  //...\n  //小程序配置\n  \"miniProgram\": {\n    \"appId\": \"mp_appid\",\n    \"appSecret\": \"mp_app_secret\",\n  }\n};\nconst wx = new Wechat(wechatConfig);\n//调用小程序接口\nwx.miniProgram.getSession('code');\n\n//手动实例化 MiniProgram\nconst miniProgram = new MiniProgram({\n  miniProgram: {\n    \"appId\": \"mp_appid\",\n    \"appSecret\": \"mp_app_secret\",\n  }\n})\n```\n\n## 使用Stores\nStore用来自定义存储token持久化(如文件，数据库等待)，实现自己的Store, 请查看[API](https://github.com/JasonBoy/wechat-jssdk/wiki/Store)  \n自带 Store: `FileStore`, `MongoStore`，默认为`FileStore`, 存储到`wechat-info.json`文件.\n\n## APIs\n查看 [API wiki](https://github.com/JasonBoy/wechat-jssdk/wiki/API)\n\n## Demo\n\n在v3.1.0后，demo页面增加卡券和支付的用例测试，\nCopy `demo/wechat-config-sample.js` 到 `demo/wechat-config.js`,  \n然后在里面里面修改 `appId`, `appSecret`, 及其他的[配置](#wechat-config) 如支付的其他配置如果需要使用支付功能的话.\n\n在`./demo/index.js`中设置你自己的`appId`, `appSecret`， 然后 `npm start` 或 `npm run dev`, 使用微信开发者工具测试。\n\n## Buy me a coffee\n如果您觉得这个项目对您有用，可以请我喝杯咖啡\n![reward-me](https://raw.githubusercontent.com/JasonBoy/wechat-jssdk/master/assets/jason-wx-reward-code.png)\n\n## LICENSE\n\nMIT @ 2016-present [jason](http://blog.lovemily.me)\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJasonBoy%2Fwechat-jssdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FJasonBoy%2Fwechat-jssdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJasonBoy%2Fwechat-jssdk/lists"}