官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
1.通过重定向回调获取code
关键代码:
//获取公众号相关信息 //获取公众号相关信息
$config = $obj->getConfig();
$code = request()->get('code');
if(!$code){
//回调时会返回code
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config['appid'];
$redirect_uri = urlencode('http://'.$_SERVER['HTTP_HOST'].'/test/apply');
$url .='&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
//进行头信息跳转
header('Location:'.$url);
}
2.因为获取openid的安全级别比较高,所以只能再服务端进行获取,再返回给前端,所以通过curl请求获取到openid
//获取openid
$param = [
'appid' => $config['appid'], //公众号的唯一标识
'secret' => $config['appsecret'], //公众号的appsecret
'code' => $code,
'grant_type' => 'authorization_code'
];
//http_build_query:使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'.http_build_query($param);
$res = curlRequest($url);
$res = json_decode($res);
$openid = isset($res->openid) ? $res->openid : '';
$this->assign('openid', $openid);
return $this->fetch('join');
3.前端通过隐藏域来保存oppenid:
<input type="hidden" name="openid" value="{$openid}">