thinkphp3.2.3微信授权登录

浏览:6457 最后更新:2017-07-04 10:08 分类:控制器 关键字: 授权 微信 登录 扩展 微信登录
最近公司在开发微信,着两天做授权登录,搞死了 第一次用tp开发项目 ,还好,
tp跟laravel的理念不是很一致,还好很容易接受 挺好 跟大家贴出来我写的这个代码吧,需要用的东西我都已经定义成常量,需要的话直接修改 中间关于session有点瑕疵 希望大佬可以告诉我一下. 谢谢<?php
namespace Apps\Controller;
use Common\Controller\AppBaseController;
define("TOKEN", "");//你微信定义的token
define("APPID", "");//你微信定义的appid
define("APPSECRET","");//你微信公众号的appsecret
            session_start;//打开session
class TestController extends AppBaseController //继承的这个控制器没用 你可以继承其他的任意一个

{
    //第一步:用户同意授权,获取code
    function accept(){
        //这个链接是获取code的链接 链接会带上code参数
        $REDIRECT_URI = "http://www.icoco.xin/wxt_webhome/index.php/Apps/Test/getCode";
        echo $REDIRECT_URI."<br>";
        $REDIRECT_URI = urlencode($REDIRECT_URI);
        echo $REDIRECT_URI."<br>";
        $scope = "snsapi_userinfo";
        echo $scope."<br>";
        $state = md5(mktime());
        echo $state."<br>";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$REDIRECT_URI."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
        header("location:$url");
        
    }
    //用户同意之后就获取code  通过获取code可以获取一切东西了  机智如我
    function getCode(){
        //获取accse_token
        $code = $_GET["code"];
        //echo $code;
                //echo "<br>";
        //用code获取access_yoken
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        //这里可以获取全部的东西  access_token openid scope
        $res = $this->https_request($url);
        $res  = json_decode($res,true);
        $openid = $res["openid"];
        echo "<pre>";
        //print_r($res);
        //echo $openid;
        //echo "<br>";
        $access_token = $res["access_token"];
        //echo $access_token;
        //这里是获取用户信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        $res = json_decode($res,true);
        //写入session
        print_r($res);
        //把用户的信息写入session 以备查用
        $weixn = $res["openid"];
        $nickname = $res["nickname"];

            $_SESSION["weixin"]=$weixin;
         header("location:http://www.icoco.xin/wxt_webhome/test.php");
    }
    function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
}//classend
大致注释都写的清晰明了,不明白的直接下方留言或者是加小陈QQ1098765230
评论( 相关
后面还有条评论,点击查看>>