You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/Areas/Storage/Helper/TemplateMessageHelper.cs

83 lines
2.9 KiB
C#

2 years ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace DSWeb.Areas.Storage.Helper
{
public class TemplateMessageHelper
{
public static bool SendTemplateMessage(string appid, string templateId, List<Tuple<string, string, string>> values, string toUser, string url, out string message)
{
StringWriter strWriter = new StringWriter();
JsonWriter jwriter = new JsonTextWriter(strWriter);
jwriter.WriteStartObject();
jwriter.WritePropertyName("touser");
jwriter.WriteValue(toUser);
jwriter.WritePropertyName("template_id");
jwriter.WriteValue(templateId);
jwriter.WritePropertyName("url");
jwriter.WriteValue(url);
jwriter.WritePropertyName("data");
//data
jwriter.WriteStartObject();
foreach (var item in values)
{
jwriter.WritePropertyName(item.Item1);
jwriter.WriteStartObject();
jwriter.WritePropertyName("value");
jwriter.WriteValue(item.Item2);
if (!string.IsNullOrWhiteSpace(item.Item3))
{
jwriter.WritePropertyName("color");
jwriter.WriteValue(item.Item3);
}
jwriter.WriteEndObject();
}
jwriter.WriteEndObject();
jwriter.WriteEndObject();
string strJson = strWriter.ToString();
try
{
string token = string.Empty;
string errorMsg = string.Empty;
bool success = Dispatch.Helper.TokenHelper.GetMpToken(appid, out token, out errorMsg);
if (success)
{
//请求模板发送
string postUrl = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
string rtnPost = Dispatch.Helper.WebRequestHelper.DoPost(postUrl, strJson);
var obj = new { errcode = "", errmsg = "", msgid = "" };
var jObj = JsonConvert.DeserializeAnonymousType(rtnPost, obj);
if (jObj.errcode == "0")
{
message = "";
return true;
}
else
{
message = $"{jObj.errmsg},code:{jObj.errcode}";
return false;
}
}
else
{
message = errorMsg;
return false;
}
}
catch (Exception ex)
{
message = $"{ex.Message}";
return false;
}
}
}
}