快乐每一天

自己选择的路,跪着也要走下去...

标签 EasyWeichat 下的文章

EasyWeiChat&ThinkPHP5.1 实现简单的网页授权登录demo

首先是composer 框架

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ 

composer create-project topthink/think=5.1.* tp5

cd tp5

composer require naixiaoxin/think-wechat 

接下来是demo

<?php
namespace app\index\controller;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Factory;
use think\facade\Session;
session_start();
class Index
{

    public function hello($name = 'ThinkPHP5')
    {    

        $user = $_SESSION['wechat_user'];

        return 'hello,' . $name;
    }

    public function confcc(){
        $config = [
            'app_id' => '**************',
            'secret' => '*******************************',
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/index/index/oauth_callback',
            ],
            // ..
        ];
        return $config;
    }

    public function clears(){
        print_r($_SESSION);
        session_destroy();
    }

    public function profile(){

        $config=$this->confcc();
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        // 未登录
        if (empty($_SESSION['wechat_user'])) {

            $_SESSION['target_url'] = '/index/index/profile';

            return $oauth->redirect();
            // 这里不一定是return,如果你的框架action不是返回内容的话你就得使用
            // $oauth->redirect()->send();
        }
// 已经登录过
        $user = $_SESSION['wechat_user'];

        var_dump($user);

        // echo 122;
        // exit;

    }

    public function oauth_callback(){

        $config=$this->confcc();

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

// 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();

        $targetUrl = empty($_SESSION['target_url']) ? '/index/index/hello' : $_SESSION['target_url'];

        header('location:'. $targetUrl); // 跳转到 user/profile
    }


}

2019-08-06T02:09:45.png

关注公众号,然后在微信里面执行下面的连接既可以体验这个代码的效果,不到30行就能完成简单的授权获取用户信息功能,感谢强大的EasyWeichat

http://easywx.cssnb.com/index/index/profile

阅读全文