. NET development micro-credit Public Platform Example Tutorial _ Practical Tips

Source: Internet
Author: User
Tags cdata sha1 sha1 encryption

The example in this article describes the method of. NET development of a micro-trust public platform. Share to everyone for your reference. The implementation methods are as follows:

One, Description:

Public platform information interface for developers to provide a new way of message processing, only when you apply to become a developer, you can use the development of the public platform, where you need to fill out a URL and a token, these two information also requires you to have your own server (extranet server) resources, The token can be filled by the developer, URL is the interface configuration Information link address, in this article I used to create a simple Web site, in one of the pages of the background program to configure the relevant interface information, and then published to the extranet server, The last link that can be accessed to this page is the URL that should be filled in here.

Second, the interface configuration process:

1. URL Access-Verify signature:

Copy Code code as follows:
Const string Token = "aka";//define a local variable that cannot be modified, and the variables defined here are consistent with the Token that is filled in with the interface configuration information
protected void Page_Load (object sender, EventArgs e)
{
String poststr = "";
Valid ()//check signature, when the information submitted after the page has prompted "You have successfully become a public platform developer, you can use the development of the public platform" this time, then you need to comment out the calibration method, so that the subsequent message back to normal operation
if (Request.HttpMethod.ToLower () = = "POST")///When a general micro-trust user sends a message to the public account, the micro-trust server will post the message to the completed URL
{
Poststr = Postinput ();
if (string. IsNullOrEmpty (POSTSTR) = = False)
{
Writelog (Poststr,server)//Diary
Responsemsg (POSTSTR);
}
}
}
private void Valid ()
{
String echostr = request.querystring["Echostr"]. ToString ();
if (Checksignature ())
{
if (!string. IsNullOrEmpty (ECHOSTR))
{
Response.Write (ECHOSTR);
Response.End ();
}
}
}

Copy Code code as follows:
<summary>
Verifying the micro-letter signature
</summary>
<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);//Dictionary sort
String tmpstr = String. Join ("", arrtmp);
Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1")//SHA1 encryption of the string
Tmpstr = Tmpstr.tolower ()//lowercase conversion of alphabetic parts in string, non-alphabetic characters not processed
Writelog (Tmpstr, Server);//Count Log
if (tmpstr = = signature)//The developer obtains the encrypted string that can be compared with signature to identify the request from the micro-letter. The developer verifies the request by checking the signature, if confirms that the GET request comes from the micro-trust server, returns the ECHOSTR parameter content as it is, the access is valid, otherwise the access fails
{
return true;
}
Else
return false;
}

///<summary>
///Get the data returned by 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);
}

<summary>
Returns the results of a micro-letter message
</summary>
<param name= "Weixinxml" ></param>
private void Responsemsg (string weixinxml)
{
Try
{
XmlDocument doc = new XmlDocument ();
Doc. Loadxml (weixinxml);//Read XML string
XmlElement rootelement = doc. DocumentElement;

XmlNode Msgtype = Rootelement.selectsinglenode ("Msgtype")//Get message type in string

String resxml = "";
if (Msgtype.innertext = = "text")//If the message type is a text message
{
var model = new
{
Tousername = Rootelement.selectsinglenode ("Tousername"). InnerText,
Fromusername = Rootelement.selectsinglenode ("Fromusername"). InnerText,
Createtime = Rootelement.selectsinglenode ("Createtime"). InnerText,
Msgtype = Msgtype.innertext,
Content = Rootelement.selectsinglenode ("Content"). InnerText,
MsgId = Rootelement.selectsinglenode ("MsgId"). InnerText
};
Resxml = "<xml><tousername><! [cdata[] + model. Fromusername + "]]></tousername><fromusername><! [cdata[] + model. Tousername + "]]></fromusername><createtime>" + convertdatetimeint (datetime.now) + "</CreateTime > ";
if (!string. IsNullOrEmpty (model. Content)//If a message is received
{
if (model. Content.contains ("Hello") | | Model. Content.contains ("good") | | Model. Content.contains ("Hi") | | Model. Content.contains ("Hello"))//Hello
{
Resxml = "<msgtype><! [cdata[text]]></msgtype><content><! [cdata[Hello, something please leave a message, I will promptly reply to you. ]]></content><funcflag>0</funcflag></xml> ";
}

}

else//did not receive a message
{
Resxml = "<msgtype><! [cdata[text]]></msgtype><content><! [cdata[, thank you for your attention, something please leave a message. ]]></content><funcflag>0</funcflag></xml> ";
}

Response.Write (Resxml);
}
if (Msgtype.innertext = = "image")//If the message type is a picture message
{
var model = new
{
Tousername = Rootelement.selectsinglenode ("Tousername"). InnerText,
Fromusername = Rootelement.selectsinglenode ("Fromusername"). InnerText,
Createtime = Rootelement.selectsinglenode ("Createtime"). InnerText,
Msgtype = Msgtype.innertext,
Picurl = Rootelement.selectsinglenode ("Picurl"). InnerText,
MsgId = Rootelement.selectsinglenode ("MsgId"). InnerText
};
Resxml = "<xml><tousername><! [cdata[] + model. Fromusername + "]]></tousername><fromusername><! [cdata[] + model. Tousername + "]]></fromusername><createtime>" + convertdatetimeint (datetime.now) + "</CreateTime ><msgtype><! [cdata[news]]></msgtype><articlecount>1</articlecount><articles><item>< title><! [cdata[Welcome your visit! ]]></title><description><! [cdata[Thank you very much for your attention! ]]></description><picurl><! [cdata[http://...jpg]]></picurl><url><! [cdata[http://www.baidu.com/]]></url></item></articles><funcflag>0</funcflag> </xml> ";
Response.Write (Resxml);
}
else//if it's the rest of the message types
{
var model = new
{
Tousername = Rootelement.selectsinglenode ("Tousername"). InnerText,
Fromusername = Rootelement.selectsinglenode ("Fromusername"). InnerText,
Createtime = Rootelement.selectsinglenode ("Createtime"). InnerText,
};
Resxml = "<xml><tousername><! [cdata[] + model. Fromusername + "]]></tousername><fromusername><! [cdata[] + model. Tousername + "]]></fromusername><createtime>" + convertdatetimeint (datetime.now) + "</CreateTime ><msgtype><! [cdata[text]]></msgtype><content><! [cdata[, thank you for my attention, something please leave a message, I will promptly reply to you oh. ]]></content><funcflag>0</funcflag></xml> ";
Response.Write (Resxml);
}
}
catch (Exception ex)
{
Throw ex;
}
Response.End ();

}
<summary>
DateTime converted into 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>
Write log (for tracking), you can put what you want to print into a text file, easy to test
</summary>
public static void Writelog (string strmemo, HttpServerUtility server)
{
string filename = server. MapPath ("/logs/log.txt")//Create a folder name logs in a Web site project (and then create a Web page file in the folder to avoid the site from being published to the server and not seeing the scheduled file)
if (! Directory.Exists (server. MapPath ("//logs//"))
Directory.CreateDirectory ("//logs//");
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 ();
}
}

I hope this article will help you with your. NET programming.

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.