C# 微信模板消息推送(第三方Senparc)
///
/// 微信消息推送模板编号
///
public const string TEMPLATID = "微信公众号模板编号";
public const string APPID = "微信appid";
//模板类
public class MsgTemplateQueue
{
public TemplateDataItem first { get; set; }
public TemplateDataItem keyword1 { get; set; }
public TemplateDataItem keyword2 { get; set; }
public TemplateDataItem keyword3 { get; set; }
public TemplateDataItem keyword4 { get; set; }
public TemplateDataItem remark { get; set; }
}
using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Common;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.AdvancedAPIs;
using Models;
namespace Web.Controllers.App
{
[HiddenApi]
[WebApiActionFillter]
[RoutePrefix("api/v1/push")]
public class ApppushController : ApiController
{
private wechatorderBLL orderBll = new wechatorderBLL();
///
/// 测试推送
///
///
[HttpGet,Route("test")]
public JsonRes Test()
{
var _usercode = AuthTiketHelper.GetUserObject().Name;
//需要推送的参数
var res = Send(_usercode, "7556", "0.01");
return new JsonRes((int)ReturnCode.成功, res, null);
}
#region 发送微信消息
///
/// 发送微信消息
///
/// 姓名
/// 卡号
/// 金额
///
private int Send(string name, string cardnum, string money)
{
var openidlist = new List { };
openidlist.Add("微信openid");
openidlist = openidlist.Distinct().ToList();
//点击详情后跳转后的链接地址,为空则不跳转
var hostUrl = ConfigHelper.GetConfigString("HOST"); //发布站点地址
var linkUrl = $"{hostUrl}/app/#/topUpRecord"; //查看详情地址
//为模版中的各属性赋值
var first = "恭喜您充值成功";
var templateData = new MsgTemplateQueue()
{
first = new TemplateDataItem($"{first}", "#CC0033"),
keyword1 = new TemplateDataItem(name, "#99CC00"),
keyword2 = new TemplateDataItem(cardnum, "#99CC00"),
keyword3 = new TemplateDataItem(money, "#99CC00"),
keyword4 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "#99CC00"),
remark = new TemplateDataItem("充值金额成功", "#0099CC")
};
var sendSuccessOpenidList = new List();
foreach (var openId in openidlist)
{
try
{
var accesstoken = AccessTokenContainer.GetAccessToken(SchoolConfig.WechatConfig.AppId);
var sendResult =
TemplateApi.SendTemplateMessage(accesstoken, openId, WechatConfig.TEMPLATID, linkUrl, templateData);
if (sendResult.errcode == (int)ReturnCode.成功) sendSuccessOpenidList.Add(openId);
}
catch
{
return (int)ReturnCode.异常;
}
}
return sendSuccessOpenidList.Count < 1
? (int)ReturnCode.微信消息推送失败
: (int)ReturnCode.成功;
}
#endregion
}
}