思路
因为菜单设置成view时不能直接向微信服务器申请参数,要使用oauth2方式,需要做一次跳转,跳转时向微信服务器请求获得code,拿到code后再获取openid。我们需要两个页面,一个是获取code的跳转页,一个是获取openid的页面。具体代码如下。参考博客:http://blog.csdn.net/windvally/article/details/50921059
前置条件
配置授权回调页面域名
微信官方说明
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN#######配置地址
页面获取openid微信参考资料https://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html
code跳转页
<?php$APPID=’**************’;$REDIRECT_URI=’http://*********/webtest_rec.php’; //为要获取openid的页面$scope=’snsapi_base’;$state=’TEST’;//$scope=’snsapi_userinfo’;//需要授权$to_url=’https://open.weixin.qq.com/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);?>
获取openid页面
<?php$APPID=’******’;$SECRET=’******’;$state=’TEST’;$code=”;if($_GET[‘state’]==$state){$code = $_GET[‘code’];$uinfo=file_get_contents(“https://api.weixin.qq.com/sns/oauth2/access_token?appid=”.$APPID.”&secret=”.$SECRET.”&code={$code}&grant_type=authorization_code”);$uinfo=(array)json_decode($uinfo);$openid=$uinfo[‘openid’];echo “OPENID IS: “.$openid; //打印openid}?>
访问链接
你的code页地址
就会跳转到获取openid的页面效果如下
thinkphp示例
<?phpnamespace Wechat\Controller;use Think\Controller;class IndexController extends Controller { function _initialize() { } //获取openid页 public function index(){ //auth2获取openid $APPID='wx43ca47f682d37412'; $SECRET='6addbff756d8213ff39c4205ac172948'; $state='TEST'; $code=''; if($_GET['state']==$state){ $code = $_GET['code']; $uinfo=file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$APPID."&secret=".$SECRET."&code={$code}&grant_type=authorization_code"); $uinfo=(array)json_decode($uinfo); $openid=$uinfo['openid']; echo "OPENID IS: ".$openid; //打印openid } } //auth2获取openid跳转页 public function code(){ $APPID='wx43ca47f682d37412'; $REDIRECT_URI='http://car.qzurl.cn/wechat.php/Index/index'; $scope='snsapi_userinfo'; $state='TEST'; //$scope='snsapi_userinfo';//需要授权 $to_url='https://open.weixin.qq.com/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); }}```