.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 之前我们在做消息回复的时候我们对回复的消息简单做了分类,前面也有讲述如何回复[普通消息类型消息],这里将讲述多媒体消 ...
随机推荐
- Summary on deep learning framework --- Torch7
Summary on deep learning framework --- Torch7 2018-07-22 21:30:28 1. 尝试第一个 CNN 的 torch版本, 代码如下: -- ...
- 剑指offer:顺时针打印矩阵
问题描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数 ...
- [Maven - Java Version] 如何设置Maven的Java版本或者使用不同的JDK版本编译
In pom.xml, defined this maven.compiler.source properties to tell Maven to use Java 8 to compile the ...
- Python 入门小实例笔记
实例1:打印用户输入的姓名与手机号码知识点:编码,获取输入,变量,标准输出 #encoding=utf-8 import time #1.提示用户输入信息 name = input ("请输 ...
- 从身份证管理系统思考企业CMDB的建设
关注嘉为科技,获取运维新知 对大部分中大型的企业来说,CMDB建设对于整个IT服务和IT运维管理的重要性不言而喻,但是目前仍然有非常多的企业无法建设好CMDB. 我最近刚好接触了一个公安系统的朋友,他 ...
- python-Excel读取-合并单元格读取
python-Excel读取-合并单元格读取(后续会补充python-Excel写入的部分) 1. python读取Excel单元格 代码包含读取Excel中数据,以及出现横向合并单元格,以及竖向合并 ...
- C#高级编程(第九版) 知识点梳理
---恢复内容开始--- 第二章 核心C# 2.7 命名空间可以使用别名,但是这样做有什么好处? 2.12 C#预处理器指令 #define DEBUG #if DEBUG Console.Write ...
- 安装Windows 和 Linux双系统(vmware) Centos7
这里我安装的是Windows + Centos 7,如果是要安装Centos 6,步骤一样 一.安装Windows和Linux双系统需要先安装Windows然后安装Linux 解释:这里解释下为什么要 ...
- OO第二单元作业总结【自我反思与审视】
第二单元作业的完成史,就是一部心酸的血泪史…… 多线程的出现为我(们)打开一片广阔的天地,我也在这方天地摸爬滚打,不断成长!如果说第一单元之前还对Java语法有所了解的话,那么这单元学习多线程则完全是 ...
- Matlab-6:解非线性方程组newton迭代法
函数文件: function x=newton_Iterative_method(f,n,Initial) x0=Initial; tol=1e-11; x1=x0-Jacobian(f,n,x0)\ ...