Bläddra i källkod

小程序登录

lrf402788946 4 år sedan
förälder
incheckning
93a3977659
4 ändrade filer med 44 tillägg och 2 borttagningar
  1. 9 0
      app/controller/weixin.js
  2. 7 1
      app/service/user.js
  3. 22 0
      app/service/weixin.js
  4. 6 1
      config/config.prod.js

+ 9 - 0
app/controller/weixin.js

@@ -199,6 +199,15 @@ class WeixinController extends Controller {
       this.ctx.redirect(to_uri);
     }
   }
+
+  // GET 签到小程序请求用户
+  async appAuth() {
+    const { js_code, login = true } = this.ctx.query;
+    const appopenid = await this.ctx.service.weixin.appAuth(js_code);
+    if (!login) this.ctx.ok(appopenid);
+    const res = await this.findByAppOpenid(appopenid);
+    this.ctx.ok(res);
+  }
 }
 
 module.exports = WeixinController;

+ 7 - 1
app/service/user.js

@@ -78,7 +78,7 @@ class UserService extends CrudService {
 
   // 学生绑定
   async bind(data) {
-    const { openid, id_number, mobile,  unionid } = data;
+    const { openid, id_number, mobile, unionid } = data;
     assert(openid && id_number && mobile, '缺少部分信息项');
     let user = await this.model.findOne({ mobile });
     if (user) {
@@ -136,6 +136,12 @@ class UserService extends CrudService {
     const user = await this.model.findOne({ openid });
     return user;
   }
+  // 通过openid查询用户信息
+  async findByAppOpenid(appopenid) {
+    // 通过openid查询用户信息
+    const user = await this.model.findOne({ appopenid });
+    return user;
+  }
 
   // 通过unionid查询用户信息
   async findByunionid(unionid) {

+ 22 - 0
app/service/weixin.js

@@ -277,5 +277,27 @@ class WeixinAuthService extends AxiosService {
     });
   }
 
+  // 小程序登录
+  async appAuth(js_code) {
+    const { wxapp } = this.app.config;
+    if (!wxapp) return;
+    let url = 'https://api.weixin.qq.com/sns/jscode2session';
+    let query = `?js_code=${js_code}`;
+    const keys = Object.keys(wxapp);
+    for (const key of keys) {
+      query = `${query}&${key}=${wxapp[key]}`;
+    }
+    url = `${url}${query}`;
+    const res = await this.ctx.curl(url, {
+      method: 'get',
+      headers: {
+        'content-type': 'application/json',
+      },
+    });
+    const { openid } = res.data;
+    if (!openid) throw new BusinessError(ErrorCode.BUSINESS, '未获取到openid', '未获取到openid');
+    return openid;
+  }
+
 }
 module.exports = WeixinAuthService;

+ 6 - 1
config/config.prod.js

@@ -17,7 +17,12 @@ module.exports = () => {
     payurl: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
     sendDirMq: 'http://www.jilinjobswx.cn/api.weixin.qq.com/cgi-bin/message/template/send?appid=',
   };
-
+  // 签到小程序
+  config.wxapp = {
+    appid: 'wx3b5ac763ada73e0e',
+    secret: '0f30fcbb9ad45697800611ad4af585bb',
+    grant_type: 'authorization_code',
+  };
   // 服务器发布路径
   config.baseUrl = 'http://jytz.jilinjobs.cn';
   // 认证回调地址