在公众号菜单跳转页面上配置跳转,按公众平台网页上的例子配置重定向:
因为菜单设置成view时不能直接向微信服务器申请参数,所以需要做一次跳转,跳转时向微信服务器请求获得code,拿到code后再获取openid。
<?php
$APPID='**************';$REDIRECT_URI='http://*********/webtest_rec.php'; //为要获取openid的页面
$scope='snsapi_base';
$state='TEST';
//$scope='snsapi_userinfo';//需要授权
$to_url='/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
echo $to_url;
header("Location:".$to_url);
?>
重定向后会在重定向上带上'code'和'state'两个参数。
在定向后的目标页面上获取code,然后通过code来获取open id;
webtest_rec.php如下:
<?php
echo "THIS IS REC WEB<br>";
$APPID='******';
$SECRET='******';
$state='TEST';
$code='';
if($_GET['state']==$state){
$code = $_GET['code'];
$uinfo=file_get_contents("/sns/oauth2/access_token?app&secret=".$SECRET."&code={$code}&grant_type=authorization_code");
$uinfo=(array)json_decode($uinfo);
$openid=$uinfo['openid'];
echo "OPENID IS: ".$openid; //打印openid
}
?>
这种方式只能简单的获取openid,不需要用户对网页授权。
是不是很简单呢?