PHP实现微信小程序用户授权的工具类示例(3)
保存用户信息的方法
/** * 保存用户信息的方法 * @param $wxaUserData * @param $regFromGh 表示是否从公众号进行注册 */ public function regWxaUser($wxaUserData,$regFromGh = false) { $value = $wxaUserData['unionId']; $key = getCacheKey('redis_key.cache_key.zset_list.lock') . $value; $newExpire = RedisHelper::getLock($key); $data = $this->storeWxaUser($wxaUserData,$regFromGh); RedisHelper::releaseLock($key, $newExpire); return $data; } /** * 保存信息 * @param $wxaUserData * @return mixed */ public function storeWxaUser($wxaUserData,$regFromGh = false) { $wxUnionId = $wxaUserData['unionId']; if (!$user = $this->getByWxUnionId($wxUnionId)) { $getAccountDataStartTime = time(); //这里是因为需要统一账户获取uid,所以这个是用户中心的接口,如果没有这个流程,则直接使用数据 if($accountData = AccountCenterHelper::regWxaUser($wxaUserData)){ $getAccountDataEndTime = time(); $accountRegTime = $getAccountDataEndTime - $getAccountDataStartTime; error_log("reg user spend time is ===================>" . $accountRegTime); $user = [ 'uid' => $accountData['uid'], 'user_name' => $accountData['user_name'], 'nick_name' => $wxaUserData['nickName'], 'sex' => $accountData['sex'], 'wx_union_id' => $accountData['wx_union_id'], 'avatar' => isset($accountData['avatar'])?$accountData['avatar']:"", 'from_appid' => $accountData['from_appid'], 'province' => $wxaUserData['province'], 'city' => $wxaUserData['city'], 'country' => $wxaUserData['country'], 'openid' => $wxaUserData['openId'], 'wx_header' => isset($wxaUserData['avatarUrl'])?$wxaUserData['avatarUrl']:"", 'gh_openid' => $regFromGh?$wxaUserData['openId']:"", ]; error_log("insert data=============>" . json_encode($user)); $user = $this->store($user); $regApiUserEndTime = time(); error_log(" reg api user spend time================>" . ($regApiUserEndTime - $getAccountDataEndTime)); error_log(" after insert data=============>" . json_encode($user)); } }else{ if(!$user['wx_header']){ $updateData = [ 'id' => $user['id'], 'uid' => $user['uid'], 'wx_header' => $wxaUserData['avatarUrl'], ]; $this->update($updateData); } //同步用户的openid if($wxaUserData['openId'] != $user['openid']){ $updateData = [ 'id' => $user['id'], 'uid' => $user['uid'], 'openid' => $wxaUserData['openId'], ]; $this->update($updateData); } } $data['uid'] = $user['uid']; $data['unionid'] = $wxUnionId; return $data; }
根据unionid获取用户信息