From c65cacdea3ef9f863bfd09e0b89b999204037282 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=82=B9=E6=99=AF=E7=AB=8B?= <zoujingli@qq.com>
Date: Wed, 14 Apr 2021 11:55:40 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BE=AE=E4=BF=A1=E8=81=94?=
 =?UTF-8?q?=E5=90=88=E7=99=BB=E5=BD=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 app/data/controller/api/Wechat.php    |  9 +++++++--
 app/data/controller/api/Wxapp.php     | 18 ++++++++++--------
 app/data/service/UserAdminService.php | 18 ++++++++++++++++++
 3 files changed, 35 insertions(+), 10 deletions(-)

diff --git a/app/data/controller/api/Wechat.php b/app/data/controller/api/Wechat.php
index 35269cf2c..3c535ecd3 100644
--- a/app/data/controller/api/Wechat.php
+++ b/app/data/controller/api/Wechat.php
@@ -65,8 +65,12 @@ class Wechat extends Controller
     /**
      * 加载网页授权数据
      * @return \think\Response
+     * @throws \WeChat\Exceptions\InvalidResponseException
+     * @throws \WeChat\Exceptions\LocalCacheException
      * @throws \think\admin\Exception
+     * @throws \think\db\exception\DataNotFoundException
      * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
      */
     public function oauth(): Response
     {
@@ -77,10 +81,11 @@ class Wechat extends Controller
             $script[] = 'alert("Wechat WebOauth failed.")';
         } else {
             $data = $result['fansinfo'] ?? [];
-            $data['openid2'] = $data['openid'];
+            $data[$this->field] = $data['openid'];
             $data['base_sex'] = ['未知', '男', '女'][$data['sex']] ?? '未知';
+            if (isset($result['unionid'])) $data['unionid'] = $result['unionid'];
             if (isset($data['headimgurl'])) $data['headimg'] = $data['headimgurl'];
-            $map = isset($data['unionid']) ? ['unionid' => $data['unionid']] : [$this->field => $result['openid']];
+            $map = UserAdminService::instance()->getUserUniMap($this->field, $data[$this->field], $data['unionid'] ?? '');
             $result['userinfo'] = UserAdminService::instance()->set($map, array_merge($map, $data), $this->type, true);
             $script[] = "window.WeChatOpenid='{$result['openid']}'";
             $script[] = 'window.WeChatFansInfo=' . json_encode($result['fansinfo'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
diff --git a/app/data/controller/api/Wxapp.php b/app/data/controller/api/Wxapp.php
index 91e53b9cf..4d32f634a 100644
--- a/app/data/controller/api/Wxapp.php
+++ b/app/data/controller/api/Wxapp.php
@@ -62,10 +62,11 @@ class Wxapp extends Controller
      */
     public function session()
     {
-        $input = $this->_vali(['code.require' => '登录凭证code不能为空!']);
-        [$openid, $unionid, $sessionKey] = $this->_getSessionKey($input['code']);
-        $map = empty($unionid) ? [$this->field => $openid] : ['unionid' => $unionid];
-        $data = array_merge($map, [$this->field => $openid, 'session_key' => $sessionKey]);
+        $input = $this->_vali(['code.require' => '登录凭证CODE不能为空!']);
+        [$openid, $unionid, $session] = $this->_getSessionKey($input['code']);
+        $map = UserAdminService::instance()->getUserUniMap($this->field, $openid, $unionid);
+        $data = [$this->field => $openid, 'session_key' => $session];
+        if (!empty($unionid)) $data['unionid'] = $unionid;
         $this->success('授权换取成功!', UserAdminService::instance()->set($map, $data, $this->type, true));
     }
 
@@ -84,10 +85,11 @@ class Wxapp extends Controller
             [$openid, $unionid, $input['session_key']] = $this->_getSessionKey($input['code']);
             $result = Crypt::instance($this->config)->decode($input['iv'], $input['session_key'], $input['encrypted']);
             if (is_array($result) && isset($result['avatarUrl']) && isset($result['nickName'])) {
-                $sex = ['未知', '男', '女'][$result['gender']] ?? '未知';
-                $map = empty($result['unionId']) ? [$this->field => $openid] : ['unionid' => $unionid];
-                $data = [$this->field => $openid, 'headimg' => $result['avatarUrl'], 'nickname' => $result['nickName'], 'base_sex' => $sex];
-                $this->success('数据解密成功!', UserAdminService::instance()->set($map, array_merge($map, $data), $this->type, true));
+                $data = [$this->field => $openid, 'nickname' => $result['nickName'], 'headimg' => $result['avatarUrl']];
+                $data['base_sex'] = ['-', '男', '女'][$result['gender']] ?? '-';
+                if (!empty($unionid)) $data['unionid'] = $unionid;
+                $map = UserAdminService::instance()->getUserUniMap($this->field, $openid, $unionid);
+                $this->success('数据解密成功!', UserAdminService::instance()->set($map, $data, $this->type, true));
             } elseif (is_array($result)) {
                 $this->success('数据解密成功!', $result);
             } else {
diff --git a/app/data/service/UserAdminService.php b/app/data/service/UserAdminService.php
index c83805ddd..82cc3c709 100644
--- a/app/data/service/UserAdminService.php
+++ b/app/data/service/UserAdminService.php
@@ -110,6 +110,24 @@ class UserAdminService extends Service
         return ['my_invite' => $query->where(['pid1' => $uuid])->count()];
     }
 
+    /**
+     * 获取用户查询条件
+     * @param string $field 认证字段
+     * @param string $openid 用户OPENID值
+     * @param string $unionid 用户UNIONID值
+     * @return array
+     */
+    public function getUserUniMap(string $field, string $openid, string $unionid = ''): array
+    {
+        if (!empty($unionid)) {
+            [$map1, $map2] = [[['unionid', 'eq', $unionid]], [[$field, 'eq', $openid]]];
+            if ($uid = $this->app->db->name('DataUser')->whereOr([$map1, $map2])->value('id')) {
+                return ['id' => $uid];
+            }
+        }
+        return [$field => $openid];
+    }
+
     /**
      * 列表绑定用户数据
      * @param array $list 原数据列表