微信 OAuth2.0 网页授权

1、登录微信公众平台,在 "开发者中心" 找到

174342_8rMt_2320053.png

点击右侧的修改。

授权回调域名配置规范为全域名并且不带http,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权。

如:www.test.com

2、获取code

请求授权页面构造:

            $appid = "公众号在微信的appid";  

             $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=http://www.test.com/oauth.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';  

                header("Location:".$url);  

            }

3、在域名根目录下,新建一个文件,命名为oauth.php(授权回调地址),

<?php

$appid = "公众号在微信的appid";  

$secret = "公众号在微信的app secret";  

$code = $_GET["code"];  

$url = 'https://api.weixin.qq.com/sns/oauth2/access_token'; //请求地址

    //$ref_url = http://www.baidu.com; //来源页面

    $data = array(  //提交的数据

        "appid" => $appid,

        "secret" => $secret,

"code" => $code,

"grant_type" => "authorization_code"

    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_USERAGENT, $agent);

    //curl_setopt($ch, CURLOPT_REFERER, $ref_url);

    curl_setopt($ch, CURLOPT_POST, TRUE); //以POST方式提交

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //超时时间

    $contents = curl_exec($ch); //执行并获取返回数据

    curl_close($ch);

    $json_obj = json_decode($contents,true); 

  

//根据openid和access_token查询用户信息  

$access_token = $json_obj['access_token'];  

$openid = $json_obj['openid'];  

$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';  

  

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,$get_user_info_url);  

curl_setopt($ch,CURLOPT_HEADER,0);  

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  

$res = curl_exec($ch);  

curl_close($ch);  

  

//解析json  

$user_obj = json_decode($res,true);  

$_SESSION['user'] = $user_obj;  

print_r($user_obj);  

  

?>  



ps:参考

http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html

http://huangqiqing123.iteye.com/blog/2005770


转载于:https://my.oschina.net/jack088/blog/469663

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值