. NET implementation of micro-credit public account interface Development instance Code _ practical Skills

Source: Internet
Author: User
Tags auth cdata httpcontext sha1 sha1 encryption

Speaking of micro-credit public accounts, we will not be unfamiliar with the use of this platform can give the website or system to add a new bright spot, directly to the point, before use must carefully read the official API documentation.
API Document Address: http://mp.weixin.qq.com/wiki/index.php

methods to use. NET implementations:
Micro-letter Interface Address page code:

Copy Code code as follows:

Weixin _wx = new Weixin ();
String poststr = "";
if (Request.HttpMethod.ToLower () = = "POST")
{
Stream s = System.Web.HttpContext.Current.Request.InputStream;
Byte[] B = new Byte[s.length];
S.read (b, 0, (int) s.length);
Poststr = Encoding.UTF8.GetString (b);
if (!string. IsNullOrEmpty (POSTSTR))//Request Processing
{
_wx. Handle (POSTSTR);
}
}
Else
{
_wx. Auth ();
}

Specific processing class

Copy Code code as follows:

<summary>
Micro-trust public platform Operation class
</summary>
public class Weixin
{
private string Token = "My_weixin_token"; Replace it with your own token.
public void Auth ()
{
String echostr = system.web.httpcontext.current.request.querystring["Echostr"];
if (Checksignature ())//Verify that the signature is correct
{
if (!string. IsNullOrEmpty (ECHOSTR))
{
System.Web.HttpContext.Current.Response.Write (ECHOSTR); Returns the original value indicating that the checksum succeeded
System.Web.HttpContext.Current.Response.End ();
}
}
}


public void Handle (string poststr)
{
Encapsulation Request Class
XmlDocument doc = new XmlDocument ();
Doc. Loadxml (POSTSTR);
XmlElement rootelement = doc. DocumentElement;
Msgtype
XmlNode Msgtype = Rootelement.selectsinglenode ("Msgtype");
Received value---> Receive Message Class (also known as message push)
RequestXML requestxml = new RequestXML ();
Requestxml.tousername = Rootelement.selectsinglenode ("Tousername"). InnerText;
Requestxml.fromusername = Rootelement.selectsinglenode ("Fromusername"). InnerText;
Requestxml.createtime = Rootelement.selectsinglenode ("Createtime"). InnerText;
Requestxml.msgtype = Msgtype.innertext;

Different processing according to different types
Switch (requestxml.msgtype)
{
Case "text"://Text message
Requestxml.content = Rootelement.selectsinglenode ("Content"). InnerText;
Break
Case "image"://Picture
Requestxml.picurl = Rootelement.selectsinglenode ("Picurl"). InnerText;
Break
Case "Location"://Position
requestxml.location_x = Rootelement.selectsinglenode ("location_x"). InnerText;
requestxml.location_y = Rootelement.selectsinglenode ("location_y"). InnerText;
Requestxml.scale = Rootelement.selectsinglenode ("Scale"). InnerText;
Requestxml.label = Rootelement.selectsinglenode ("Label"). InnerText;
Break
Case "link"://Link
Break
Case "Event"://Event Push support v4.5+
Break
}

Message reply
Responsemsg (RequestXML);
}


<summary>
Verifying the micro-letter signature
* Sort token, timestamp, nonce three parameters in dictionary order
* Concatenation of three parameter strings into a string for SHA1 encryption
* The developer obtains the encrypted string to compare with the signature, which identifies the request from the micro-letter.
</summary>
<returns></returns>
private bool Checksignature ()
{
String signature = system.web.httpcontext.current.request.querystring["signature"];
string timestamp = system.web.httpcontext.current.request.querystring["timestamp"];
String nonce = system.web.httpcontext.current.request.querystring["nonce"];
Encryption/validation Process:
1. Sort token, timestamp, nonce three parameters in dictionary order
String[] Arrtmp = {Token, timestamp, nonce};
Array.Sort (arrtmp);//Dictionary sort
2. Concatenation of three parameter strings into a string for SHA1 encryption
String tmpstr = String. Join ("", arrtmp);
Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1");
Tmpstr = Tmpstr.tolower ();
3. The developer obtains the encrypted string to compare with the signature, which identifies the request from the micro-letter.
if (tmpstr = = signature)
{
return true;
}
Else
{
return false;
}
}

<summary>
Message reply (micro-message return)
</summary>
<param name= "RequestXML" >the request xml.</param>
private void Responsemsg (RequestXML requestxml)
{
Try
{
String resxml = "";
The main is to call the database for keyword matching automatic reply content, can be written according to their own business situation.
1. Usually, when no instructions are matched, return the Help information
Autoresponse mi = new Autoresponse (requestxml.content, requestxml.fromusername);

Switch (requestxml.msgtype)
{
Case "Text":
A series of actions are performed here to implement the automatic reply content.
String _remsg = mi. Getremsg ();
if (Mi.msgtype = 1)
{
Resxml = "<xml><tousername><! [cdata["+ Requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[news]]></msgtype><content><! [cdata[]]></content><articlecount>2</articlecount><articles> ";
Resxml = mi. Getrepic (Requestxml.fromusername);
Resxml = "</Articles><FuncFlag>1</FuncFlag></xml>";
}
Else
{
Resxml = "<xml><tousername><! [cdata["+ Requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [cdata["+ _remsg +"]]></content><funcflag>1</funcflag></xml> ";
}
Break
Case "Location":
String city = Getmapinfo (requestxml.location_x, requestxml.location_y);
if (city = = "0")
{
Resxml = "<xml><tousername><! [cdata["+ Requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [Cdata[Well, we know where you are. You can: "+ mi." Getdefault () + "]]></content><funcflag>1</funcflag></xml>";
}
Else
{
Resxml = "<xml><tousername><! [cdata["+ Requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [Cdata[Well, we know where you are. You can: "+ mi." Getdefault () + "]]></content><funcflag>1</funcflag></xml>";
}
Break
Case "image":
Text mixed message specific format see the official API "reply to text message"
Break
}

System.Web.HttpContext.Current.Response.Write (Resxml);
Writetodb (RequestXML, Resxml, mi.pid);
}
catch (Exception ex)
{
Writetxt ("Exception:" + ex.) Message + "struck:" + ex. Stacktrace.tostring ());
Wx_logs. Myinsert ("Exception:" + ex.) Message + "struck:" + ex. Stacktrace.tostring ());
}
}


<summary>
Unix Time converted to 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);
}


<summary>
DateTime converted to 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;
}


<summary>
Call Baidu Map, return coordinate information
</summary>
<param name= "Y" > Longitude </param>
<param name= "x" > Latitude </param>
<returns></returns>
public string Getmapinfo (string x, string y)
{
Try
{
string res = string. Empty;
String parame = String. Empty;
String url = "Http://maps.googleapis.com/maps/api/geocode/xml";

Parame = "latlng=" + x + "," + y + "&language=zh-cn&sensor=false";//This key is an individual application
res = webrequestpost (URL, parame);

XmlDocument doc = new XmlDocument ();
Doc. Loadxml (RES);

XmlElement rootelement = doc. DocumentElement;
String Status = Rootelement.selectsinglenode ("status"). InnerText;

if (Status = = "OK")
{
Get City only
XmlNodeList Xmlresults = Rootelement.selectsinglenode ("/geocoderesponse"). ChildNodes;
for (int i = 0; i < Xmlresults.count; i++)
{
XmlNode childnode = xmlresults[i];
if (Childnode.name = = "status") {
Continue
}
String city = "0";
for (int w = 0; w < childNode.ChildNodes.Count; w++)
{
for (int q = 0; q < childnode.childnodes[w]. Childnodes.count; q++)
{
XmlNode childetwo = childnode.childnodes[w]. CHILDNODES[Q];
if (Childetwo.name = = "Long_name")
{
City = Childetwo.innertext;
}
else if (Childetwo.innertext = "locality")
{
return to City;
}
}
}
return to City;
}
}
}
catch (Exception ex)
{
Writetxt ("Map exception:" + ex.) Message.tostring () + "struck:" + ex. Stacktrace.tostring ());
return "0";
}
return "0";
}


<summary>
Post Commit Call Crawl
</summary>
<param name= "url" > Submit address </param>
<param name= "param" > Parameters </param>
<returns>string</returns>
public string webrequestpost (string url, string param)
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes (param);
HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (url + "?" + param);
Req. method = "Post";
Req. Timeout = 120 * 1000;
Req. ContentType = "application/x-www-form-urlencoded;";
Req. ContentLength = BS. Length;

using (Stream Reqstream = req. GetRequestStream ())
{
Reqstream.write (BS, 0, BS.) Length);
Reqstream.flush ();
}

using (WebResponse WR = req. GetResponse ())
{
The content of the received page is processed here
Stream STRM = wr. GetResponseStream ();
StreamReader sr = new StreamReader (STRM, System.Text.Encoding.UTF8);

String line;
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
while (line = Sr. ReadLine ())!= null)
{
Sb. Append (line + System.Environment.NewLine);
}
Sr. Close ();
Strm. Close ();
Return SB. ToString ();
}
}

<summary>
Save this interaction information to a database
</summary>
<param name= "RequestXML" ></param>
<param name= "_xml" ></param>
<param name= "_pid" ></param>
private void Writetodb (RequestXML requestxml, string _xml, int _pid)
{
Weixinmsg WX = new Weixinmsg ();
Wx. Fromusername = Requestxml.fromusername;
Wx. Tousername = Requestxml.tousername;
Wx. Msgtype = Requestxml.msgtype;
Wx. MSG = requestxml.content;
Wx. Creatime = Requestxml.createtime;
Wx. location_x = requestxml.location_x;
Wx. location_y = requestxml.location_y;
Wx. Label = Requestxml.label;
Wx. Scale = Requestxml.scale;
Wx. Picurl = Requestxml.picurl;
wx.reply = _xml;
Wx.pid = _pid;
Try
{
Wx. ADD ();
}
catch (Exception ex)
{
Wx_logs. Myinsert (ex. message);
Ex.message;
}
}
}

Response Class Model

Copy Code code as follows:

#region Micro-Letter Request Class RequestXML
<summary>
Micro-Letter Request Class
</summary>
public class RequestXML
{
private string tousername = "";
<summary>
Message receiver micro-signal, general public platform account Micro-signal
</summary>
public string Tousername
{
get {return tousername;}
set {tousername = value;}
}

private string fromusername = "";
<summary>
Message sending side micro-signal
</summary>
public string Fromusername
{
get {return fromusername;}
set {fromusername = value;}
}

private string createtime = "";
<summary>
Creation time
</summary>
public string Createtime
{
get {return createtime;}
set {createtime = value;}
}

private string msgtype = "";
<summary>
Information Type Geography: location, Text message: text, message type: image
</summary>
public string Msgtype
{
get {return msgtype;}
set {Msgtype = value;}
}

private String content = "";
<summary>
Information content
</summary>
public string Content
{
get {return content;}
set {content = value;}
}

private string location_x = "";
<summary>
Geographical latitude
</summary>
public string location_x
{
get {return location_x;}
set {location_x = value;}
}

private string location_y = "";
<summary>
Geographical longitude
</summary>
public string location_y
{
get {return location_y;}
set {location_y = value;}
}

private string scale = "";
<summary>
Map Zoom Size
</summary>
public string Scale
{
get {return scale;}
set {scale = value;}
}

private String label = "";
<summary>
Location information
</summary>
public string Label
{
get {return label;}
set {label = value;}
}

private string picurl = "";
<summary>
Image links, developers can use HTTP get to obtain
</summary>
public string Picurl
{
get {return picurl;}
set {Picurl = value;}
}
}
#endregion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.