欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net 微信模板消息DEMO 已测试好用

程序员文章站 2022-04-10 19:35:03
/// /// 发送模板消息 /// /// AccessToken /// 发送的模板数据 /// public static string SendTe......
    /// <summary>
    /// 发送模板消息
    /// </summary>
    /// <param name="accessToken">AccessToken</param>
    /// <param name="data">发送的模板数据</param>
    /// <returns></returns>
    public static string SendTemplateMsg(string accessToken, string data)
    {
        string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", accessToken);
        HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
        hwr.Method = "POST";
        hwr.ContentType = "application/x-www-form-urlencoded";
        byte[] payload;
        payload = System.Text.Encoding.UTF8.GetBytes(data); //通过UTF-8编码
        hwr.ContentLength = payload.Length;
        Stream writer = hwr.GetRequestStream();
        writer.Write(payload, 0, payload.Length);
        writer.Close();
        var result = hwr.GetResponse() as HttpWebResponse; //此句是获得上面URl返回的数据
        string strMsg = WebResponseGet(result);
        return strMsg;
    }

    public static string WebResponseGet(HttpWebResponse webResponse)
    {
        StreamReader responseReader = null;
        string responseData = "";
        try
        {
            responseReader = new StreamReader(webResponse.GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webResponse.GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }
        return responseData;
    }

    public string testSendTemplateMsg()
    {

        //Dictionary<string, string> oDictionary = new Dictionary<string, string>();
        //oDictionary.Add("touser", "oCbVgt5S-LwIzolY0eOlewEWZ3Yo");
        //oDictionary.Add("template_id", "a11BWcVHomXI-GNdC_kUGkn7Z_HwukuQM3cuPt-3wik");
        //oDictionary.Add("url", "http://weixin.qq.com/download");

        //Dictionary<string, string> ofirst = new Dictionary<string, string>();
        //ofirst
        //oDictionary.Add("data", "http://weixin.qq.com/download");

        string json = "{\"touser\":\"oCbVgt5S-LwIzolY0eOlewEWZ3Yo\",\"template_id\":\"a11BWcVHomXI-GNdC_kUGkn7Z_HwukuQM3cuPt-3wik\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\":{\"value\":\"故障提醒\",\"color\":\"#173177\"},\"performance\":{\"value\":\"CPU故障存在电压不稳\",\"color\":\"#173177\"},\"time\":{\"value\":\"2020-10-01 00:00:00\",\"color\":\"#173177\"},\"remark\":{\"value\":\"\",\"color\":\"#173177\"}}}";
       
        return SendTemplateMsg(Access_token(), json);
    }

public string Access_token()
{

        BLL.BLLEAccess_toen oBLLEAccess_toen = new BLL.BLLEAccess_toen();

        E_Access_toen oE_Access_toen = new E_Access_toen();
        oE_Access_toen = oBLLEAccess_toen.GetList<E_Access_toen>(u => u.ID != 0).OrderByDescending(u => u.ID).FirstOrDefault();
        if (oE_Access_toen != null)
        {
            DateTime t1 = DateTime.Parse(oE_Access_toen.Access_tokenTime.ToString());
            DateTime t2 = DateTime.Parse(DateTime.Now.ToString());
            System.TimeSpan t3 = t2 - t1;  //两个时间相减 。默认得到的是 两个时间之间的天数   得到:365.00:00:00 

            double getSeconds = t3.TotalSeconds; //将这个天数转换成秒数, 返回值是double类型的
            if (getSeconds > 7000)
            {
                //重新获得
                string urlstr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
                string Jsonstr = PostToHttpService(urlstr, "");
                JObject outputObj1 = JObject.Parse(Jsonstr);//将json转为数组


                E_Access_toen ooE_Access_toen = new E_Access_toen();
                ooE_Access_toen.Access_token = outputObj1["access_token"].ToString();
                ooE_Access_toen.Access_tokenTime = DateTime.Now;
                ooE_Access_toen.Guid = UtilsHelper.NewGuid();
                oBLLEAccess_toen.Add(ooE_Access_toen);
                return outputObj1["access_token"].ToString();
            }
            else
            {
                return oE_Access_toen.Access_token;
            }
        }
        else
        {
            //重新获得
            string urlstr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            string Jsonstr = PostToHttpService(urlstr, "");
            JObject outputObj1 = JObject.Parse(Jsonstr);//将json转为数组


            E_Access_toen ooE_Access_toen = new E_Access_toen();
            ooE_Access_toen.Access_token = outputObj1["access_token"].ToString();
            ooE_Access_toen.Access_tokenTime = DateTime.Now;
            ooE_Access_toen.Guid = UtilsHelper.NewGuid();
            oBLLEAccess_toen.Add(ooE_Access_toen);
            return outputObj1["access_token"].ToString();

        }


    }

本文地址:https://blog.csdn.net/weixin_43044132/article/details/109245863

相关标签: .net MVC json