コード例 #1
0
ファイル: User.php プロジェクト: unionbt/hanpaimall
 /**
  * 更新微信资料(如果没有则添加用户资料)
  * 
  * @param  string $openid      	OPENID
  * @param  string $access_token     如果是通过OAuth2授权,则需要传递此参数
  * @param  string $role_name        组名,只在添加用户时有效
  * @param  integer $update_expire 	多少分钟更新一次?
  * @return integer                  返回UID
  */
 public function updateWechatUser($openid, $access_token = NULL, $cache = TRUE)
 {
     if (empty($openid)) {
         return FALSE;
     }
     $wechatUser = FALSE;
     $hashkey = 'update-wechatuser-' . $openid . '/' . $this->api->appid;
     if (!$cache || is_null($wechatUser = Cache::get($hashkey, null))) {
         $wechatUser = WechatUser::firstOrCreate(['openid' => $openid, 'waid' => $this->api->waid]);
         $wechat = $this->getUserInfo($wechatUser->openid, $access_token, $cache);
         /*
         			无授权的OAuth2是无法获取资料的
         			if (empty($wechat))
         				throw new \Exception("Get wechat's user failure:" .$this->api->errCode .' '.$this->api->errMsg);*/
         //公众号绑定开放平台,可获取唯一ID
         if (empty($wechatUser->unionid) || !empty($wechat['unionid'])) {
             $wechatUser->update(['unionid' => isset($wechat['unionid']) ? $wechat['unionid'] : $wechatUser->openid . '/' . $this->api->appid]);
         }
         if (isset($wechat['nickname'])) {
             //将所有唯一ID匹配的资料都更新
             $wechatUsers = WechatUser::where('unionid', $wechatUser->unionid)->get();
             foreach ($wechatUsers as $v) {
                 $v->update(['nickname' => $wechat['nickname'], 'gender' => $wechat['sex'], 'is_subscribed' => !empty($wechat['subscribe']), 'subscribed_at' => !empty($wechat['subscribe_time']) ? Carbon::createFromTimestamp($wechat['subscribe_time']) : NULL, 'country' => $wechat['country'], 'province' => $wechat['province'], 'city' => $wechat['city'], 'language' => $wechat['language'], 'remark' => !empty($wechat['remark']) ? $wechat['remark'] : NULL, 'groupid' => !empty($wechat['groupid']) ? $wechat['groupid'] : NULL, 'avatar_aid' => $wechat['avatar_aid']]);
             }
         }
         $wechatUser = WechatUser::where('openid', $openid)->where('waid', $this->api->waid)->get()->first();
         Cache::put($hashkey, $wechatUser, 12 * 60);
         //0.5 day
     }
     return $wechatUser;
 }