C#微信接口之推送模板消息功能示例
程序员文章站
2023-12-14 09:31:28
本文实例讲述了c#微信接口之推送模板消息功能。分享给大家供大家参考,具体如下:
public string sendtempletmessge()
{...
本文实例讲述了c#微信接口之推送模板消息功能。分享给大家供大家参考,具体如下:
public string sendtempletmessge() { string strreturn = string.empty; try { #region 获取access_token string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret"; webrequest request = webrequest.create(@apiurl); request.method = "post"; webresponse response = request.getresponse(); stream stream = response.getresponsestream(); encoding encode = encoding.utf8; streamreader reader = new streamreader(stream, encode); string detail = reader.readtoend(); var jd = jsonconvert.deserializeobject<wxapi>(detail); string token = (string)jd.access_token; #endregion #region 组装信息推送,并返回结果(其它模版消息于此类似) string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token; string temp = "{\"touser\": \"" + userinfo.openid + "\"," + "\"template_id\": \"f3krrjjeyldf4tndtg-ojervgedgjjdxcy4t9kuwm70\", " + "\"topcolor\": \"#ff0000\", " + "\"data\": " + "{\"first\": {\"value\": \"您好,您有一条回款通知信息\"}," + "\"keyword1\": { \"value\": \"单位名称\"}," + "\"keyword2\": { \"value\": \"日期\"}," + "\"keyword3\": { \"value\": \"金额\"}," + "\"keyword4\": { \"value\": \"业务员\"}," + "\"remark\": {\"value\": \"\" }}}"; #endregion //核心代码 getresponsedata(temp, @url); strreturn = "推送成功"; } catch (exception ex) { strreturn = ex.message; } return strreturn; } /// <summary> /// 返回json数据 /// </summary> /// <param name="jsondata">要处理的json数据</param> /// <param name="url">要提交的url</param> /// <returns>返回的json处理字符串</returns> public string getresponsedata(string jsondata, string url) { byte[] bytes = encoding.utf8.getbytes(jsondata); httpwebrequest request = (httpwebrequest)webrequest.create(url); request.method = "post"; request.contentlength = bytes.length; request.contenttype = "json"; stream reqstream = request.getrequeststream(); reqstream.write(bytes, 0, bytes.length); //声明一个httpwebrequest请求 request.timeout = 90000; //设置连接超时时间 request.headers.set("pragma", "no-cache"); httpwebresponse response = (httpwebresponse)request.getresponse(); stream streamreceive = response.getresponsestream(); encoding encoding = encoding.utf8; streamreader streamreader = new streamreader(streamreceive, encoding); string strresult = streamreader.readtoend(); streamreceive.dispose(); streamreader.dispose(); return strresult; }
涉及到的实体:
public class wxapi { public string access_token { set; get; } }
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结》
希望本文所述对大家c#程序设计有所帮助。