{"id":13602725,"url":"https://github.com/node-webot/wechat-oauth","last_synced_at":"2025-05-15T17:04:25.611Z","repository":{"id":23750243,"uuid":"27124361","full_name":"node-webot/wechat-oauth","owner":"node-webot","description":"Wechat OAuth","archived":false,"fork":false,"pushed_at":"2022-02-11T09:18:21.000Z","size":242,"stargazers_count":801,"open_issues_count":10,"forks_count":137,"subscribers_count":53,"default_branch":"master","last_synced_at":"2025-05-08T15:43:55.864Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/node-webot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"MIT-License","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-11-25T12:19:18.000Z","updated_at":"2025-04-14T17:47:35.000Z","dependencies_parsed_at":"2022-09-05T18:01:37.443Z","dependency_job_id":null,"html_url":"https://github.com/node-webot/wechat-oauth","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-webot%2Fwechat-oauth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-webot%2Fwechat-oauth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-webot%2Fwechat-oauth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-webot%2Fwechat-oauth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/node-webot","download_url":"https://codeload.github.com/node-webot/wechat-oauth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254384987,"owners_count":22062422,"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":[],"created_at":"2024-08-01T18:01:35.647Z","updated_at":"2025-05-15T17:04:25.588Z","avatar_url":"https://github.com/node-webot.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"wechat-oauth\n===============\n\n微信公共平台OAuth接口消息接口服务中间件与API SDK\n\n## 模块状态\n\n- [![NPM version](https://badge.fury.io/js/wechat-oauth.png)](http://badge.fury.io/js/wechat-oauth)\n- [![Build Status](https://travis-ci.org/node-webot/wechat-oauth.png?branch=master)](https://travis-ci.org/node-webot/wechat-oauth)\n- [![Dependencies Status](https://david-dm.org/node-webot/wechat-oauth.png)](https://david-dm.org/node-webot/wechat-oauth)\n- [![Coverage Status](https://coveralls.io/repos/node-webot/wechat-oauth/badge.png)](https://coveralls.io/r/node-webot/wechat-oauth)\n\n## 功能列表\n- OAuth授权\n- 获取基本信息\n\nOAuth2.0网页授权，使用此接口须通过微信认证，如果用户在微信中（Web微信除外）访问公众号的第三方网页，公众号开发者可以通过此接口获取当前用户基本信息（包括昵称、性别、城市、国家）。详见：[官方文档](http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息)\n\n详细参见[API文档](http://doxmate.cool/node-webot/wechat-oauth/api.html)\n\n## Installation\n\n```sh\n$ npm install wechat-oauth\n```\n\n## Usage\n\n### 初始化\n引入OAuth并实例化\n\n```js\nvar OAuth = require('wechat-oauth');\nvar client = new OAuth('your appid', 'your secret');\n```\n\n以上即可满足单进程使用。\n当多进程时，token需要全局维护，以下为保存token的接口。\n\n```js\nvar oauthApi = new OAuth('appid', 'secret', function (openid, callback) {\n  // 传入一个根据openid获取对应的全局token的方法\n  // 在getUser时会通过该方法来获取token\n  fs.readFile(openid +':access_token.txt', 'utf8', function (err, txt) {\n    if (err) {return callback(err);}\n    callback(null, JSON.parse(txt));\n  });\n}, function (openid, token, callback) {\n  // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等\n  // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例\n  // 持久化时请注意，每个openid都对应一个唯一的token!\n  fs.writeFile(openid + ':access_token.txt', JSON.stringify(token), callback);\n});\n```\n\n附上全局维护AccessToken的示例代码：\n\nMongodb|mongoose\n\n``` js\nvar TokenSchema = new Schema({\n  access_token: String,\n  expires_in: Number,\n  refresh_token: String,\n  openid: String,\n  scope: String,\n  create_at: String\n});\n```\n\n自定义getToken方法\n\n```js\nTokenSchema.statics.getToken = function (openid, cb) {\n  this.findOne({openid:openid}, function (err, result) {\n    if (err) throw err;\n    return cb(null, result);\n  });\n};\n```\n\n自定义saveToken方法\n\n```js\nTokenSchema.statics.setToken = function (openid, token, cb) {\n  // 有则更新，无则添加\n  var query = {openid: openid};\n  var options = {upsert: true};\n  this.update(query, token, options, function (err, result) {\n    if (err) throw err;\n    return cb(null);\n  });\n};\n\nmongoose.model('Token', 'TokenSchema');\n```\n\n初始化：\n\n```js\nvar client = new OAuth(appid, secret, function (openid, callback) {\n  // 传入一个根据openid获取对应的全局token的方法\n  // 在getUser时会通过该方法来获取token\n  Token.getToken(openid, callback);\n}, function (openid, token, callback) {\n  // 持久化时请注意，每个openid都对应一个唯一的token!\n  Token.setToken(openid, token, callback);\n});\n```\n\nMySQL:\n\n建表SQL\n\n```sql\nCREATE TABLE `token` (\n  `access_token` varchar(200) COLLATE utf8_bin NOT NULL COMMENT '令牌',\n  `expires_in` varchar(10) COLLATE utf8_bin NOT NULL COMMENT '有效期',\n  `refresh_token` varchar(200) COLLATE utf8_bin NOT NULL COMMENT '刷新参数',\n  `openid` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '用户编号',\n  `scope` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '作用域',\n  `create_at` varchar(20) COLLATE utf8_bin NOT NULL COMMENT '令牌建立时间'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='微信令牌表';\n```\n\n设置openid为唯一索引\n\n```sql\nALTER TABLE `token`\n  ADD UNIQUE KEY `openid` (`openid`);\n```\n\n使用示例：\n\n```js\nvar client = new Oauth(appid, secret, function (openid, callback) {\n  var sql = 'SELECT * FROM token WHERE openid = ?';\n  db.query(sql, [openid], function (err, result) {\n    if(err) {\n      return callback(err);\n    }\n    return callback(null, result[0]);\n  });\n}, function (openid, token, callback) {\n  var sql = 'REPLACE INTO token(access_token, expires_in, refresh_token, openid, scope, create_at) VALUES(?, ?, ?, ?, ?, ?)';\n  var fields = [token.access_token, token.expires_in, token.refresh_token, token.openid, token.scope, token.create_at];\n  db.query(sql, fields, function (err, result) {\n    return callback(err);\n  });\n});\n```\n\n### 小程序初始化\n使用小程序时，需要在初始化OAuth时指定`isMiniProgram`参数为`true`\n\n单进程\n\n```js\nvar OAuth = require('wechat-oauth');\nvar client = new OAuth('your appid', 'your secret', null, null, true); // 最后一个参数即isMiniProgram\n```\n\n多进程\n\n```js\nvar oauthApi = new OAuth('appid', 'secret', getToken, saveToken, true);\n```\n\n注意：微信不会将用户的sessionKey过期时间告知开发者，该时间会根据用户与小程序互动频繁程度等因素发生变化，建议根据小程序客户端`wx.checkSession()`方法检验凭证是否依旧有效，若失效应该再次使用code换取新的sessionKey。故而此例中的`getToken`和`saveToken`方法过期机制须有不同。\n[官方文档](https://developers.weixin.qq.com/miniprogram/dev/api/signature.html)\n\n### 引导用户\n生成引导用户点击的URL。\n\n```js\nvar url = client.getAuthorizeURL('redirectUrl', 'state', 'scope');\n```\n\n如果是PC上的网页，请使用以下方式生成\n```js\nvar url = client.getAuthorizeURLForWebsite('redirectUrl');\n```\n\n### 获取Openid和AccessToken\n用户点击上步生成的URL后会被重定向到上步设置的 `redirectUrl`，并且会带有`code`参数，我们可以使用这个`code`换取`access_token`和用户的`openid`\n\n```js\nclient.getAccessToken('code', function (err, result) {\n  var accessToken = result.data.access_token;\n  var openid = result.data.openid;\n});\n```\n\n### 获取用户信息\n如果我们生成引导用户点击的URL中`scope`参数值为`snsapi_userinfo`，接下来我们就可以使用`openid`换取用户详细信息（必须在getAccessToken方法执行完成之后）\n\n```js\nclient.getUser(openid, function (err, result) {\n  var userInfo = result;\n});\n```\n\n## 捐赠\n如果您觉得Wechat OAuth对您有帮助，欢迎请作者一杯咖啡\n\n![捐赠wechat](https://cloud.githubusercontent.com/assets/327019/2941591/2b9e5e58-d9a7-11e3-9e80-c25aba0a48a1.png)\n\n## 交流群\nQQ群：157964097，使用疑问，开发，贡献代码请加群。\n\n## Contributors\n感谢以下贡献者：\n\n```\n$ git summary\n\n project  : wechat-oauth\n repo age : 2 years, 2 months\n active   : 13 days\n commits  : 29\n files    : 11\n authors  :\n    24  Jackson Tian  82.8%\n     1  Kainy Guo     3.4%\n     1  Teng Fei      3.4%\n     1  cherry-geqi   3.4%\n     1  welch         3.4%\n     1  wzw           3.4%\n\n```\n\n## License\nThe MIT license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-webot%2Fwechat-oauth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnode-webot%2Fwechat-oauth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-webot%2Fwechat-oauth/lists"}