PHP 发送小程序、公众号模板消息

下面是封装好的一个类库,可以直接拿去使用,传进access_token即可

<?php
class Lib_TemplateMessageClient
{
    const API_LIBRARY_LIST      = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list';
    const API_LIBRARY_GET       = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/library/get';
    const API_TEMPLATE_ADD      = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/add';
    const API_TEMPLATE_DEL      = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/del';
    const API_TEMPLATE_SEND     = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send';
    const API_TEMPLATE_LIST     = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/list';
    const API_SERVICE_MESSAGE   = 'https://api.weixin.qq.com/cgi-bin/message/template/send';


    protected $message = [
        'touser'        => '',            // 用户的openid
        'template_id'   => '',            // 模板id
        'url'           => '',            // 跳转的小程序链接【具体说明可看小程序文档】
        'data'          => [],            // 内容【具体说明看文档】
        'form_id'       => '',            // 小程序推送需要到,公众号不需要        
        'miniprogram'   => '',            // 看文档
    ];

    protected $required = ['touser', 'template_id'];

    protected $accessToken = '';

    public function __construct($accessToken = null)
    {
        $this->accessToken = $accessToken ? $accessToken : '';
    }

    /**
     * 获取小程序模板库标题列表
     * @param int $offset
     * @param int $count
     * @return mixed
     */
    public function getLibraryList($offset, $count)
    {
        return $this->httpPost(self::API_LIBRARY_LIST, compact('offset', 'count'));
    }

    /**
     * 获取模板库某个模板标题下关键词库
     * @param string $id
     * @return mixed
     */
    public function get($id)
    {
        return $this->httpPost(self::API_LIBRARY_GET, compact('id'));
    }

    /**
     * 组合模板并添加至帐号下的个人模板库
     * @param string $id
     * @param array $keyword
     * @return mixed
     */
    public function add($id, $keyword = array())
    {
        $params = [
            'id' => $id,
            'keyword_id_list' => $keyword,
        ];
        return $this->httpPost(self::API_TEMPLATE_ADD, $params);
    }

    /**
     * 删除帐号下的某个模板
     * @param string $templateId
     * @return mixed
     */
    public function delete($templateId)
    {
        $params = [
            'template_id' => $templateId,
        ];
        return $this->httpPost(self::API_TEMPLATE_DEL, $params);
    }

    /**
     * 获取帐号下已存在的模板列表
     * @param int $offset
     * @param int $count
     * @return mixed
     */
    public function getTemplates($offset, $count)
    {
        return $this->httpPost(self::API_TEMPLATE_LIST, compact('offset', 'count'));
    }

    /**
     * 发送小程序模版消息
     * @param array $data  // 具体内容可看小程序或公众号模板
     * @return mixed
     */
    public function send($data = array())
    {
        $params = $this->formatMessage($data);

        $this->restoreMessage();

        return $this->httpPost(self::API_TEMPLATE_SEND, $params);
    }

    /**
     * 发送公众号模版消息
     * @param array $data    // 具体内容可看小程序或公众号模板
     * @return mixed
     */
    public function sendServiceMessage($data = array())
    {
        $params = $this->formatMessage($data);

        $this->restoreMessage();

        return $this->httpPost(self::API_SERVICE_MESSAGE, $params);
    }



    protected function restoreMessage()
    {
        $this->message = (new ReflectionClass(__CLASS__))->getDefaultProperties()['message'];
    }

    protected function formatMessage($data = array())
    {
        $params = array_merge($this->message, $data);

        foreach ($params as $key => $value) {
            if (in_array($key, $this->required, true) && empty($value) && empty($this->message[$key])) {
                throw new InvalidArgumentException(sprintf('Attribute "%s" can not be empty!', $key));
            }

            $params[$key] = empty($value) ? $this->message[$key] : $value;
        }

        $params['data'] = $this->formatData($params['data'] ? $params['data'] : array());

        return $params;
    }

    protected function formatData($data = array())
    {
        $formatted = [];

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (isset($value['value'])) {
                    $formatted[$key] = $value;
                    continue;
                }

                if (count($value) >= 2) {
                    $value = [
                        'value' => $value[0],
                        'color' => $value[1],
                    ];
                }
            } else {
                $value = [
                    'value' => strval($value),
                ];
            }

            $formatted[$key] = $value;
        }

        return $formatted;
    }

    public function httpGet($url, $query = array())
    {
        $accessToken = [
            'access_token' => $this->accessToken
        ];

        $params = array_merge($query, $accessToken);

        return App_Func::curl($url, $params, 'GET');
    }

    public function httpPost($url, $data = array())
    {

        $url = $url . '?access_token=' . $this->accessToken;

        return App_Func::curlRaw($url, $data);
    }
}

有帮助到的小伙伴动动你的小指点个关注点个赞 ~

要在 PHP发送微信公众号模板消息,首先需要在微信公众平台中创建一个模板消息并获取模板 ID。接下来,您需要在 PHP 中使用 cURL 库向微信 API 发送 POST 请求,以便将模板消息发送给用户。以下是示例代码: ```php $access_token = 'YOUR_ACCESS_TOKEN'; $template_id = 'YOUR_TEMPLATE_ID'; $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; $data = array( 'touser' => 'OPENID', 'template_id' => $template_id, 'data' => array( 'first' => array('value' => 'Hello, world!'), 'keyword1' => array('value' => 'Keyword 1'), 'keyword2' => array('value' => 'Keyword 2'), 'remark' => array('value' => 'This is a remark.') ) ); $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string) )); $result = curl_exec($ch); curl_close($ch); echo $result; ``` 上述代码中,`$access_token` 是您的公众号访问令牌,`$template_id` 是您创建的模板消息的 ID。您需要将 `OPENID` 替换为要接收模板消息的用户的 OpenID。`$data` 数组包含模板消息的详细信息,其中 `first`、`keyword1`、`keyword2` 和 `remark` 分别对应模板消息中的不同部分。最后,使用 cURL 库将 `$data` 数组作为 JSON 字符串发送到微信 API,然后解析响应以查看是否成功。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值