14-发送模板消息

发送模板消息

在上一节课中,我们获取到了当前公众号的模板 ID,接下来就可以使用这个模板来发送模板消息。

接口说明

HTTP 请求方式:POST

https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

替换模板占位符时,还可以为每个字段设置显示颜色。

Handler 实现

public class TemplateSendHandle : WeiXinHandlerBase, IWeiXinHandler
{
    private string url = "https://api.weixin.qq.com/cgi-bin/message/template/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 uploadUrl = string.Format(url, accessTokenInfo.access_token);
        var user = new UserGetHandler().DoGet<UserInfo>();

        var post = new
        {
            touser = user.data.openid[0], // 发给第一个人
            template_id = "coA2OijGsDxN3b2i48D0vaPLd5BraRQnDYcJ8MazzAc",
            url = "http://www.bamn.cn",
            data = new
            {
                first = new { value = "恭喜你购买成功!", color = "#173177" },
                orderMoneySum = new { value = "1000!", color = "#183177" },
                orderProductName = new { value = "苹果电脑 MACBOOK PRO", color = "#173177" },
                Remark = new { value = "备注,分12期还款", color = "#173377" }
            }
        };

        var json = JsonHelper.SerializeObject(post);
        var resultjson = HtmlHelper.HttpPost(uploadUrl, json);
        var output = JsonHelper.DeserializeJsonToObject<T>(resultjson);
        return output;
    }
}Code language: HTML, XML (xml)

控制器中调用

public ActionResult TemplateSend()
{
    var result = new TemplateSendHandle().DoPost<dynamic>();
    return Json(result);
}Code language: PHP (php)

调用测试

访问地址:

http://xxxxx.imwork.net/home/TemplateSend

返回结果:

{"errcode":0,"errmsg":"ok","msgid":451307458980315137}Code language: JSON / JSON with Comments (json)

errcode 为 0 表示发送成功。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注