群发文本短消息
群发短消息是公众号开发中比较常见的需求,很多公司都希望有这样的功能,比如发送一条放假通知。这个功能怎么实现呢?
群发短消息分很多种,有图文消息、语音消息、视频消息等,其他几种大同小异,这里以文本消息为例子。
接口说明
在官方帮助文档中找到:根据 OpenID 列表群发【订阅号不可用,服务号认证后可用】
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." }
}Code language: JSON / JSON with Comments (json)
具体说明可以参考:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21
上面的 touser 就是上一节中获取的 data.openid,其他两个参数也比较好理解。
定义实体对象类
public class MessageTextSendParamInfo
{
public string[] touser { set; get; }
public string msgtype { set; get; }
public TextContent text = new TextContent();
public class TextContent
{
public string content { set; get; }
}
}
public class MessageTextSendResultInfo
{
public string errcode { set; get; }
public string errmsg { set; get; }
public string msg_id { set; get; }
public string msg_data_id { set; get; }
}Code language: JavaScript (javascript)
添加 Handler 处理群发文本消息
public class TextMessageSendHandler : WeiXinHandlerBase, IWeiXinHandler
{
private string url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}";
public T DoGet<T>(params string[] param) where T : class
{
throw new NotImplementedException();
}
public T DoPost<T>(params string[] param) where T : class
{
var user = new UserGetHandler().DoGet<UserInfo>();
var messageTextSendParamInfo = new MessageTextSendParamInfo();
messageTextSendParamInfo.touser = user.data.openid;
messageTextSendParamInfo.msgtype = "text";
messageTextSendParamInfo.text.content = param[0];
var json = JsonHelper.SerializeObject(messageTextSendParamInfo);
url = string.Format(url, accessTokenInfo.access_token);
var content = HtmlHelper.HttpPost(url, json);
return JsonHelper.DeserializeJsonToObject<T>(content);
}
}Code language: HTML, XML (xml)
控制器中调用
public ActionResult MessageTextSend(string words)
{
var result = new TextMessageSendHandler().DoPost<MessageTextSendResultInfo>(words);
return Json(result);
}Code language: PHP (php)
调用测试
访问接口地址,words 参数后面的是发送消息内容:
http://ddddddd.imwork.net/home/MessageTextSend?words=%E5%8C%97%E7%9B%9F%E7%BD%91%E6%A0%A1
返回的 JSON 结果:
{"errcode":"0","errmsg":"send job submission success","msg_id":"3147483653","msg_data_id":null}Code language: JSON / JSON with Comments (json)
表示发送成功。
Previous: 05-获取关注我们公众号的微信号的Openid列表
Next: 07-动态类和匿名对象在微信公众号中的应用