100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > easywechat (在thinkphp5中使用easywechat完成微信网页认证)

easywechat (在thinkphp5中使用easywechat完成微信网页认证)

时间:2018-07-14 16:51:08

相关推荐

easywechat (在thinkphp5中使用easywechat完成微信网页认证)

由于在easywechat中没有提及在thinkphp中的使用,后来我在/topic/45416.html中找到了有人已经封装了一下,我把自己使用的过程写下来与大家共勉

在thinkphp中安装easywechat

1.使用composer下载

使用命令行进入thinkphp根目录

然后运行下面的命令:

composerrequirehooklife/thinkphp5-wechat

然后发布配置文件到项目根目录

phpthinkwechat:config

然后你会看到application目录下多了一个extra文件夹,里面有一个wechat.php,如果报错了,请参考 /archives/72/,这样就算是引入成功了

然后

填写配置文件需要填写的项

示例:

'debug' => true,

/**

* 账号基本信息,请从微信公众平台/开放平台获取

*/

'app_id' => '......', // AppID

'secret' => '......', // AppSecret

'token' => '......', // Token

'aes_key' => '',

'oauth' => [

'scopes' => ['snsapi_userinfo'],

'callback' => '回调地址',

],

然后,在原代码基础上创建一个控制器(与微信相关):Wechat1.php,

在里面定义一个变量app

$options = Config::get('wechat');

$app = new Application($options);

这样就能够使用app变量了,其他的用法参照文档/docs即可

配置和原来类似,我是在Wechat1.php中定义一个serve方法

public function serve(){

$server = self::$app->server;

$server->setMessageHandler(function ($message) {

return '你好';

});

$server->serve()->send();

}

在微信公众号后台验证token的url写能够访问到这个serve方法的链接即可验证成功

下面重点说明我使用easywechat进行网页授权过程

在需要授权的控制器Personal.php中的写了

static $app;

public function _initialize()

{

if (empty(session('id'))){

self::$app = Wechat1::return_app();

$oauth = self::$app->oauth;

session('target_url',$_SERVER['PATH_INFO']);

if (empty(session('wechat_user'))){

$oauth->redirect()->send();

}else{

$user = session('wechat_user');

$open_id = $user['original']['openid'];

//查询数据库中用户的账号的openid中是否有值,有值说明用户的微信与账号绑定

$student_no = self::check_login($open_id);

if ($student_no!=0){

session('id',$student_no);

$this->redirect(session('target_url'));

}else{

$this->redirect('index/Index/login');

}

}

}

}

然后在Wechat1.php中写了一个授权回调的方法

public function oauth(){

$oauth = self::$app->oauth;

$user = $oauth->user();

session('wechat_user',$user->toArray());

$targetUrl = session('target_url');

$this->redirect($targetUrl);

}

注:上面的配置文件中的回调函数就写能够找到oauth方法的地址即可

这样就能够完成微信网页授权,授权过的微信的用户信息存在session中,之后用到该用户信息的时候,只需要从session中取即可

### 注:现在官方网站上面支持thinkphp了,可以使用官方支持的扩展包,应该会更方便一些!!!thinkphp-wechat地址

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。