PHP API微信网页授权接口实现

20 篇文章 0 订阅
9 篇文章 0 订阅

这两天在网上看到关于微信网页授权的文档,闲着没事就来做做
首先说说需要的材料
1. 一个可访问的域名或IP地址
2.微信公众平台(一定要先去https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index里面设置网页授权获取用户基本信息的网页账号)
在这里插入图片描述
3.草料二维码制作
首先说明一下,我用的是laravel框架
行,不废话了,代码直接上

	/**
	*当用户同意授权(授权成功)时,微信会回调到$redirect_url这个链接,并且带上一个有效时间为五分钟的code(code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。)
	*/
	public function getUserDetail(){
        $redirect_url=urlencode("https://www.cacov.cn/crontab/getUserInfo");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=$redirect_url&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        return redirect($url);
    }
    /**
    *通过code换取网页授权access_token
    *拉取用户信息(需scope为 snsapi_userinfo---上一个方法中设置)
    */
    public function getUserInfo(){
        $code=$_GET['code'];
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
        $res=$this->my_curl_wx_api($url,'GET');
        $access_token=$res['access_token'];//网页授权的access_token
        $openid=$res['openid'];//用户的openid
        //拉取用户的详细信息
        $user_url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $user_res=$this->my_curl_wx_api($user_url,'GET');
        print_r($user_res);
    }
    /**
     * @param $url
     * @param string $type
     * @param array $data
     * @return mixed
     * 接口请求
     */
    protected function my_curl_wx_api($url, $type = 'POST', $data = array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        if($data){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }


完成上面的步骤后,就可以去草料二维码里面将getUserDetail方法的服务器位置生成一个二维码,然后用微信扫一下就好了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值