在微信开发中,通常要获取点击链接的用户的open_id通常需要这几步。
1、获取带code的url,重定向。获取code。
static public function getURL(array $params) { $wx_id = $params['wx_id']; $domain = self::getWxDate($wx_id)->domain; $name = $params['name']; $param = [ 'appid' => config('wechat.app_id'), 'redirect_uri' => $domain .'/wx/' . $name, 'response_type' => 'code', 'scope' => 'snsapi_base', 'state' => 1 ]; return 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query($param) . '#wechat_redirect'; } 2、通过code获取openid public function getAuth(Request $request) { $code = $request->input('code'); $open_id = Cache::get($code, false); if (!$open_id) { $params = [ 'appid' => config('wechat.app_id'), 'secret' => config('wechat.secret'), 'code' => $request->input('code'), 'grant_type' => 'authorization_code', ]; $http = new Http(); $result = $http->get('https://api.weixin.qq.com/sns/oauth2/access_token', $params)->getBody(); $result = json_decode($result, true); if (isset($result['errcode'])) { return $result['errmsg']; } else { $open_id = $result['openid']; Cache::put($code, $open_id, 10); } } return view('weixin', ['open_id' => $open_id, 'red' => $data->amount]); }注:因为当通过code来获取openid时,code只能使用一次,这里用了一个小技巧来解决刷新网页code过期。就是上面标红的代码部分。当第一次获取到openid时,将openid缓存起来,刷新时会判断,如果openid存在,就不用通过code来获取openid了。当然这两行代码还有值得注意的地方就是缓存的key为code值。