在 ThinkPHP 5 中,你可以使用 EasyWeChat 这个第三方库来实现微信公众号发送模板消息的功能。下面是一个简单的示例代码:
- 首先,使用 Composer 安装 EasyWeChat:
composer require overtrue/wechat
- 在
config
目录下创建wechat.php
文件,并添加以下配置信息(填入你自己的微信公众号相关信息):
<?php
return [
'official_account' => [
'app_id' => 'your_app_id',
'secret' => 'your_secret',
// ...
],
];
- 创建一个控制器,在其中编写发送模板消息的逻辑。例如,创建
WechatController.php
:
<?php
namespace app\index\controller;
use think\Controller;
use EasyWeChat\Factory;
class WechatController extends Controller
{
public function sendTemplateMessage()
{
$app = Factory::officialAccount(config('wechat.official_account'));
$result = $app->template_message->send([
'touser' => 'openid', // 接收消息用户的 openid
'template_id' => 'your_template_id',
'url' => 'http://example.com', // 跳转链接(可选)
'data' => [
'key1' => 'value1',
// 其他模板数据...
],
]);
if ($result['errcode'] === 0) {
echo "消息发送成功";
} else {
echo "消息发送失败:" . $result['errmsg'];
}
}
}
请注意将上述代码中的 your_app_id
、your_secret
、openid
和 your_template_id
替换为你自己的相关信息。
以上代码假设你已经在微信公众平台设置了相应的模板消息,并获取到了对应的模板ID。在 sendTemplateMessage()
方法中,我们使用 EasyWeChat 的工厂方法创建了一个公众号实例,然后调用其中的 template_message->send()
方法来发送模板消息。
当访问 WechatController.php
中的 sendTemplateMessage()
方法时,将会发送指定的模板消息给目标用户。
请根据具体需求和场景进行适当修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问