微信開發之向用戶群發文本消息


本文目錄

  1. 給單一用戶發文本消息
  2. 給多個用戶發文本消息
  3. 給所有用戶發文本消息
  4. 有更好的方案嗎?
  5. 遇到的問題
  6. 小結


微信提供的api,對於針對用戶openid發消息的話,沒有向所有關注者群發消息的接口,但提供了向單一用戶和多用戶發文本消息的接口,我們可以基於此開發向所有用戶群發消息的接口。
補充:后面我發現其實可以有更好的實現方案,詳看 ‘有更好的方案嗎?‘。

文中遇到部分的接口請查看上一文:

微信開發之獲取用戶詳細列表


1、 給單一用戶發文本消息

微信開發文檔入口:

客服接口-發消息

我的代碼接口:

/**
 * 向一個粉絲發送消息
 */
public function sendMsgToOne($openid, $content)
{
    $access_token = $this->getAccessToken();
    if (!$access_token) {
        return false;
    }

    $url ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
    $post_arr = [
                    'touser' => $openid,
                    'msgtype' => 'text',
                    'text' => ['content'=>$content]
                ];
    $post_str = json_encode($post_arr, JSON_UNESCAPED_UNICODE);
    $return = httpRequest($url, 'POST', $post_str);
    $wxdata = json_decode($return, true);
    if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) {
        $this->setError('微信錯誤碼:'.$wxdata['errcode'].',錯誤信息:'.$wxdata['errmsg']);
        return false;
    }

    return true;
}


2、 給多個用戶發文本消息

微信開發文檔入口:

根據OpenID列表群發【訂閱號不可用,服務號認證后可用】

我的代碼接口:

/**
 * 指定一部分人群發消息
 * @param array $openids
 * @param string $content
 * @return boolean
 */
public function sendMsgToMass($openids, $content)
{
    $access_token = $this->getAccessToken();
    if (!$access_token) {
        return false;
    }

    $url ="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={$access_token}";
    $post_arr = [
                    'touser' => $openids,
                    'msgtype' => 'text',
                    'text' => ['content'=>$content]
                ];
    $post_str = json_encode($post_arr, JSON_UNESCAPED_UNICODE);
    $return = httpRequest($url, 'POST', $post_str);
    $wxdata = json_decode($return, true);
    if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) {
        $this->setError('微信錯誤碼:'.$wxdata['errcode'].',錯誤信息:'.$wxdata['errmsg']);
        return false;
    }

    return true;
}


3、 給所有用戶發文本消息

利用上面的兩個接口,實現一個統一的接口,如下:
下面接口入參$openids支持數組和字符串,字符串支持多個openid用連接,具體請看代碼吧。

/**
 * 發送消息,自動識別id數
 * @param string or array $openids
 * @param string $content
 * @return boolean
 */
public function sendMsg($openids, $content)
{
	if (empty(openids)) {
    	return true;
    }
    if (is_string($openids)) {
        $openids = explode(',', $openids);
    }

    if (count($openids) > 1) {
        $result = $this->sendMsgToMass($openids, $content);
    } else {
        $result = $this->sendMsgToOne($openids[0], $content);
    }

    if ($result === false) {
        return false;
    }

    return true;
}

下面實現向所有用戶群發消息, 使用的時候請判斷接口返回是否為false,若是,可用getError()獲取詳細錯誤信息,具體可參考上一文 微信開發之獲取用戶詳細列表

/**
 * 給所有粉絲發消息
 * @param string $content
 * @return boolean
 */
public function sendMsgToAll($content)
{
    $next_openid = '';
    do {
        $id_list = $this->getFanIdList($next_openid);
        if ($id_list === false) {
            return false;
        }

        $result = $this->sendMsg($id_list['data']['openid'], $content);
        if ($result === false) {
            return false;
        }

        $next_openid = $id_list['next_openid'];
    } while($id_list['count']);

    return true;
}


4、 有更好的方案嗎?

微信開發文檔入口:

根據標簽進行群發【訂閱號與服務號認證后均可用】

我一直以為微信沒有提供直接向所有用戶群發的接口,其實是有的!
在上面的微信文檔中,我發現,這個接口竟然被歸類在根據標簽進行群發里面。不過不需要用標簽這個概念,里面有個關鍵的變量是is_to_all,把它置為 true 即可。
這樣子可以節省上一接口中的相關api的調用次數,更能提高web響應的性能!

我的代碼接口:

/**
 * 給所有粉絲發消息
 * @param string $content
 * @return boolean
 */
public function sendMsgToAll($content)
{
    $access_token = $this->getAccessToken();
    if (!$access_token) {
        return false;
    }

    $url ="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={$access_token}"; 
    $post_arr = [
                    'filter' => ['is_to_all'=>true, 'tag_id'=>0],
                    'msgtype' => 'text',
                    'text' => ['content'=>$content]
                ];
    $post_str = json_encode($post_arr, JSON_UNESCAPED_UNICODE);
    $return = httpRequest($url, 'POST', $post_str);
    $wxdata = json_decode($return, true);
    if ($this->checkError($wxdata, $url)) {
         return false;
    }

    return true;
}


5、 遇到的問題

在向單一用戶發消息的時候,遇到報45015錯誤的接收報文:

{
    "errcode":45015,
    "errmsg":"response out of time limit or subscription is canceled hint: [***]"
}

原因是當用戶微信不活躍時間超過48小時,不會將信息推送到用戶微信公眾號。

: 上面說法來源於騰訊官方,評論區園友實際測試也是,謝謝這位朋友指出。
為了驗證這個說法的正確性,我試着先向公眾號發個信息,果然公眾號可以向單一用戶推送消息了。


小結

簡單利用微信向單一用戶和多用戶的發消息接口,實現向所有用戶群發消息,但利用標簽接口群發效率回更好哦。其他的語音、圖文等消息發送也是類似的。


主要參考文檔

微信開發文檔:https://mp.weixin.qq.com/wiki

-end-


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM