EasyWeChat SDK 详细说明
一、概述
EasyWeChat 是一个开源的 PHP 微信开发 SDK,由 overtrue(安正超)开发维护。它封装了微信公众平台、开放平台、企业微信、微信支付等多个微信产品的 API,提供了简洁易用的接口。
二、主要特性
1. 支持全面的微信产品
- ✅ 微信公众号(服务号、订阅号)
- ✅ 微信小程序
- ✅ 微信支付(包括服务商模式)
- ✅ 企业微信
- ✅ 开放平台
- ✅ 微信硬件平台
2. 功能模块丰富
- 消息管理(接收/回复消息)
- 用户管理
- 菜单管理
- 素材管理
- 模板消息
- 客服消息
- 二维码管理
- 卡券功能
- 门店管理
- JS-SDK
- 数据统计
三、版本说明
不同版本对比
| 版本 | PHP要求 | 特点 | 状态 |
|---|---|---|---|
| 2.x | PHP 5.3+ | 早期版本,已停止维护 | ❌ 已废弃 |
| 3.x | PHP 5.6+ | 稳定版本,广泛使用 | ✅ 主流版本 |
| 4.x | PHP 7.0+ | 新版,支持 PSR 标准 | ✅ 推荐新项目 |
| 5.x | PHP 7.2+ | 最新版,支持 PHP 8 | ✅ 最新版本 |
安装命令
# 安装 3.x 版本
composer require "overtrue/wechat:~3.1"
# 安装 4.x 版本
composer require "overtrue/wechat:~4.0"
# 安装 5.x 版本
composer require "overtrue/wechat:~5.0"
四、核心架构
1. Application(应用入口)
namespace EasyWeChat\Foundation;
use Pimple\Container;
class Application extends Container
{
// 服务提供者数组
protected $providers = [];
// 构造函数
public function __construct($config);
// 获取服务
public function __get($id);
// 设置服务
public function __set($id, $value);
}
2. 服务提供者机制
// 服务提供者示例
namespace EasyWeChat\Foundation\ServiceProviders;
use EasyWeChat\Server\Server;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
class ServerServiceProvider implements ServiceProviderInterface
{
public function register(Container $pimple)
{
$pimple['server'] = function ($pimple) {
return new Server($pimple['access_token']);
};
}
}
五、详细使用指南
1. 基础配置
1.1 完整配置示例
$config = [
/**
* 基础配置
*/
'app_id' => 'wx3cf0f39249eb0e60', // AppID
'secret' => 'f1c242f4f28f735d4687abb469072a29', // AppSecret
'token' => 'easywechat', // Token
'aes_key' => 'K4CgXpZvUj9pR7x2V8hG5nJqNtY6wA0d', // 安全模式下请一定要填写!!!
/**
* 日志配置
*/
'log' => [
'level' => 'debug', // debug, info, notice, warning, error, critical, alert, emergency
'file' => '/tmp/easywechat.log',
// 'file' => __DIR__ . '/wechat.log', // 绝对路径
],
/**
* 缓存配置(默认使用文件缓存)
*/
'cache' => [
'driver' => 'file', // 支持 file, redis, memcached
'path' => '/tmp/easywechat/cache', // 文件缓存路径
],
/**
* OAuth 配置(网页授权)
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'], // snsapi_base, snsapi_userinfo
'callback' => '/oauth_callback', // 回调地址
],
/**
* 支付配置(如果需要支付功能)
*/
'payment' => [
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => '/path/to/your/cert.pem', // 绝对路径!!!
'key_path' => '/path/to/your/key.pem', // 绝对路径!!!
'notify_url' => '默认的订单回调地址',
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
],
/**
* 小程序配置(如果需要小程序功能)
*/
'mini_program' => [
'app_id' => 'mini-program-appid',
'secret' => 'mini-program-secret',
],
/**
* 企业微信配置
*/
'work' => [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'agent_id' => 1000002,
'secret' => 'xxxxxxxxxx',
],
];
1.2 多应用配置管理
// 多应用配置管理类
class WeChatConfig
{
private static $configs = [
'official_account' => [
'app_id' => 'xxx',
'secret' => 'xxx',
'token' => 'xxx',
],
'mini_program' => [
'app_id' => 'yyy',
'secret' => 'yyy',
],
'payment' => [
'app_id' => 'xxx',
'mch_id' => 'zzz',
'key' => 'zzz',
],
];
public static function get($type)
{
$config = self::$configs[$type] ?? null;
if (!$config) {
throw new InvalidArgumentException("未找到 {$type} 的配置");
}
// 添加通用配置
$config['log'] = [
'level' => env('APP_DEBUG') ? 'debug' : 'error',
'file' => LOG_PATH . 'wechat_' . $type . '.log',
];
return $config;
}
}
2. 核心模块使用
2.1 服务器模块(消息处理)
use EasyWeChat\Foundation\Application;
$app = new Application($config);
$server = $app->server;
// 设置消息处理器
$server->setMessageHandler(function ($message) {
// $message 类型:EasyWeChat\Support\Collection
// 属性:ToUserName, FromUserName, CreateTime, MsgType, MsgId, Content, etc.
switch ($message->MsgType) {
case 'event':
// 事件消息
return $this->handleEvent($message);
case 'text':
// 文本消息
return $this->handleText($message);
case 'image':
// 图片消息
return $this->handleImage($message);
case 'voice':
// 语音消息
return $this->handleVoice($message);
case 'video':
// 视频消息
return $this->handleVideo($message);
case 'shortvideo':
// 小视频消息
return $this->handleShortVideo($message);
case 'location':
// 位置消息
return $this->handleLocation($message);
case 'link':
// 链接消息
return $this->handleLink($message);
case 'file':
// 文件消息(企业微信)
return $this->handleFile($message);
default:
return '收到未知类型消息';
}
});
// 具体处理方法
private function handleEvent($message)
{
switch ($message->Event) {
case 'subscribe':
// 关注事件
return $this->handleSubscribe($message);
case 'unsubscribe':
// 取消关注事件
$this->handleUnsubscribe($message);
return '';
case 'SCAN':
// 扫码事件(已关注用户)
return $this->handleScan($message);
case 'LOCATION':
// 上报地理位置事件
return $this->handleLocationEvent($message);
case 'CLICK':
// 菜单点击事件
return $this->handleMenuClick($message);
case 'VIEW':
// 菜单跳转链接事件
return $this->handleMenuView($message);
case 'TEMPLATESENDJOBFINISH':
// 模板消息发送完成
return $this->handleTemplateSendJobFinish($message);
default:
return '';
}
}
// 响应微信服务器的请求
$response = $server->serve();
$response->send();
2.2 用户管理
$user = $app->user;
// 1. 获取用户列表
$userList = $user->lists(); // 获取全部用户
$userList = $user->lists($nextOpenId); // 从指定 openid 开始获取
// 2. 获取用户信息
$userInfo = $user->get($openId);
// 或者批量获取
$userInfos = $user->batchGet([$openId1, $openId2]);
// 3. 修改用户备注
$user->remark($openId, 'VIP客户');
// 4. 获取用户分组
$groups = $user->group($openId);
// 5. 移动用户分组
$user->move($openId, $groupId);
// 6. 获取黑名单用户
$blacklist = $user->blacklist($beginOpenId = null);
// 7. 拉黑用户
$user->block([$openId1, $openId2]);
// 8. 取消拉黑用户
$user->unblock([$openId1, $openId2]);
2.3 素材管理
$material = $app->material;
// 1. 上传临时素材(3天内有效)
$temporary = $app->material_temporary;
$imageResult = $temporary->uploadImage($path); // 图片
$voiceResult = $temporary->uploadVoice($path); // 语音
$videoResult = $temporary->uploadVideo($path, $title, $description); // 视频
$thumbResult = $temporary->uploadThumb($path); // 缩略图
// 2. 获取临时素材
$media = $temporary->get($mediaId);
// 3. 上传永久素材
$imageResult = $material->uploadImage($path); // 图片
$voiceResult = $material->uploadVoice($path); // 语音
$videoResult = $material->uploadVideo($path, $title, $description); // 视频
$thumbResult = $material->uploadThumb($path); // 缩略图
// 图文素材
$article = [
'title' => '测试标题',
'thumb_media_id' => $thumbMediaId,
'author' => '作者',
'digest' => '摘要',
'show_cover_pic' => 1,
'content' => '正文内容',
'content_source_url' => '原文链接',
'need_open_comment' => 1, // 是否打开评论
'only_fans_can_comment' => 1, // 是否粉丝才可评论
];
$articleResult = $material->uploadArticle($article); // 单图文
$articlesResult = $material->uploadArticle([$article1, $article2]); // 多图文
// 4. 获取永久素材
$media = $material->get($mediaId);
// 5. 删除永久素材
$material->delete($mediaId);
// 6. 修改图文素材
$material->updateArticle($mediaId, $article, $index = 0);
// 7. 获取素材总数
$stats = $material->stats();
// 8. 获取素材列表
// 图片、语音、视频
$list = $material->lists($type, $offset = 0, $count = 20);
// 图文
$list = $material->lists('news', $offset = 0, $count = 20);
2.4 菜单管理
$menu = $app->menu;
// 1. 定义菜单结构
$buttons = [
[
"type" => "click",
"name" => "今日歌曲",
"key" => "V1001_TODAY_MUSIC"
],
[
"name" => "菜单",
"sub_button" => [
[
"type" => "view",
"name" => "搜索",
"url" => "http://www.soso.com/"
],
[
"type" => "miniprogram",
"name" => "小程序",
"url" => "http://mp.weixin.qq.com",
"appid" => "xiaochengxuappid12345",
"pagepath" => "pages/index/index"
],
[
"type" => "click",
"name" => "赞一下我们",
"key" => "V1001_GOOD"
],
],
],
[
"type" => "location_select",
"name" => "发送位置",
"key" => "V1001_LOCATION_SELECT"
],
];
// 2. 创建菜单
$menu->add($buttons);
// 3. 获取菜单
$menus = $menu->current();
// 4. 删除菜单
$menu->destroy();
// 5. 创建个性化菜单
$conditionalButtons = [
'button' => $buttons,
'matchrule' => [
'tag_id' => '2',
'sex' => '1',
'country' => '中国',
'province' => '广东',
'city' => '广州',
'client_platform_type' => '2',
'language' => 'zh_CN'
]
];
$menu->add($conditionalButtons);
// 6. 删除个性化菜单
$menuId = '208379533';
$menu->destroy($menuId);
// 7. 测试个性化菜单
$userId = 'weixin';
$menu->match($userId);
2.5 模板消息
$notice = $app->notice;
// 1. 设置行业
$industryIds = [1, 2]; // 主行业和副行业
$notice->setIndustry($industryIds[0], $industryIds[1]);
// 2. 获取行业信息
$industries = $notice->getIndustry();
// 3. 获取模板ID
$templateIdShort = 'TM00015';
$templateId = $notice->addTemplate($templateIdShort);
// 4. 获取模板列表
$templates = $notice->getPrivateTemplates();
// 5. 删除模板
$notice->deletePrivateTemplate($templateId);
// 6. 发送模板消息
$message = $notice->to($openId)
->template($templateId)
->url('http://www.example.com') // 跳转链接
->data([
'first' => '恭喜你购买成功!',
'keyword1' => '巧克力',
'keyword2' => '39.8元',
'keyword3' => '2019年10月1日',
'remark' => '欢迎再次购买!'
])
->send();
// 7. 发送一次性订阅消息
$subscribeNotice = $app->notice;
$message = $subscribeNotice->to($openId)
->template($templateId)
->scene($scene) // 订阅场景值
->data([/* 模板数据 */])
->send();
2.6 客服消息
$staff = $app->staff;
// 1. 获取客服列表
$list = $staff->lists();
// 2. 获取在线客服
$online = $staff->online();
// 3. 添加客服账号
$staff->create('test@test', '客服昵称', 'password');
// 4. 修改客服账号
$staff->update('test@test', '新昵称', '新密码');
// 5. 删除客服账号
$staff->delete('test@test');
// 6. 设置客服头像
$staff->avatar('test@test', $imagePath);
// 7. 发送客服消息
$messageHandler = $app->staff_message;
// 文本消息
$messageHandler->text('您好')->to($openId)->send();
// 图片消息
$messageHandler->image($mediaId)->to($openId)->send();
// 语音消息
$messageHandler->voice($mediaId)->to($openId)->send();
// 视频消息
$messageHandler->video($mediaId)->to($openId)->send();
// 音乐消息
$messageHandler->music($title, $description, $musicUrl, $thumbMediaId)->to($openId)->send();
// 图文消息
$articles = [
[
'title' => '标题',
'description' => '描述',
'url' => '链接',
'picurl' => '图片链接'
]
];
$messageHandler->news($articles)->to($openId)->send();
// 8. 客服输入状态
$messageHandler->typing($openId); // 进入输入状态
$messageHandler->cancelTyping($openId); // 取消输入状态
2.7 微信支付
$payment = $app->payment;
// 1. 统一下单
$order = new \EasyWeChat\Payment\Order([
'body' => '测试商品',
'out_trade_no' => date('YmdHis') . mt_rand(1000, 9999),
'total_fee' => 1, // 单位:分
'trade_type' => 'JSAPI', // JSAPI, NATIVE, APP
'openid' => $openId, // trade_type=JSAPI时需要
'product_id' => '123456', // trade_type=NATIVE时需要
'notify_url' => 'https://example.com/pay/notify', // 支付结果通知地址
]);
$result = $payment->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
// 获取支付配置(用于前端调起支付)
$config = $payment->configForJSSDKPayment($result->prepay_id);
// 如果是 NATIVE 支付,返回二维码链接
$codeUrl = $result->code_url;
}
// 2. 查询订单
$payment->query($outTradeNo);
$payment->queryByTransactionId($transactionId);
// 3. 关闭订单
$payment->close($outTradeNo);
// 4. 申请退款
$refundOrder = [
'out_trade_no' => $outTradeNo,
'out_refund_no' => date('YmdHis') . mt_rand(1000, 9999),
'total_fee' => 100,
'refund_fee' => 100,
'refund_desc' => '测试退款',
];
$payment->refund($refundOrder);
// 5. 查询退款
$payment->queryRefund($outTradeNo);
$payment->queryRefundByRefundNo($outRefundNo);
// 6. 下载对账单
$billDate = '20190101';
$billType = 'ALL'; // ALL, SUCCESS, REFUND, RECHARGE_REFUND
$payment->downloadBill($billDate, $billType);
// 7. 支付结果通知处理
$response = $payment->handleNotify(function($notify, $successful) {
// $notify 是通知内容
// $successful 表示支付是否成功
if (!$successful) {
// 支付失败,记录日志
Log::error('支付失败', ['notify' => $notify]);
return false;
}
// 支付成功,处理业务逻辑
$outTradeNo = $notify->out_trade_no;
// 查询本地订单
$order = OrderModel::where('trade_no', $outTradeNo)->find();
if (!$order) {
Log::error('订单不存在', ['trade_no' => $outTradeNo]);
return false;
}
if ($order->status == 'paid') {
// 防止重复处理
return true;
}
// 更新订单状态
$order->status = 'paid';
$order->paid_at = time();
$order->save();
// 其他业务逻辑...
return true; // 返回 true 告诉微信处理成功
});
六、ThinkPHP 集成示例
1. 服务类封装
// application/common/service/WeChatService.php
namespace app\common\service;
use EasyWeChat\Foundation\Application;
use think\Config;
use think\Cache;
use think\Log;
class WeChatService
{
private static $instances = [];
/**
* 获取微信应用实例
*/
public static function getInstance($type = 'official_account')
{
if (!isset(self::$instances[$type])) {
$config = self::getConfig($type);
self::$instances[$type] = new Application($config);
}
return self::$instances[$type];
}
/**
* 获取配置
*/
private static function getConfig($type)
{
$baseConfig = Config::get('wechat.' . $type);
if (!$baseConfig) {
throw new \Exception("微信配置不存在:{$type}");
}
// 合并通用配置
$config = array_merge($baseConfig, [
'log' => [
'level' => Config::get('app_debug') ? 'debug' : 'error',
'file' => LOG_PATH . 'wechat_' . $type . '.log',
],
'cache' => new WeChatCacheDriver(), // 自定义缓存驱动
]);
return $config;
}
/**
* 获取公众号实例
*/
public static function officialAccount()
{
return self::getInstance('official_account');
}
/**
* 获取小程序实例
*/
public static function miniProgram()
{
return self::getInstance('mini_program');
}
/**
* 获取支付实例
*/
public static function payment()
{
return self::getInstance('payment');
}
/**
* 获取企业微信实例
*/
public static function work()
{
return self::getInstance('work');
}
/**
* 处理服务器验证
*/
public static function serve()
{
try {
$app = self::officialAccount();
$server = $app->server;
$server->setMessageHandler(function($message) {
return WeChatMessageHandler::handle($message);
});
return $server->serve();
} catch (\Exception $e) {
Log::error('微信服务器处理失败', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return '服务器异常';
}
}
/**
* 获取 JS-SDK 配置
*/
public static function getJssdkConfig($url = null)
{
$app = self::officialAccount();
$js = $app->js;
if ($url) {
$js->setUrl($url);
}
return $js->config([
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'closeWindow',
'scanQRCode',
], true);
}
}
// 自定义缓存驱动(适配 ThinkPHP 缓存)
class WeChatCacheDriver implements \Doctrine\Common\Cache\Cache
{
public function fetch($id)
{
return Cache::get($id);
}
public function contains($id)
{
return Cache::has($id);
}
public function save($id, $data, $lifeTime = 0)
{
return Cache::set($id, $data, $lifeTime);
}
public function delete($id)
{
return Cache::rm($id);
}
public function getStats()
{
return null;
}
}
2. 消息处理器
// application/common/handler/WeChatMessageHandler.php
namespace app\common\handler;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\Voice;
use EasyWeChat\Message\Video;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Article;
use think\Log;
class WeChatMessageHandler
{
/**
* 处理消息
*/
public static function handle($message)
{
try {
switch ($message->MsgType) {
case 'event':
return self::handleEvent($message);
case 'text':
return self::handleText($message);
case 'image':
return self::handleImage($message);
case 'voice':
return self::handleVoice($message);
case 'video':
return self::handleVideo($message);
case 'shortvideo':
return self::handleShortVideo($message);
case 'location':
return self::handleLocation($message);
case 'link':
return self::handleLink($message);
default:
return self::defaultResponse($message);
}
} catch (\Exception $e) {
Log::error('微信消息处理异常', [
'message' => $message,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return '服务器繁忙,请稍后再试';
}
}
/**
* 处理文本消息
*/
private static function handleText($message)
{
$content = trim($message->Content);
// 关键字回复
switch ($content) {
case '帮助':
case 'help':
return self::helpResponse();
case '菜单':
return self::menuResponse();
case '绑定':
return self::bindResponse($message->FromUserName);
default:
// 智能回复或默认回复
return self::autoReply($content);
}
}
/**
* 处理事件消息
*/
private static function handleEvent($message)
{
switch ($message->Event) {
case 'subscribe':
return self::handleSubscribe($message);
case 'unsubscribe':
return self::handleUnsubscribe($message);
case 'SCAN':
return self::handleScan($message);
case 'LOCATION':
return self::handleLocationEvent($message);
case 'CLICK':
return self::handleMenuClick($message);
case 'VIEW':
return self::handleMenuView($message);
default:
return '';
}
}
/**
* 关注事件处理
*/
private static function handleSubscribe($message)
{
$openId = $message->FromUserName;
$eventKey = $message->EventKey ?? ''; // 扫描带参数二维码关注
// 记录用户关注
UserService::subscribe($openId, $eventKey);
// 回复欢迎消息
return new Text([
'content' => "欢迎关注!\n\n".
"回复【帮助】查看使用指南\n".
"回复【绑定】关联您的账号"
]);
}
/**
* 帮助回复
*/
private static function helpResponse()
{
$content = "📱 使用指南\n\n".
"🔸 绑定账号:回复【绑定】\n".
"🔸 查看菜单:回复【菜单】\n".
"🔸 联系客服:回复【客服】\n".
"🔸 意见建议:直接留言";
return new Text(['content' => $content]);
}
/**
* 自动回复(可接入AI)
*/
private static function autoReply($content)
{
// 简单关键词匹配
$keywords = [
'你好' => '您好!有什么可以帮助您的吗?',
'谢谢' => '不客气!',
'客服' => '客服工作时间:9:00-18:00\n'.
'客服电话:400-xxx-xxxx',
];
if (isset($keywords[$content])) {
return new Text(['content' => $keywords[$content]]);
}
// 默认回复
return new Text([
'content' => "收到您的消息:{$content}\n\n".
"暂时无法理解您的意思,您可以回复【帮助】查看使用指南"
]);
}
}
七、常见问题解决方案
1. 缓存问题
// Redis 缓存配置
'cache' => [
'driver' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 1,
'prefix' => 'wechat:', // 缓存前缀
],
// 文件缓存配置
'cache' => [
'driver' => 'file',
'path' => RUNTIME_PATH . 'wechat/cache/',
'prefix' => 'wechat_',
],
2. SSL 证书问题
// 临时禁用 SSL 验证(开发环境)
$app = new Application($config);
$app['http']->setDefaultOptions([
'verify' => false,
]);
// 或使用 Guzzle 配置
'guzzle' => [
'timeout' => 10.0,
'verify' => false, // 关闭 SSL 验证
],
3. 多账号管理
class WeChatManager
{
private static $accounts = [];
/**
* 注册账号
*/
public static function register($name, $config)
{
self::$accounts[$name] = new Application($config);
}
/**
* 获取账号实例
*/
public static function account($name)
{
if (!isset(self::$accounts[$name])) {
throw new \Exception("微信账号 {$name} 未注册");
}
return self::$accounts[$name];
}
/**
* 获取所有账号
*/
public static function all()
{
return self::$accounts;
}
}
// 使用
WeChatManager::register('default', $config1);
WeChatManager::register('payment', $config2);
$defaultApp = WeChatManager::account('default');
$paymentApp = WeChatManager::account('payment');
4. 异步处理消息
// 使用队列异步处理消息
$server->setMessageHandler(function($message) {
// 将消息推送到队列
Queue::push(WeChatMessageJob::class, [
'message' => $message->toArray(),
'time' => time()
]);
// 立即回复"处理中"
return new Text(['content' => '消息已收到,正在处理中...']);
});
// 队列任务
class WeChatMessageJob
{
public function fire($job, $data)
{
$message = new Collection($data['message']);
// 处理耗时操作
$result = WeChatMessageHandler::handle($message);
// 如果需要异步回复,可以使用客服消息接口
if ($result) {
$app = WeChatService::officialAccount();
$staff = $app->staff;
$staff->message($result)->to($message->FromUserName)->send();
}
$job->delete();
}
}
八、性能优化建议
1. 缓存优化
- 使用 Redis 替代文件缓存
- 合理设置缓存时间
- 使用连接池管理数据库连接
2. 异步处理
- 耗时操作使用队列处理
- 模板消息、客服消息异步发送
- 图片上传等操作异步处理
3. 监控和日志
- 记录 API 调用耗时
- 监控 access_token 使用情况
- 设置合理的日志级别
4. 错误处理
- 实现熔断机制
- 设置重试策略
- 降级方案
EasyWeChat SDK 提供了全面且易用的微信开发接口,通过合理的封装和优化,可以构建稳定高效的微信应用。