TP3.2.3 微信公众号实现网页授权登录

微信公众号实现网页授权

直接贴代码

新手一枚,根据我们的需求大概整理一下,勿喷
https://blog.csdn.net/weixin_40228592/article/details/81241123


namespace Home\Controller;
use Think\Controller;
class BaseController extends Controller {

    const USER_ID = 'user_id'; 
    const WEIXIN_OPENID = 'openid';
    const TARGET_URL = 'target_url';
    public function __construct()
    {
        $openid=$_SESSION[self::WEIXIN_OPENID];
        if(empty($openid)){

            $code=$_GET['code'];
            if($code){
                $openid=$this->get_openid($code);
                $arr = M('table')->field('field')->where(['openid'=>$openid])->find();
                session_start();
                $user_id = $arr['uid'];
                $_SESSION[self::USER_ID]=$user_id;
                $_SESSION[self::WEIXIN_OPENID]=$openid;
            }else{
                session_start();
                 $_SESSION[self::TARGET_URL]='https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $this->authForTc();

            }
        }

            $arr = M('table')->field('field')->where(['openid'=>$openid])->find();
            session_start();
            $user_id = $arr['uid'];
            $_SESSION[self::USER_ID]=$user_id;

        parent::__construct();
    }
    public function authForTc()
    {
        $url=$_SESSION[self::TARGET_URL];
        $redirect_uri=urlencode($url);
        $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";
        header("Location: $url");
    }

    public function get_openid($code){
        $appid="你的appid";
        $secret="你的secret";
        $get_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $arr = $this->request_get($get_token_url);
        return $arr['openid'];
    }


    public function cache_openid()
    {
        return $_SESSION[self::WEIXIN_OPENID];
    }

    public function cache_userid()
    {
        return $_SESSION[self::USER_ID];
    }

    public function request_get($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $json_obj = json_decode($res,true);
        return $json_obj;
    }

}


调用基类方法

namespace Home\Controller;
use Think\Controller;
class HouseController extends BaseController {
     public function house()
    {

        $user_id=$this->cache_userid();
        if(!$user_id){
        return false;

        }

    }

}

你可能感兴趣的:(TP3.2.3 微信公众号实现网页授权登录)