tp5公众号获取用户信息

开发公众号,最常用到的就是获取用户信息,对于大神来说,这技术跟本就不是什么事儿,但对于小冰这样的小白来说,却是一件苦差事儿,就上次,因为这活儿,弄了我一个大晚上。
1、首先在公众号后台填 写授权域名
注:授权回调页面域名:填写域名(不带http和www)本址可以先使用本机ip地址
2、php代码块
(1、)先引导用户进入授权页面,使用appid获取code;

public function wxLogin(){
       //appId
       $appId = 'your appId';
       // 回调的url
       $redirect_uri = urlencode('http://127.0.0.1/test/public/index/user/getUserInfo');
       //跳转微信回调到redirect_uri获取code
       $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
       $this->redirect($url);
    }

//参数解释
appid:公从号中的appid
redirect_uri:授权后重定向的地址,即引导用户进入授权的那个页面,需要使用urlEncode函数进行处理
response_type:填写code即可
scope:有两个选择 snsapi_base(不弹出授权页面,直接跳转,只能拿到用户的opedid) snsapi_userinfo(弹出授权页面,可以拿到opendid 和用户头像等)
state:填写STATE(大写)
#wechat_redirect:没有参数 (注意前面有井号)

(2、)通过code 换取 access_token

public function getUserInfo(){
       //获取code
       $code = $_GET["code"];
       // appId与appSecret
       $appId = 'your appId';
       $appSecret = 'your appSecret';
      
       $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
       $res = $this->sendRequest($url);
       $access_token = $res["access_token"];//拿到access_token
       $openId  = $res['openid']; //拿到用户的oppid
       $getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
       //得到用户信息
       $user_info = $this->sendRequest($getUserInfo);
       dump($user_info);
       //接下来的逻辑...
   }

//url参数解析
appid:公众号的appid
appSecret:公众号的appSecret
code:第一步中的get过来的code
grant_type:填写authorization_code即可

(3、)发送请求

public function sendRequest($url){
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       $output = curl_exec($ch);
       curl_close($ch);
       return json_decode($output, true);
   }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值