Straight into the subject:
Micro-Credit public account development document, the official version (Https://mp.weixin.qq.com/wiki), believe me, I have been unable to spit slot to write this document, I really want to chop this keyboard, but after the start found that the original keyboard is my own money to buy .... It's embarrassing.
Nonsense do not say, directly say how to deploy, how to develop.
First, you have to have a public platform account, OK, start to count the hole.
The first pit, do not think that is not the enterprise number can not be developed, may apply for test number, than the so-called subscriber number interface a lot.
After entering the background management, click the Developer tool, you can see the public platform test account, direct access can be. Start filling in your own configuration.
Pay attention to the graffiti section, this part of the program must be configured Dongdong, if not configured, this is certainly unsuccessful.
The second pit , of course, you are so configured also must not be successful, do not ask me why. Not a few ...
Please do not think Penguin game, this is true, must be 80 port, in fact, also published a domain name site can be. Because the domain name website All is 80 ports come out, continues to say the topic.
Penguin told us, to use the micro-letter account, must have a server, and then configure our release of the site on the line, please note that token is set itself, this is not automatically generated, set themselves. URL is the name of the site we published
The third Pit, the website does not publish, the interface configuration information is forever configuration not past, remembers, is forever.
JS interface Secure domain name, this please refer directly to the document (http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html).
JS interface Security Domain name is to download the image, call the micro-letter image interface, etc., such as when you need to call the camera, or to say that you need to upload photos, this time the need for JS security interface, about the specific content is not a detailed description.
In the version background of the micro-credit public account test number, there is an Experience Interface permission table This item must also be configured. It is not necessarily configured, but this interface can be used to obtain some information about the users of the micro-trust. It is worth reminding that each of the public accounts corresponding to each ID is unique, that is, even if the site intranet unchanged, if the public number, then, this time the micro-credit data is not common, but only relative to the public number.
Fourth Pit, the application of micro-letter Web page authorization, here's the Web page authorized user basic information, this itself no problem, but no hint will have a problem.
Here's the URL, please note that there must be no www, and there is no backslash , that is, the callback format of the URL here is abc.com OK, please remember this format, must do so. OK, the server for now, temporarily start talking in code.
First from the server authentication. This is an example in the official website, but PHP, in fact, the first is to verify a random number, and then in the case of post, detect the return value can be. Directly on the code
Public ActionResult Index () {if (Request.HttpMethod.ToLower () = "POST") {if (Checksignature ())//Verify that the server passes {get Menulist ()//Load Menu} else {Response.Write ("
The public platform then customizes the menu with permissions, but once the custom menu is started, the original manually edited menu is not available, that is, if the server is validated, it must be controlled with its own code.
Let's take a look at the Getmenulist () method, which is actually very simple, just by virtue of a JSON format string. Then call the micro-letter interface. public void Getmenulist ()
<em id= "__mcedel" > {
string weixin1 = "";
Weixin1 = @ ' {' button '
: [
{
] ' type ': ' Click ' ', ' ' Name '
: ' Hello! ', ' '
key ' ': ' Hello ' '
},
{'
type ': ' View ', ' name '
: ' Company profile ', '
url ' ': ' http://www.xnfhtech.com '
},
{ "" Name ":" "
Product Introduction", "
Sub_button" ": [
{
" "type" ":" "click"
"" "", "" Key ': ' ' P1 '
}, {' Type ': ' Click ', ' '
name '
: '
product 2 ', ' '
key ' ': ' P2 ' '
}]
} ] }";
String access_token = Tools.WA_GetAccess_Token.IsExistAccess_Token ();
String i = this. Menucreate (menu, access_token);
Response.Write (i);
} <br><br>
</em>
public string Menucreate (string Menujson, String access_token) {JavaScriptSerializer Jss = new JavaScriptSerializer ()
;
String setmenuurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}"; Setmenuurl = string.
Format (Setmenuurl, Access_token);//Get token, patchwork URL string resptext = Webrequestpostorget (Setmenuurl, Menujson);
dictionary<string, object> respdic = (dictionary<string, object>) jss.deserializeobject (RespText); return respdic["Errcode"]. ToString ();//Return 0 Publish success}///<summary>///post/get commit call crawl///</summary>///<param name= "url" > Submit Address </param>///<param name= "param" > Parameters </param>///<returns>string</returns> Public
String Webrequestpostorget (String sURL, String sparam) {byte[] bt = System.Text.Encoding.UTF8.GetBytes (Sparam);
Uri Uriurl = new Uri (sURL); HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (uriurl);//httpwebrequest req = (HttpWebRequest) Httpwebrequest.create (URL + (uRl. IndexOf ("?") >-1? "" : "?")
+ param); Req.
method = "Post"; Req.
Timeout = 120 * 1000; Req.
ContentType = "application/x-www-form-urlencoded;"; Req. ContentLength = Bt.
Length; using (Stream Reqstream = req. GetRequestStream ())//using use to release the memory inside the using segment {reqstream.write (BT, 0, Bt.
Length);
Reqstream.flush (); The try {using (WebResponse res = req. GetResponse ()) {//Here the content of the received page is processed Stream resstream = Res.
GetResponseStream ();
StreamReader Resstreamreader = new StreamReader (Resstream, System.Text.Encoding.UTF8);
String Resline;
System.Text.StringBuilder Resstringbuilder = new System.Text.StringBuilder ();
while ((Resline = Resstreamreader.readline ())!= null) {resstringbuilder.append (resline + System.Environment.NewLine);
} resstream.close ();
Resstreamreader.close ();
return resstringbuilder.tostring (); } catch (Exception ex) {return ex.
Message;//url wrong return Error}}
Well, I admit that I am a cargo of unknown truth, how many more a access_token=isexistaccess_token (); Don't worry, the baby tells you.
When we read the document, we find that the Access_token is out of date every two hours. The method here is to get it automatically when it expires.
Fifth Pit , here's the JSON string, that is to show the menu, I hope that we all use lowercase, if the use of uppercase, then, ha ha, haha, really, very fucking, he will tell you did not use UTF8 code, but you are really coded, unfortunately or wrong, so, or lowercase it Alas
Continue to say two hours after automatic acquisition, is through the menucreate (call the micro-letter menu interface) output. On the code.
<summary>///prevents Token Two-hour changes per request///</summary> public class Wa_getaccess_token {public wa_getaccess_t Oken () {} public static Waentity.access_token Getaccess_token () {String url = ' Https://api.weixin.qq.com/cgi-bin/to Ken?grant_type=client_credential&appid= "+ configurationmanager.appsettings[" AppID "] +" &secret= "+
configurationmanager.appsettings["Appsecret"];
Access_token entity = new Access_token ();
try {HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (URL); Req.
method = ' Get '; using (WebResponse WR = req. GetResponse ()) {HttpWebResponse Myresponse = (httpwebresponse) req.
GetResponse ();
StreamReader reader = new StreamReader (Myresponse.getresponsestream (), System.Text.Encoding.UTF8); String content = Reader.
ReadToEnd ();
Access_token token = new Access_token ();
token = jsonhelper.parsefromjson<access_token> (content);
Entity.access_token = Token.access_token;
entity.expires_in = token.expires_in; } catch{//logging} REturn entity;
///<summary>///based on the current date to determine whether Access_token is overdue if the overdue return to the new Access_token otherwise return Access_token///</summary> <param name= "datetime" ></param>///<returns></returns> public static string isexistacces S_token () {try {string Token = string.
Empty;
DateTime Youxrq;
Reads the data in the XML file and displays it. String filepath = HttpContext.Current.Request.MapPath ("~/xmlfile.xml");
StreamReader str = new StreamReader (filepath, System.Text.Encoding.UTF8);
XmlDocument xml = new XmlDocument (); Xml.
Load (str); Str.
Close (); Str.
Dispose (); Token = XML. selectSingleNode ("xml"). selectSingleNode ("Access_token").
InnerText; YOUXRQ = Convert.todatetime (XML. selectSingleNode ("xml"). selectSingleNode ("Access_youxrq").
InnerText);
if (DateTime.Now > Youxrq) {DateTime _YOUXRQ = DateTime.Now;
Waentity.access_token mode = Getaccess_token (); Xml. selectSingleNode ("xml"). selectSingleNode ("Access_token").
innertext = Mode.access_token; _YOUXRQ = _youxrq. AddSEconds (Convert.ToInt32 (mode.expires_in)); Xml. selectSingleNode ("xml"). selectSingleNode ("Access_youxrq"). InnerText = _youxrq.
ToString (); Xml.
Save (filepath);
Token = Mode.access_token;
return Token; catch (Exception ex) {return ";//Record log}}} public class Access_token {public Access_token ()}
String Access_token {get; set;}
public string expires_in {get; set;} public class Jsonhelper {///<summary>///generate JSON format///</summary>///<typeparam name= "T" ;</typeparam>///<param name= "obj" ></param>///<returns></returns> public static str ing getjson<t> (T obj) {datacontractjsonserializer json = new DataContractJsonSerializer (obj.
GetType ()); using (MemoryStream stream = new MemoryStream ()) {json.
WriteObject (stream, obj); String Szjson = Encoding.UTF8.GetString (stream. ToArray ());
return Szjson; }///<summary>///get JSON model///</summary>///; Typeparam name= "T" ></typeparam>///<param name= "Szjson" ></param>///<returns></
returns> public static T parsefromjson<t> (string szjson) {T obj = activator.createinstance<t> (); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (Szjson)) {DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj.
GetType ()); Return (T) serializer.
ReadObject (MS);
}
}
}
Forgive me again unknown truth, the so-called xmlfile.xml This is what ghost, well, I actually do not want to say so straightforward, or the code directly on the better.
<?xml version= "1.0" encoding= "Utf-8"?>
<xml>
<Access_Token> get Token</access_token >
<access_youxrq>2015/9/12 17:56:31</access_youxrq>
</xml>
I'm sure this is something you really don't want to say.
Well, silently eating melon seeds, quietly watching you continue, today is first here, then we continue to walk, has five pits Ah, the baby in the heart bitter ah.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.