register($userInfo, $referee_id); // 生成token (session3rd) $this->token = $this->token($userInfo['openid']); // 记录缓存, 7天 Cache::set($this->token, $user_id, 86400 * 7); return $user_id; } /** * 获取token */ public function getToken() { return $this->token; } /** * 生成用户认证的token */ private function token($openid) { return md5($openid . 'token_salt'); } /** * 自动注册用户 */ private function register($userInfo, $referee_id = null) { $data = []; //通过unionid查询用户是否存在 $user = null; $data['union_id'] = ''; if(isset($userInfo['unionid']) && !empty($userInfo['unionid'])){ $data['union_id'] = $userInfo['unionid']; $user = self::detailByUnionid($userInfo['unionid']); } // 查询用户是否已存在 if(!$user){ $user = self::detail(['mpopen_id' => $userInfo['openid']]); } if($user){ $model = $user; // 只修改union_id $data = [ 'union_id' => $data['union_id'], ]; }else{ $model = $this; $data['referee_id'] = $referee_id; $data['reg_source'] = 'mp'; // 用户数据 $data['mpopen_id'] = $userInfo['openid']; $data['nickName'] = $userInfo['nickname']; $data['avatarUrl'] = $userInfo['headimgurl']; $data['gender'] = $userInfo['sex']; $data['province'] = $userInfo['province']; $data['country'] = $userInfo['country']; $data['city'] = $userInfo['city']; //默认等级 $data['grade_id'] = GradeModel::getDefaultGradeId(); } try { $this->startTrans(); // 保存/更新用户记录 if (!$model->save(array_merge($data, [ 'app_id' => self::$app_id ])) ) { throw new BaseException(['msg' => '用户注册失败']); } if (!$user && $referee_id > 0) { // 记录推荐人关系, RefereeModel::createRelation($model['user_id'], $referee_id); //更新用户邀请数量 (new UserModel())->setIncInvite($referee_id); } $this->commit(); } catch (\Exception $e) { $this->rollback(); throw new BaseException(['msg' => $e->getMessage()]); } return $model['user_id']; } }