微信公众号授权,获取用户信息

结合文档和百度整理出几个方法,记录一下
用户直接访问getcode这个方法就行

<?php
namespace app\common\controller;

use think\Controller;

class Getinfo extends Controller
{
    //获取code
    public function getcode()
    {
        $appid = '公众号APPID';
        
        $huiurl = urlEncode('请求成功后的回调地址,具体到你的控制器方法中');//这里的url一定要用urlEncode处理一下
        //scope参数:snsapi_base(不弹出授权页面,直接跳转,只能获取用户openid)snsapi_userinfo(弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$huiurl.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
        header('location:'.$url);
    }
    //获取网页授权access_token,获取用户的openid
    public function getopenid()
    {
        $appid = '公众号APPID';
        $appsecret = '公众号的appsecret';
        $code = $_GET['code'];//这里用来接收上一步回调回来的code
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $res = $this->http_curl($url,'get');
        //进行到这里其实就可以做一下操作了,比如限制用户一天进入几次等操作;

		//下面就是获取用户信息了
        if(!empty($res['access_token'])){
            $data = $this->getuser($res['access_token'],$res['openid']);
        }
        var_dump($data);//获取到的用户信息

    }

    //获取用户信息
    public function getuser($access_token,$openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $data = $this->http_curl($url,'get');
        return $data;
    }


    //执行url请求
    public  function http_curl($url,$type='get',$res='json',$arr=''){

//        $url 请求的url
//        $type 请求类型
//        $res 返回数据类型
//        $arr post请求参数
        $ch=curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值