微信公众号开发全部流程,测试号开发微信授权登陆 3

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29787335/article/details/70053134

这里用到的几个接口基本上是开发微信的必备环节,很重要,而且这里有很多个知识点,以我个人的经验为例,面试一般问微信的问题就那么几个,要么就是微信的授权登陆,要么就是微信的支付几次握手,微信支付流程,回掉啊等等,基本上就这几个问题,然后剩下的就是掉接口了,谁都会掉,说谁都会,但是真正搞起来却不是那么一回事了。不说废话了,进入正题,

我提前准备了一个页面,http://www.520hutian.com/my/my/my/index.php/Home/Index/rou,页面上有3个肉,然后当我扫码进入这个测试公众号点击火锅然后点肉这个菜单的时候我需要进行授权登陆,这里面有几个步骤:

首先我写了一个肉页面的显示,然后当用户点击肉的时候我的方法会redirect到一个地址,这个地址就是拼接起来的,

       /*
* 肉页面的显示
*/
public function rou(){
$appid = C('APPID');//读取配置
$redirect_uri = "http://www.520hutian.com".U('Home/index/authorLogin');
redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
}

其中$redirect_url 就是回掉地址,在这个方法去接受你需要的code,这样就完成了第一步,获取了code然后就需要获取access_token,这里的access_token和我们之前的那些接口的access_token不同,这个时候就是调接口,他需要的参数就是你刚才的code和appid和appsecret,他会给你返回openid(用户的唯一id),第三步按照某些大神的说法没有必要你想写就写不想写也行,反正我个人也是觉得没啥必要,相当于一个可选参数,可有可无,第四步就是获取用户信息了,也是掉接口,需要access_token和openid,然后就能获取到你想要的数据了,这些操作以及打印都在微信里面,建议开发用网页版的微信比较好调试,(其中点击肉页面也就箱单与你在微信对话里面点击https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect,当然我这个是拼接的,你得打印出来,发给你自己的微信然后点击,此前记住需要关注这个微信号,以上就是微信号授权登陆的全部了,很简单,自己操作一遍,以后就没问题了)

   /*
*  授权登陆第一步获取code,然后第二步用code获取access_token,然后第三步(可省略,也可做)刷新access_token,第四步拉取用户信息(需scope为 snsapi_userinfo)
*/
public function authorLogin(){
//第一步接收code
if (isset($_GET['code'])){
echo $_GET['code'];
}else{
echo "NO CODE";
}
//第二步获取access_token
$appid = C('APPID');//读取配置
$appsecret = C('APPSECRET');//读取配置

$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
$json = '';
$result = curlpost($url,$json); 

$result = json_decode($result,true);

dump($result);
//第三步,刷新access_token
$thirdUrl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$result['refresh_token'];
$thirdJson = '';
$thirdResult = curlpost($thirdUrl,$thirdJson); 
$thirdResult = json_decode($thirdResult,true);
dump($thirdResult);


//第四步,获取用户信息
$fourthUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$thirdResult['access_token'].'&openid='.$thirdResult['openid'].'&lang=zh_CN';
$fourthJson = '';
$fourthResult = curlpost($fourthUrl,$fourthJson); 
//dump($fourthResult);
$fourthResult = json_decode($fourthResult,true);
dump($fourthResult);
}








猜你喜欢

转载自blog.csdn.net/qq_29787335/article/details/70053134