.net回复图片
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Web.Security;
using LYSY.Framework.Commons;
using System.Web.Script.Serialization;
using AgentsWork;
using System.Runtime.Serialization.Json;
using LYSY.Framework.CommonsWapper;
using System.Text.RegularExpressions;
public partial class wxyz : System.Web.UI.Page
{
string Token = "";//你的token
string appid = "";
string appsecret = "";
#region 以下代码只用于第一次验证 验证完后请注释
protected void Page_Load(object sender, EventArgs e)
{
DataSet reply = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Wxsysconfig");
int replynumber=reply.Table1().Rows.Count;
if (replynumber == 0)
{
}
else
{
DataRow dr1 = reply.Tables[0].Rows[0];
Token= Convert.ToString(dr1["token"]);
appid = Convert.ToString(dr1["AppID"]);
appsecret = Convert.ToString(dr1["AppSecret"]);
int istoken = Convert.ToInt32(dr1["istoken"]);
if (istoken == 1)
{
string postStr = "";
if (Request.HttpMethod.ToLower() == "post")
{
System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
postStr = System.Text.Encoding.UTF8.GetString(b);
if (!string.IsNullOrEmpty(postStr))
{
Response.End();
}
//WriteLog("postStr:" + postStr);
}
else
{
Valid();
}
}
else if (istoken == 2)
{
if (Request.HttpMethod == "POST")
{
string weixin = "";
weixin = PostInput();//获取xml数据
if (!string.IsNullOrEmpty(weixin))
{
ResponseMsg(weixin);//调用消息适配器
}
}
}
}
}
#endregion
#region 以下是正常使用时的pageload 请在验证时将其注释 并保证在正常使用时可用
/// <summary>
/// 以下是正常使用时的pageload 请在验证时将其注释 并保证在正常使用时可用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//protected void Page_Load(object sender, EventArgs e)
//{
// if (Request.HttpMethod == "POST")
// {
// string weixin = "";
// weixin = PostInput();//获取xml数据
// if (!string.IsNullOrEmpty(weixin))
// {
// ResponseMsg(weixin);//调用消息适配器
// }
// }
//}
#endregion
#region 获取post请求数据
/// <summary>
/// 获取post请求数据
/// </summary>
/// <returns></returns>
private string PostInput()
{
Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
return Encoding.UTF8.GetString(b);
}
#endregion
#region 消息类型适配器
private void ResponseMsg(string weixin)// 服务器响应微信请求
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(weixin);//读取xml字符串
XmlElement root = doc.DocumentElement;
ExmlMsg xmlMsg = GetExmlMsg(root);
//XmlNode MsgType = root.SelectSingleNode("MsgType");
//string messageType = MsgType.InnerText;
string messageType = xmlMsg.MsgType;//获取收到的消息类型。文本(text),图片(image),语音等。
DataSet wxnumber = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Wxsysreply");
int wx = wxnumber.Table1().Rows.Count;
try
{
switch (messageType)
{
//当消息为文本时
case "text":
if (wx!= 0)
{
DataRow dr1 = wxnumber.Tables[0].Rows[0];
string defaul = Convert.ToString(dr1["defaul"]);
string texttype = "";
if (defaul.Trim() == "")
{
WriteLog(xmlMsg.ToUserName);
WriteLog(xmlMsg.FromUserName);
textCase(xmlMsg, texttype);
}
else
{
WriteLog(xmlMsg.ToUserName);
WriteLog(xmlMsg.FromUserName);
texttype = defaul;
textCase(xmlMsg, texttype);
}
}
break;
case "event":
if (!string.IsNullOrEmpty(xmlMsg.EventName) && xmlMsg.EventName.Trim() == "subscribe")
{
string msg = "";
if (wx!= 0)
{
int nowtime = ConvertDateTimeInt(DateTime.Now);
DataRow dr1 = wxnumber.Tables[0].Rows[0];
string follow= Convert.ToString(dr1["follow"]);
if (follow.Trim() == "")
{
msg = "感谢你关注!";
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
else
{
DataSet datafollow = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Reply WHERE keyword='" + follow + "'");
int followcount = datafollow.Table1().Rows.Count;
if (followcount == 0)
{
msg = "感谢你关注!";
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
else
{
DataRow followdr = datafollow.Tables[0].Rows[0];
string modulekey = Convert.ToString(followdr["module"]);
if (modulekey == "basic")
{
DataSet replytext = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Replytext WHERE rid=" + Convert.ToString(followdr["rid"]));
DataRow drtext = replytext.Tables[0].Rows[0];
msg = Convert.ToString(drtext["content"]);
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
}
}
}
else
{
int nowtime = ConvertDateTimeInt(DateTime.Now);
msg = "感谢你关注!";
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
//刚关注时的时间,用于欢迎词
}
break;
case "image":
break;
case "voice":
break;
case "vedio":
break;
case "location":
break;
case "link":
break;
default:
break;
}
Response.End();
}
catch (Exception)
{
}
}
#endregion
#region 操作文本消息 + void textCase(XmlElement root)
private void textCase(ExmlMsg xmlMsg,String texttype)
{
int nowtime = ConvertDateTimeInt(DateTime.Now);
string content = xmlMsg.Content;
if (content == "授权书")
{
string mediaid = UploadMultimedia();
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[" + mediaid + "]]></MediaId></Image><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
else {
DataSet datacontent = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Reply WHERE keyword='" + content + "'");
int contentnumber = datacontent.Table1().Rows.Count;
if (contentnumber == 0) {
DataSet reply = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Reply WHERE keyword='" + texttype + "'");
int replycount = reply.Table1().Rows.Count;
if (replycount == 1)
{
DataRow dr1 = reply.Tables[0].Rows[0];
string module= Convert.ToString(dr1["module"]);
if (module == "basic")
{
DataSet replytext= ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Replytext WHERE rid="+Convert.ToString(dr1["rid"]));
DataRow drtext = replytext.Tables[0].Rows[0];
string msg = "";
msg = Convert.ToString(drtext["content"]);
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
}
}
else
{
DataRow contentlist = datacontent.Tables[0].Rows[0];
string conentmodule = Convert.ToString(contentlist["module"]);
if (conentmodule == "basic")
{
DataSet replytext = ADOAccessor.Instance.GetAllBySql("SELECT TOP 1 * FROM dbo.Replytext WHERE rid=" + Convert.ToString(contentlist["rid"]));
DataRow drtext = replytext.Tables[0].Rows[0];
string msg = "";
msg = Convert.ToString(drtext["content"]);
string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
Response.Write(resxml);
}
}
}
}
#endregion
//上传图片到公众号
public string UploadMultimedia()
{
string result = "";
string wxurl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + Get_Access_token() + "&type=image";
string filepath = "E:\\web\\lsfwx\\bg.jpg";
WriteLog("上传路径:" + filepath);
WriteLog("acc_token:"+Get_Access_token());
WriteLog("appid:" + appid);
WriteLog("appsecret:" + appsecret);
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
try
{
// byte[] b = myWebClient.UploadFile(string.Format("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type=image", Get_Access_token()), filepath);//调用接口上传文件
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// result = Encoding.Default.GetString(b);//获取返回值
byte[] responseArray = myWebClient.UploadFile(wxurl, "POST",filepath);
result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
WriteLog("上传result:" + result);
UploadMM _mode = JsonHelper.ParseFromJson<UploadMM>(result);
result = _mode.media_id;
}
catch (Exception ex)
{
result = "Error:" + ex.Message;
}
WriteLog("上传MediaId:" + result);
return result;
}
//public string Get_Access_token()
//{
// WebClient webclient = new WebClient();
// string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret + "";
// WriteLog("url:" + url);
// byte[] bytes = webclient.DownloadData(url);//在指定的path上下载
// string result = Encoding.GetEncoding("utf-8").GetString(bytes);//转string
// JavaScriptSerializer js = new JavaScriptSerializer();
// access_token amodel = js.Deserialize<access_token>(result);//此处为定义的类,用以将json转成model
// string a_token = amodel.accesstoken;
// return a_token;
//}
//获取acc_token
public string Get_Access_token()
{
string Str = GetJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret);
WriteLog("str:" + Str);
acc_token acc_token_model = JsonHelper.ParseFromJson<acc_token>(Str);
string a_token = acc_token_model.access_token;
return a_token;
}
protected string GetJson(string url)
{
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Encoding = Encoding.UTF8;
string returnText = wc.DownloadString(url);
if (returnText.Contains("errcode"))
{
//可能发生错误
}
return returnText;
}
public class acc_token
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
public class UploadMM
{
public string media_id { get; set; }
}
#region 将datetime.now 转换为 int类型的秒
/// <summary>
/// datetime转换为unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
private int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
private int converDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
/// <summary>
/// unix时间转换为datetime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
private DateTime UnixTimeToTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
#endregion
#region 验证微信签名 保持默认即可
/// <summary>
/// 验证微信签名
/// </summary>
/// * 将token、timestamp、nonce三个参数进行字典序排序
/// * 将三个参数字符串拼接成一个字符串进行sha1加密
/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
/// <returns></returns>
private bool CheckSignature()
{
string signature = Request.QueryString["signature"].ToString();
string timestamp = Request.QueryString["timestamp"].ToString();
string nonce = Request.QueryString["nonce"].ToString();
string[] ArrTmp = { Token, timestamp, nonce };
Array.Sort(ArrTmp); //字典排序
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
private void Valid()
{
string echoStr = Request.QueryString["echoStr"].ToString();
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
ADOAccessor.Instance.DefaultDataBase.ExecuteNonQuery("UPDATE dbo.Wxsysconfig SET istoken=2 WHERE ID!=0 ");
Response.Write(echoStr);
Response.End();
}
}
}
#endregion
#region 写日志(用于跟踪) + WriteLog(string strMemo, string path = "*****")
/// <summary>
/// 写日志(用于跟踪)
/// 如果log的路径修改,更改path的默认值
/// </summary>
private void WriteLog(string strMemo, string path = "wx.txt")
{
string filename = Server.MapPath(path);
StreamWriter sr = null;
try
{
if (!File.Exists(filename))
{
sr = File.CreateText(filename);
}
else
{
sr = File.AppendText(filename);
}
sr.WriteLine(strMemo);
}
catch
{
}
finally
{
if (sr != null)
sr.Close();
}
}
//#endregion
#endregion
#region 接收的消息实体类 以及 填充方法
private class ExmlMsg
{
/// <summary>
/// 本公众账号
/// </summary>
public string ToUserName { get; set; }
/// <summary>
/// 用户账号
/// </summary>
public string FromUserName { get; set; }
/// <summary>
/// 发送时间戳
/// </summary>
public string CreateTime { get; set; }
/// <summary>
/// 发送的文本内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 消息的类型
/// </summary>
public string MsgType { get; set; }
/// <summary>
/// 事件名称
/// </summary>
public string EventName { get; set; }
}
private ExmlMsg GetExmlMsg(XmlElement root)
{
ExmlMsg xmlMsg = new ExmlMsg()
{
FromUserName = root.SelectSingleNode("FromUserName").InnerText,
ToUserName = root.SelectSingleNode("ToUserName").InnerText,
CreateTime = root.SelectSingleNode("CreateTime").InnerText,
MsgType = root.SelectSingleNode("MsgType").InnerText,
};
if (xmlMsg.MsgType.Trim().ToLower() == "text")
{
xmlMsg.Content = root.SelectSingleNode("Content").InnerText;
}
else if (xmlMsg.MsgType.Trim().ToLower() == "event")
{
xmlMsg.EventName = root.SelectSingleNode("Event").InnerText;
}
return xmlMsg;
}
#endregion
}
.net回复图片的更多相关文章
- java微信开发之接受消息回复图片或者文本
上回说到 接口连接成功,接下来是真正的开发了. 消息的接收,整个过程就是关注订阅号的用户在微信订阅号中发送消息,微信服务器接收到消息,将消息发给开发者的服务器,服务器接收消息然后可以根据内容进行回复. ...
- img src某个php文件输出图片(回复更改图片readfile读取图片等)
在论坛我们经常看到一回复图片就更改等,这功能是怎么实现的呢,其实更验证码道理相同. 新建文件 randimage.php 加入以下代码: <?php $dir='../../images/'; ...
- Java微信公众平台开发(七)--多媒体消息回复之图片回复
之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复[普通消息类型消息],这里将讲述多媒体消息的回复方法,[多媒体消息]包含回复图片消息/回复语音消息/回复视频消息/回复音乐消 ...
- 用java开发微信公众号:接收和被动回复普通消息(三)
上篇说完了如何接入微信公众号,本文说一下微信公众号的最基本功能:普通消息的接收和回复.说到普通消息,那么什么是微信公众号所定义的普通消息呢,微信开发者文档中提到的接收的普通消息包括如下几类: 1.文本 ...
- C#微信公众号开发系列教程六(被动回复与上传下载多媒体文件)
微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...
- C#/ASP.NET MVC微信公众号接口开发之从零开发(三)回复消息 (附源码)
C#/ASP.NET MVC微信接口开发文章目录: 1.C#/ASP.NET MVC微信公众号接口开发之从零开发(一) 接入微信公众平台 2.C#/ASP.NET MVC微信公众号接口开发之从零开发( ...
- .Net实现微信公众平台开发接口(三) 之 “信息回复”
对于每一个POST请求,开发者在响应包(Get)中返回特定XML结构,对该消息进行响应(现支持回复文本.图片.图文.语音.视频.音乐).请注意,回复图片等多媒体消息时需要预先上传多媒体文件到微信服务器 ...
- SQL反模式学习笔记12 存储图片或其他多媒体大文件
目标:存储图片或其他多媒体大文件 反模式:图片存储在数据库外的文件系统中,数据库表中存储文件的对应的路径和名称. 缺点: 1.文件不支持Delete操作.使用SQL语句删除一条记录时,对应的文 ...
- Java微信公众平台开发(八)--多媒体消息回复
转自:http://www.cuiyongzhi.com/post/46.html 之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复[普通消息类型消息],这里将讲述多媒体消 ...
随机推荐
- Windows 控制面板调用命令
使用命令打开 Windows 控制面板指定页面 control.exe /name microsoft.folderoptions 启动资源管理器的 文件夹属性 选项卡 control.exe /na ...
- 如何恢复已禁用的console.log?
如何恢复已禁用的console.log? How to Restore a Disabled console.log?通过将其拉出iframe,在已删除的页面(如twitter)上恢复console. ...
- oracle 11g RAC 的基本操作(一)------启动与关闭
启动RAC 手工启动按照HAS, cluster, database的顺序启动,具体命令如下: 启动HAS(High Availability Services),必须以root用户 [root@or ...
- npm --save-dev --save | -D -S区别
-S就是--save的简写,就行npm默认一个start的字段,你可以不必输入npm run start 而只需输入npm start,这两个效果是一样的.-D就是--save-dev 这样安装的包的 ...
- hadoop移除节点的优雅方式
step 1:使用hdfs-site.xml的配置项,排除节点. <property> <name>dfs.hosts.exclude</name> <val ...
- Redis 持久化RDB 和AOF
一.持久化之全量写入:RDB rdb配置 [redis@6381]$ more redis.conf save 900 1 save 300 10 save 60 10000 dbfilename & ...
- 详解MySQL中concat函数的用法(连接字符串)
MySQL中concat函数 使用方法: CONCAT(str1,str2,…) 返回结果为连接参数产生的字符串.如有任何一个参数为NULL ,则返回值为 NULL. 注意: 如果所有参数均为非二进制 ...
- Vue route的使用
1.route.js文件 import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const router = ne ...
- cron定时任务
1.确认系统安装了cron rpm -aq | grep crontabs 2.认识cron时间格式 3.生成定时任务 crontab -e #进入任务命令编辑模式 30 7,12,20 * * * ...
- DTW动态时间规整算法
目录 1.基本介绍 2.算法原理(理论原理) 2.1 主要术语 2.2 算法由来和改进过程 2.3 DTW算法流程 3.算法DTW和算法HMM的比较 1.基本介绍 DTW:Dynamic Time W ...