Home >WeChat Applet >WeChat Development >WeChat public platform development - group messaging

WeChat public platform development - group messaging

高洛峰
高洛峰Original
2017-02-20 14:44:142700browse

This article mainly introduces the development of mass messaging on the WeChat public platform. Detailed information is compiled here to explain the process of mass messaging on the WeChat public platform. Friends in need can refer to the following

1. Purpose

Finished sending group messages in the WeChat official account. Here just complete the simple text sending. You can also send voice pictures, etc., but the data format is different. There is a link below to query the data sending format of the data type.

2. The process of sending group text messages

  1. Get a test public account (those who have an account do not need a test account, but formal accounts have more restrictions )

  2. Users follow the public account above

  3. Get our access_token through appid and appsecret

  4. Group text messages through access_token

3. Get a test public account + follow the public account

1), get a public test account

Visit the above link and select "Interface Test Number Application" to directly open http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index through WeChat client Scan the QR code to log in.

After logging in, you can get the information of a test public account. There are mainly two parameters, appId and appsecret, which will uniquely identify an official account, and they need to be used as parameters to obtain the user's information. ,

WeChat public platform development - group messaging

2) Configuring interface information

You can refer to the WeChat access instructions for this step. This page provides an example download of php, which is very simple and basically Just modify the custom TOKEN, and then put the verification page on your own server.

Here I provide an example of what I did:

Prepare resources:

Domain name + space (mine is sae space + Wanwang domain name), PHP for verification only File

I created a wx_sample.php

wx_sample.php

<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
 public function valid()
 {
  $echoStr = $_GET["echostr"];

  //valid signature , option
  if($this->checkSignature()){
   echo $echoStr;
   exit;
  }
 }

 public function responseMsg()
 {
  //get post data, May be due to the different environments
  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

   //extract post data
  if (!empty($postStr)){
    /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
     the best way is to check the validity of xml by yourself */
    libxml_disable_entity_loader(true);
     $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA);
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $keyword = trim($postObj->Content);
    $time = time();
    $textTpl = "<xml>
       <ToUserName><![CDATA[%s]]></ToUserName>
       <FromUserName><![CDATA[%s]]></FromUserName>
       <CreateTime>%s</CreateTime>
       <MsgType><![CDATA[%s]]></MsgType>
       <Content><![CDATA[%s]]></Content>
       <FuncFlag>0</FuncFlag>
       </xml>";    
    if(!empty( $keyword ))
    {
      $msgType = "text";
     $contentStr = "Welcome to wechat world!";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     echo $resultStr;
    }else{
     echo "Input something...";
    }

  }else {
   echo "";
   exit;
  }
 }
  
 private function checkSignature()
 {
  // you must define TOKEN by yourself
  if (!defined("TOKEN")) {
   throw new Exception(‘TOKEN is not defined!‘);
  }
  
  $signature = $_GET["signature"];
  $timestamp = $_GET["timestamp"];
  $nonce = $_GET["nonce"];
    
  $token = TOKEN;
  $tmpArr = array($token, $timestamp, $nonce);
  // use SORT_STRING rule
  sort($tmpArr, SORT_STRING);
  $tmpStr = implode( $tmpArr );
  $tmpStr = sha1( $tmpStr );
  
  if( $tmpStr == $signature ){
   return true;
  }else{
   return false;
  }
 }
}

?>

in the space root directory pointed to by the domain name and then filled in Configuration information Token (must be consistent with the token in wx_sample.php above), URL (the address of wx_sample.php)

WeChat public platform development - group messaging

Then submit it

If the prompt fails, please check the Token and URL [If it is your own domain name and space, please register; Baidu sae and Sina sae need to apply for it yourself and pass the certification (just take a photo of your hand holding the ID and upload it, it is very simple and the shortest It will take 2 days), this step is necessary】

3) Configure the JS interface security domain name

Be sure not to include a protocol when filling in this domain name, for example http://www.sagosoft. com/; This is wrong, this is a URL, not a domain name

The domain name should be similar to www.sagosoft.com [Otherwise, invalid url domain will be prompted when accessing WeChat js-sdk]

WeChat public platform development - group messaging

4) Follow the public account

Only when a user follows this public account can he authorize a third party to log in and obtain user information by opening a link with public account information. operation. Therefore, we also need to use our WeChat to follow the WeChat ID. The operation is as follows:

It is still the page that jumped after successful login. We can see that the page has a QR code. We can scan the Follow the QR code. If you follow successfully, there will be one more user's information in the "User List" on the right. As shown in the figure below:

WeChat public platform development - group messaging

5) Configure the callback function

We access third-party web pages (that is, our own web pages) on the WeChat client When using WeChat, we can use the WeChat web page authorization mechanism. We not only need the appid and appsecret obtained previously, but also need to have the domain name settings for the callback after the user authorizes, that is, where the page will jump to after the user authorizes. The specific configuration is as follows:

Still on the page just now, there is a "Web page authorization to obtain basic user information", click on the subsequent modification

WeChat public platform development - group messaging

Fill in the callback domain name:

The domain name is the root domain name configured above. If the URL you filled in in the "Interface Configuration Information" above is zcr.sinaaappc.com/wx_sample.php, just fill in zcr.sinaaappc here. .com will do.

WeChat public platform development - group messaging

If your URL has not been blacklisted,

WeChat public platform development - group messaging

WeChat public platform development - group messaging will appear at the top

Note:

1. What is filled in here is the domain name (a string), not the URL, so please do not add http:// and other protocol headers;
2. Authorization The callback domain name configuration specification is the full domain name. For example, the domain name that requires web page authorization is: www.qq.com. After configuration, the pages under this domain name are http://www.qq.com/music.html and http://www.qq .com/login.html can perform OAuth2.0 authentication. But ttp://pay.qq.com, http://music.qq.com, http://qq.com cannot perform OAuth2.0 authentication

At this point, we are done After obtaining and configuring the public account test account, users have already followed the WeChat public account.

4. Obtain our access_token through appid and appsecret

Access_token is the globally unique ticket of the official account. The official account needs to use access_token when calling each interface. Developers need to store it properly. At least 512 characters of space must be reserved for access_token storage. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the last access_token to become invalid.

Getting method:

http request method: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Parameter Description


##ParameterIs it necessaryDescriptiongrant_typeYesGet access_token fill in client_credentialappidYesThird-party user’s unique credentialsecret is the third-party user’s unique credential key, that is, appsecret
Return instructions

Under normal circumstances, WeChat will return the following JSON data packet to the public account:

{"access_token":"ACCESS_TOKEN","expires_in" :7200}


ParameterDescriptionaccess_tokenObtained voucherexpires_inVoucher validity time, unit: seconds##

错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):

{"errcode":40013,"errmsg":"invalid appid"} 

例子:

获取access_token:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx41cb8dbd827a16e9&secret=d4624c36b6795d1d99dcf0547af5443d

返回数据:

{
 "access_token": "qR5UK2vMf5aTHV8e-uB10FZW0caTZm_1kbkUe4OPK2ILVvNaoa7pLzYWqLUAmx6Sjq1E7pKHrVAtuG0_1MPkqmDfOkm2750kaLWNk59DS-iDOpjjxompJtXa3WhbN5FKRWNhADAVAR",
 "expires_in": 7200
}

5、通过access_token群发短信

  在公众平台网站上,为订阅号提供了每天一条的群发权限,为服务号提供每月(自然月)4条的群发权限。而对于某些具备开发能力的公众号运营者,可以通过高级群发接口,实现更灵活的群发能力。

请注意:

1、对于认证订阅号,群发接口每天可成功调用1次,此次群发可选择发送给全部用户或某个分组;
2、对于认证服务号虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败;
3、具备微信支付权限的公众号,在使用群发接口上传、群发图文消息类型时,可使用标签加入外链;
4、开发者可以使用预览接口校对消息样式和排版,通过预览接口可发送编辑好的消息给指定用户校验效果。
 

 1)根据分组进行群发【订阅号与服务号认证后均可用】

调用接口:

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN 在body添加如下数据(以JSON格式数据发送)——发送其他格式数据,只需要改里面参数信息即可,具体可查看微信官方文档:

{
 "filter":{
  "is_to_all":false,
  "group_id":2
 },
 "text":{
  "content":"CONTENT"
 },
 "msgtype":"text"
}

参数说明:


参数 是否必须 说明
filter 用于设定图文消息的接收者
is_to_all 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户
group_id 群发到的分组的group_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写group_id
mpnews 用于设定即将发送的图文消息
media_id 用于群发的消息的media_id
msgtype 群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video,卡券为wxcard
title 消息的标题
description 消息的描述
thumb_media_id 视频缩略图的媒体ID

例子:发送给所有人

url:

https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=KBoNONaJZ4-KhafQVJoQ6VBX0F-bls7nAsJBn8Fy7GLwav4Be1lRJcob1RHH6wW35IxxFwkJnZfnc-On9EQITg3oxEWUw7O2YyVW9naDknu6PQX9fnSmQcr8ojTK8Ug-HDTcAAABXN

发送的json数据:发送给所有人

{
 "filter":{
  "is_to_all":true
 },
 "text":{
  "content":"CONTENT"
 },
 "msgtype":"text"
}

返回数据:

{
 "errcode": 0,
 "errmsg": "send job submission success",
 "msg_id": 1000000003
}

参数意义:

 

参数 说明
type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),图文消息为news
errcode 错误码
errmsg 错误信息
msg_id 消息发送任务的ID
msg_data_id 消息的数据ID,该字段只有在群发图文消息时,才会出现。可以用于在图文分析数据接口中,获取到对应的图文消息的数据,是图文分析数据接口中的msgid字段中的前半部分,详见图文分析数据接口中的msgid字段的介绍。

错误码及其以及查询:

使用postman模拟https请求发送如下图所示:

WeChat public platform development - group messaging

2)根据OpenID列表群发【订阅号不可用,服务号认证后可用】

发送的http请求url:(注意:和上面的不同)

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN

数据格式:

{
 "touser":[
 "OPENID1",
 "OPENID2"
 ],
 "msgtype": "text",
 "text": { "content": "hello from boxer."}
}

其中 OPENID1和OPENID2是我们要发送的微信用户openId(用户的唯一标示)。

例子:

发送"oF3PcsnsrMiJzEwalZZbAfWQpxCI","oF3PcshH1CUIhR_WYau6swUiPzlw" 两个用户。

内容为:hello from boxer.欢迎来到百度

url:

https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=wRyTbnsiu18ssEhMPLf4bDfeT-Bt6e6tgR4CQGVLBipRcyJPkdAKPYfM6-qkKuHUN8uRKJh6Xvm0OuAdFgqOo8Ru8hoDxl-cGc9bh-ezJb2ZUcJSnQk2s416zI8kbEOfOGYdAFARJB 

json数据:

{
 "touser":[
 "oF3PcsnsrMiJzEwalZZbAfWQpxCI",
 "oF3PcshH1CUIhR_WYau6swUiPzlw"
 ],
 "msgtype": "text",
 "text": { "content": "hello from boxer.<a href=‘http://www.php.cn/‘>欢迎希沃学院</a>"}
}

返回数据:

{
 "errcode": 0,
 "errmsg": "send job submission success",
 "msg_id": 3147483654
}

使用postman模拟发送请求如下:

WeChat public platform development - group messaging

微信号接收到的内容:

WeChat public platform development - group messaging


更多WeChat public platform development - group messaging相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn