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);
    }
}

有幫助到的小夥伴動動你的小指點個關注點個贊 ~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章