首先在nodejs裏的config下建立一個wechat.js文件,裏面配置好appid和appSecret。node
let config = exports; config.production = { appId: 'wxc464e493a4e946b6', appSecret: 'ab86e8264ed8c8a91df958a98a7928b4', // appId: 'wxe27bcb44cb1e4753', // appSecret: '920841d36776734b772f778cfa8c8b77', }; config.testing = Object.assign({}, config.production); config.development = Object.assign({}, config.production); config.qa = Object.assign({}, config.testing, {}); config.nc = Object.assign({}, config.production, {}); config.sjhl = Object.assign({}, config.production, {}); config.gm = Object.assign({}, config.production, {});
而後在libs下建立wechat.js文件,redis
裏面的代碼爲sql
var fs = require('fs'); var OAuth = require('wechat-oauth'); class Wechat { //拿到配置文件裏的appid和appSecret constructor(appId, appSecret) { this.appId = appId; this.appSecret = appSecret; this.client = new OAuth(this.appId, this.appSecret, this.getToken, this.setToken); } //從緩存中獲取用戶的assets token getToken(openid, callback) { let file = `runtime/access_token_${openid}.txt`; if (!fs.existsSync(file)) { return callback(null); } fs.readFile(file, 'utf8', function (err, txt) { if (err) { console.log('[wechat] get token err', err); return callback(err); } callback(null, JSON.parse(txt)); }); } //若是沒獲取到token就把token設置到緩存中 setToken(openid, token, callback) { let file = `runtime/access_token_${openid}.txt`; fs.writeFile(file, JSON.stringify(token), callback); } //傳入url讓用戶點擊受權 getAuthorizeURL(url) { let redirectUrl = this.client.getAuthorizeURL(url, 'qiongtao.li', 'snsapi_userinfo'); return redirectUrl; } //獲取用戶的accessToken async getAccessToken(code) { return new Promise((resolve, reject) => { this.client.getAccessToken(code, (err, rst) => { if (err) { console.log('[wechat] get access token err', err); resolve(); } console.log('[wechat] access token:', rst.data); resolve(rst.data); }) }) } //經過openid獲取到用戶信息 async getUser(openid) { return new Promise((resolve, reject) => { this.client.getUser(openid, (err, rst) => { if (err) { console.log('[wechat] get user info err', err); resolve(); } console.log('[wechat] userinfo:', rst); resolve(rst); }) }) } } module.exports = Wechat
最後在toutes裏寫action,代碼爲api
const Wechat = require('../../libs/Wechat'); const Trans = require('../../libs/database/Mysql'); const Model = require('../../libs/Model'); const RecordLog = require('../../libs/Log'); const Request = require('../../libs/Request'); const redis = require('../../libs/Redis'); const wechat = new Wechat(_.config.wechat.appId, _.config.wechat.appSecret); module.exports = { '/npi/wechat/login': { get: async (ctx, next) => { let echostr = ctx.query.echostr || ''; let code = ctx.query.code || ''; if (echostr != '') { //證實你是開發者 return echostr; } //受權認證 if (code == '') { let domain = ctx.protocol + '://' + ctx.host; // let url = wechat.getAuthorizeURL(domain + ctx.url); ctx.set('Referrer', ctx.headers['Referrer'] || `${domain}/npi/test/succ`) ctx.redirect('back', url); return ''; } //得到userInfo let rst = await wechat.getAccessToken(code); let userInfo = await wechat.getUser(rst.openid); console.log('111111111111111111111111111', userInfo); //開始判斷登陸或者註冊 let openid = userInfo.data.openid; let gender = ''; if (userInfo.data.sex == '1') { gender = 'MAN'; } else { gender = 'WOMEN'; } let row = await Model.tblGyUserSocial().where('openid', openid).where('status', 'ACTIVE').getOne(); //登陸 if (row.id) { let user = await Model.tblGyUserInfo().where('id', row.user_id).getOne(); let token = _.makeToken({ userId: user.id, userType: 'PERSON', }, ctx); let str = { userId: user.id, userType: 'PERSON', }; let JsStr = JSON.stringify(str); await redis.setex("gy:app:u:token:" + token, 7200, JsStr); return _.succ('登陸成功!', { token: token, }); } //註冊 let data = { businessId: 1, datacenterId: 1, serverId: 1, }; let uid = await new Request().getJSON(_.config.settings.getId, data); Trans.transBegin(); let res = await Model.tblGyUserInfo() .set('status', 'ACTIVE') .set('update_time', new Date()) .set('create_time', new Date()) .set('id', uid) .set('nick_name', row.data.nickname) .set('gender', gender) .set('icon', row.data.headimgurl) .insert(); if (res === false) { Trans.transRollback(); return _.err('失敗!', 711); } let res1 = await Model.tblGyUserSocial() .set('status', 'ACTIVE') .set('update_time', new Date()) .set('create_time', new Date()) .set('user_id', uid) .set('platform', uid) .set('openid', openid) .set('nick_name', row.data.nickname) .set('gender', gender) .set('province', row.data.province) .set('city', row.data.city) .set('country', row.data.country) .set('icon', row.data.headimgurl) .insert(); if (res1 === false) { Trans.transRollback(); return _.err('失敗!', 711); } let token = _.makeToken({ userId: uid, userType: 'PERSON', }, ctx); let str = { userId: uid, userType: 'PERSON', }; let JsStr = JSON.stringify(str); await redis.setex("gy:app:u:token:" + token, 7200, JsStr); ctx.status = 301; ctx.redirect(_.config.settings.wechatRedirectUrl + `?token=${token}`); // return _.succ(userInfo); } }, }