发送模板消息

参考文档

官方发送模板信息

easywechat插件发送模板信息

1、需要在微信公众号平台模板消息接口,创建测试模板,获取到模板ID(template_id)

模板

2、在TP后台创建view视图,send.html,表单文件填写touser,touser是指粉丝关注的微信号

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手动发送模板信息</title>
</head>
<body>
    <form method="post">
        <table>
            <tr>
                <td>接收人:</td>
                <td>
                    <input type="text" name="touser" placeholder="请输入接收人">
                </td>
            </tr>
            <tr>
                <td>订单号:</td>
                <td>
                    <input type="text" name="code" placeholder="请输入订单号">
                </td>
            </tr>
            <tr>
                <td>课程名称:</td>
                <td>
                    <input type="text" name="title" placeholder="请输入课程名称">
                </td>
            </tr>
            <tr>
                <td>价格:</td>
                <td>
                    <input type="text" name="price" placeholder="请输入价格">
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="发送">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

控制器代码

<?php

namespace app\official\controller;

use think\Controller;
// 微信公众号封装类
use EasyWeChat\Factory;
// 微信公众号配置
use addons\wechat\library\Config;

class Template extends Controller
{
    // 微信属性
    protected $WeChat = null;

    public function __construct()
    {
        parent::__construct();

        $this->WeChat = Factory::officialAccount(Config::load());
    }

    // 手动发送模板信息
    public function send()
    {
        if($this->request->isPost())
        {
            $touser = $this->request->param('touser','','trim');
            $code = $this->request->param('code','','trim');
            $title = $this->request->param('title','','trim');
            $price = $this->request->param('price','','trim');

            $result = $this->WeChat->template_message->send([
                'touser' => $touser,
                'template_id' => 'f46BDEgHOC4Xo9xLbJgfRampQ8g_6X3vQ_5JU256D6E',
                'data' => [
                    'first' => '购买课程成功',
                    'code' => $code,
                    'title' => $title,
                    'price' => $price,
                    'createtime' => date('Y-m-d H:i',time())
                ],
            ]);

            if($result)
            {
                echo '发送成功';
            }else{
                echo '发送失败';
            }

        }

        return $this->fetch();
    }
}
powered by GitbookEdit Time: 2024-06-06 18:25:40