C#微信接口之推送模板消息功能示例
本文实例讲述了C#微信接口之推送模板消息功能。分享给大家供大家参考,具体如下:
publicstringSendTempletMessge() { stringstrReturn=string.Empty; try { #region获取access_token stringapiurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret"; WebRequestrequest=WebRequest.Create(@apiurl); request.Method="POST"; WebResponseresponse=request.GetResponse(); Streamstream=response.GetResponseStream(); Encodingencode=Encoding.UTF8; StreamReaderreader=newStreamReader(stream,encode); stringdetail=reader.ReadToEnd(); varjd=JsonConvert.DeserializeObject(detail); stringtoken=(String)jd.access_token; #endregion #region组装信息推送,并返回结果(其它模版消息于此类似) stringurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; stringtemp="{\"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(Exceptionex) { strReturn=ex.Message; } returnstrReturn; } /// ///返回JSon数据 /// ///要处理的JSON数据 /// 要提交的URL /// 返回的JSON处理字符串 publicstringGetResponseData(stringJSONData,stringUrl) { byte[]bytes=Encoding.UTF8.GetBytes(JSONData); HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url); request.Method="POST"; request.ContentLength=bytes.Length; request.ContentType="json"; Streamreqstream=request.GetRequestStream(); reqstream.Write(bytes,0,bytes.Length); //声明一个HttpWebRequest请求 request.Timeout=90000; //设置连接超时时间 request.Headers.Set("Pragma","no-cache"); HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); StreamstreamReceive=response.GetResponseStream(); Encodingencoding=Encoding.UTF8; StreamReaderstreamReader=newStreamReader(streamReceive,encoding); stringstrResult=streamReader.ReadToEnd(); streamReceive.Dispose(); streamReader.Dispose(); returnstrResult; }
涉及到的实体:
publicclassWXApi { publicstringaccess_token{set;get;} }
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。