安装
安装tp51
composer create-project topthink/think=5.1.* tp5
安装easywechat
composer require overtrue/wechat:~4.0 -vvv
环境要求
- PHP >= 7.0
- PHP cURL 扩展
- PHP OpenSSL 扩展
- PHP SimpleXML 扩展
- PHP fileinfo 拓展
申请微信测试号
链接: 微信测试号申请
在tp51框架下的config文件夹中加入wechat.php配置文件
return [
/**
* Debug 模式,bool 值:true/false
*
* 当值为 false 时,所有的日志都不会记录
*/
'debug' => true,
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => 'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,安全模式下请一定要填写!!!
/**
* 日志配置
*
* level: 日志级别, 可选为:
* debug/info/notice/warning/error/critical/alert/emergency
* permission:日志文件权限(可选),默认为null(若为null值,monolog会取0644)
* file:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'level' => 'debug',
'permission' => 0777,
'file' => Env::get('runtime_path').'log/easywechat.log',
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/wx/index/oauthCallback',
],
/**
* 微信支付
*/
'payment' => [
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
],
/**
* Guzzle 全局设置
*
* 更多请参考: http://docs.guzzlephp.org/en/latest/request-options.html
*/
'guzzle' => [
'timeout' => 3.0, // 超时时间(秒)
//'verify' => false, // 关掉 SSL 认证(强烈不建议!!!)
],
];
服务器验证
- 建立控制器基类,这里使用\app\common\controller\BaseController
namespace app\common\controller;
use EasyWeChat\Factory;
use think\facade\Config;
use think\Controller;
class BaseController extends Controller
{
protected $app = null;
public function initialize(){
//将wechat的配置文件读取出来
$config = Config::pull('wechat');
//初始化app实例
$this->app = Factory::officialAccount($config);
}
}
- 服务器验证的具体逻辑
namespace app\index\controller;
use app\common\controller\BaseController;
use think\facade\Request;
class Index extends BaseController
{
public function index(){
//监测开发者微信服务器
//$this->checkServer();
//exit;
$this->app->server->push(function ($message) {
switch ($message['MsgType']) {
case 'event':
$messageEvent = $message['Event'];
$messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
$returnInfo = $this->eventHandler($messageEvent, $messageKey);
return $returnInfo;
break;
case 'text':
return str_replace('?', '', $message['Content']) . '!'; // 实现人工智能(*^▽^*)
break;
case 'image':
return '收到图片消息';
break;
case 'voice':
return '收到语音消息';
break;
case 'video':
return '收到视频消息';
break;
case 'location':
return '收到坐标消息';
break;
case 'link':
return '收到链接消息';
break;
default:
return '收到其它消息';
break;
}
});
$response = $this->app->server->serve();
return $response->send();
}
/**
* 检测开发者服务器
* @return mixed
*/
public function checkServer(){
$response = $this->app->server->serve();
return $response->send();
}
public function setMenu(){
$buttons = [
[
"type" => "click",
"name" => "menuClick",
"key" => "menu_click_test",
],
[
"name" => "二级菜单",
"sub_button" => [
[
"type" => "view",
"name" => '搜索',
"url" => "http://domain.com/wx/index/test",
],
[
"type" => "click",
"name" => "subMenuClick",
"key" => "sub_menu_click_test"
],
],
],
];
$setRes = $this->app->menu->create($buttons);
return json_encode($setRes);
}
/**
* 事件处理
* @param $messageEvent
* @param $eventKey
* @return string
*/
private function eventHandler($messageEvent,$eventKey)
{
$messageEvent = strtolower($messageEvent);
switch ($messageEvent) {
case 'subscribe': // 订阅事件
return '欢迎订阅';
break;
case 'unsubscribe': // 取消订阅事件
// TODO 可以添加日志等其他逻辑
return '';
break;
case 'click': // 处理菜单点击事件
return $this->menuClickEventHandler($eventKey);
break;
default:
return "{$messageEvent}, {$eventKey}";
break;
}
}
/**
* 菜单栏中type为click的按钮才会发送return的消息回去
* eventKey是设置菜单时type为click的key值
* @param $eventKey
* @return string
*/
private function menuClickEventHandler($eventKey){
switch ($eventKey) {
case 'menu_click_test':
return '点击了一级菜单的 menuClick 按钮';
break;
case 'sub_menu_click_test':
return '点击了二级菜单的 subMenuClick 按钮';
break;
default:
return "嘻嘻";
break;
}
}
}
这里说明一下:服务器的验证方法是checkServer,使用easywechat,只用简单的几句就完成了验证。
针对创建菜单,和各种事件做了一个简单测试,这里就不赘述,看一下代码就很清楚了。
网页授权
具体的网页逻辑使用了一个新的父类\app\common\controller\WechatBaseController
namespace app\common\controller;
use EasyWeChat\Factory;
use think\facade\Config;
use think\Controller;
use think\facade\Session;
class WechatBaseController extends Controller
{
protected $app = null;
public function initialize(){
//将wechat的配置文件读取出来
$config = Config::pull('wechat');
//初始化app实例
$this->app = Factory::officialAccount($config);
if(!$this->hasWechatUser()){
$this->redirect('/wx/Oauth/profile');
}else{
//dump('父类统一获取');
//dump(Session::get('wechat_user'));
}
}
/**
* 是否有wechat_user的session
* @return bool
*/
protected function hasWechatUser(){
if(Session::has('wechat_user')){
return true;
}else{
return false;
}
}
}
网页授权控制器 \app\wx\controller\Oauth
namespace app\wx\controller;
use app\common\controller\WechatBaseController;
use think\facade\Session;
class Oauth extends WechatBaseController
{
// 开始授权
public function profile()
{
$oauth = $this->app->oauth;
if (empty(Session::get('wechat_user'))) {
Session::set('target_url', '/wx/Oauth/profile');
return $oauth->redirect();
}
//$user = Session::get('wechat_user');
}
// 授权成功回调
public function oauthCallback()
{
$oauth = $this->app->oauth;
$user = $oauth->user();
Session::set('wechat_user', $user);
$targetUrl = !empty(Session::get('target_url')) ? '/wx/Oauth/oauthSuccess' : Session::get('target_url');
header('location:' . $targetUrl); // 跳转到 user/profile
}
// 授权成功之后输出信息
public function oauthSuccess(){
$user=Session::get('wechat_user');
// todo 将用户的基本信息保存在数据库中,然后提供下次进行使用
dump($user);
}
}
具体业务页面
namespace app\wx\controller;
use app\common\controller\WechatBaseController;
class Index extends WechatBaseController
{
// test页面渲染
public function test()
{
//$users = $this->getUserList();
//dump($users);
return $this->view->fetch();
}
// 获取用户列表
public function getUserList(){
$users = $this->app->user->list();
return $users;
}
}
目前的测试使用就到这里,进行了一些微信基本功能的测试,感觉easywechat还是很爽的啊。
来源:CSDN
作者:u011790057
链接:https://blog.csdn.net/u011790057/article/details/103728812