PHP micro-Credit public account development of the five pits (ii) _php example

Source: Internet
Author: User
Tags cdata datetime httpcontext oauth openid ticket

The last article on the micro-letter public account of a few pits, the front five, has said the menu, the baby continues to repeat. Unfortunately, still do not know baby's baby in the end is not distressed baby, finished, I messy ...

Back to the point, we will not spit the other, the last article on the micro-letter menu, then, we now talk about the menu reply and so on.

The menu reply is the XML file that needs to be processed, and we can get the unique identification of each micro-letter user relative to the micro-public number based on the XML file returned by the micro-letter. The mechanism of the micro-trust public platform is simply that we will output the fixed format XML file, then the micro-mail app is responsible for parsing, getting the information we want, and then handling the information uniformly.

The sixth Pit, if you look at the micro-letter document, then, absolutely pits you, above the figure. Here's tousername and Fromusername must be clear, remember, do not write back, the user for micro-letter is a→b, then micro-letter for users is the opposite, seems to be clear now.

<summary>///receives the XML message sent by the micro-mail and resolves///</summary> private void Receivexml () {try {Stream requeststr
  EAM = System.Web.HttpContext.Current.Request.InputStream;
  byte[] Requestbyte = new Byte[requeststream.length];
  Requeststream.read (requestbyte, 0, (int) requeststream.length);

  String requeststr = Encoding.UTF8.GetString (requestbyte); if (!string.
  IsNullOrEmpty (REQUESTSTR)) {//Encapsulation request class XmlDocument requestdocxml = new XmlDocument ();
  Requestdocxml.loadxml (REQUESTSTR);
  XmlElement rootelement = requestdocxml.documentelement;
  Wxxmlmodel Wxxmlmodel = new Wxxmlmodel (); if (rootelement!= null) {wxxmlmodel.tousername = Rootelement.selectsinglenode ("tousername") = = null? "": Rootelement.selectsinglenode ("Tousername").
   InnerText; Wxxmlmodel.fromusername = Rootelement.selectsinglenode ("fromusername") = = null? "": Rootelement.selectsinglenode ("Fromusername").
   InnerText; Wxxmlmodel.createtime = Rootelement.selectsinglenode ("createtime") = = null? "": Rootelement.selectsinglenode ("Createtime").
   InnerText; Wxxmlmodel.msgtype = Rootelement.selectsinglenode ("msgtype") = = null? "": Rootelement.selectsinglenode ("Msgtype").
   InnerText; Switch (wxxmlmodel.msgtype) {case "text"://Text wxxmlmodel.content = Rootelement.selectsinglenode ("Content") = = Null? "": Rootelement.selectsinglenode ("Content").
    InnerText;
   Break Case "image"://Picture Wxxmlmodel.picurl = Rootelement.selectsinglenode ("picurl") = = null? "": Rootelement.selectsinglenode ("Picurl").
    InnerText;
   Break Case "Event"://Event wxxmlmodel.event = Rootelement.selectsinglenode ("event") = = null? "": Rootelement.selectsinglenode ("Event").
    InnerText; if (wxxmlmodel.event!= "templatesendjobfinish")//attention type {Wxxmlmodel.eventkey = Rootelement.selectsinglenode ("Event Key ") = = null? "": Rootelement.selectsinglenode ("Eventkey").
    InnerText;
   } break;
   Default:break; } responsexml (Wxxmlmodel);//Reply message} catch (Exception ee) {//Log error log}}///<summary>///reply message///</summary>///<param name= "Wxxmlmodel" >&lt
 ;/param> private void Responsexml (Wxxmlmodel wxxmlmodel) {string XML = ""; Switch (wxxmlmodel.msgtype) {case "text"://Text reply var info = OAuth.
  GetUserInfo (Tools.WA_GetAccess_Token.IsExistAccess_Token (), wxxmlmodel.fromusername);
  Tools.WAEntity.OAuthUser user = tools.jsonhelper.parsefromjson<tools.waentity.oauthuser> (info);
  var content = WxXmlModel.Content.ToUpper ();
  String ncbacturl = configurationmanager.appsettings["Ncbacturl"];
  string AppID = configurationmanager.appsettings["AppID"]; if (content). Contains ("T"))//Accepted text if contains T {//Business process} else {XML = Responsemessage.retext (Wxxmlmodel.fromusername, Wxxmlmode L.tousername, "/:rose Farm Big Data welcome you!"

  /:rose ");
  } break; Case ' event ': Switch (WxXmlModel.Event.ToLower ()) {case "subscribe": if (string. IsNullOrEmpty (Wxxmlmodel.eventkey)) {XML = Responsemessage.retext (wxxMlmodel.fromusername, Wxxmlmodel.tousername, "Focus on success!"

   /:rose "); else {XML = Responsemessage.subscanqrcode (Wxxmlmodel.fromusername, Wxxmlmodel.tousername, Wxxmlmodel.eventkey
   )//scan with parameters two-dimensional code first attention after the push event} break; Case "Scan": XML = Responsemessage.scanqrcode (Wxxmlmodel.fromusername, Wxxmlmodel.tousername, Wxxmlmodel.eventkey);
   /scan with parameter two-dimensional code has been concerned with direct push event break; Case "click"://Handle Click event if (Wxxmlmodel.eventkey = = "P1") {//own business logic} else {//own business logic} break
   ;
  Case "unsubscribe"://Cancel attention to break;
  } break;
 default://default reply break;

 } response.write (XML);//output XML information for the Organization}

This is the menu of information processing, the unknown people seem to ask the so-called responsemessage in the end have a few meanings, OK, I have been unable to spit my three days of research out of the micro-trust public platform things.  

public class Responsemessage {#region received type///<summary>///receive text///</summary>///<param name= "Fromusername" ></param>///<param name= "Tousername" ></param>///<param name= "Content" > </param>///<returns></returns> public static string Gettexttest (String fromusername, String Tousern
 Ame, String Content, String key) {commonmethod.writetxt (content);//Received text message string XML = "";
  Switch (Content) {case "keyword": XML = Retext (Fromusername, tousername, "keyword response test-xing Nong Feng Hua:" + key);
  Break Case "Single graphic": XML = Rearticle (Fromusername, Tousername, "test title", "Test details--Xing Nong Feng Hua:" + key, "Http://www.xnfhtech.com/templets/boz
  E/images/20120130083143544.gif "," http://www.xnfhtech.com/");
  Break
  Default:xml = Retext (Fromusername, Tousername, "no corresponding keywords-xing Nong Feng Hua:" + key);
 Break

 } return XML; ///<summary>///not concerned with scanning with parameter two-dimensional code///</summary>///<param name= "Fromusername" ></param>///& Lt;param name="Tousername" ></param>///<param name= "Eventkey" ></param>///<returns></returns>
 public static string Subscanqrcode (String fromusername, String tousername, String eventkey) {return "";  ///<summary>///has been concerned with scanning with parameter two-dimensional code///</summary>///<param name= "Fromusername" ></param>/// <param name= "Tousername" ></param>///<param name= "Eventkey" ></param>///<returns>
 </returns> public static string Scanqrcode (String fromusername, String tousername, String eventkey) {return ""; #endregion #region reply///<summary>///reply text///</summary>///<param name= "Fromusername" ; Send to WHO (OpenID) </param>///<param name= "Tousername" > From WHO (Public account ID) </param>///<param name= "Content "> Reply type text </param>///<returns> patchwork xml</returns> public static string Retext (string fromusername, S Tring Tousername, String Content) {string XML = "<xml><tousername><! [cdata["+ Fromusername +"]]></tousername><fromusername><! [cdata["+ Tousername +"]]></fromusername> ";/sent to WHO (OpenID), from WHO (Public account ID) XML + +" <CreateTime> "+ Commonmethod.convertdatetimeint (DateTime.Now) + "</CreateTime>";//reply Timestamp XML = "<msgtype><! [cdata[text]]></msgtype> "//reply type text XML + =" <content><! [cdata[+ content + "]]></content><funcflag>0</funcflag></xml>";//reply Contents Funcflag set to 1,

 Automatic star sign just received the message, suitable for activity statistics using return XML; ///<summary>///reply to single text///</summary>///<param name= "Fromusername" > Sent to (OpenID) </param&gt
 ; <param name= "Tousername" > From WHO (Public account ID) </param>///<param name= "title" > title </param>///< param name= "Description" > Details </param>///<param name= "Picurl" > Image address </param>///<param name= " URL "> Address </param>///<returns> patchwork xml</returns> public static StRing Rearticle (String fromusername, String tousername, String Title, String Description, String Picurl, String Url) {s Tring XML = "<xml><tousername><! [cdata["+ Fromusername +"]]></tousername><fromusername><! [cdata["+ Tousername +"]]></fromusername> ";/sent to WHO (OpenID), from WHO (Public account ID) XML + +" <CreateTime> "+ Commonmethod.convertdatetimeint (DateTime.Now) + "</CreateTime>";//reply Timestamp XML = "<msgtype><! [cdata[news]]></msgtype><content><!
 [cdata[]]></content><articlecount>1</articlecount><articles> "; XML = "<item><title><! [cdata["+ Title +"]]></title><description><! [cdata["+ Description +"]]></description><picurl><! [cdata["+ Picurl +"]]></picurl><url><!
 [cdata[] + Url + "]]></url></item>";
 XML = "</Articles><FuncFlag>0</FuncFlag></xml>";

 return XML; }///<summary>///Multiple text reply///</summary>///<param name= "Fromusername" > Sent to whom (OpenID) </param>///<param na Me= "Tousername" > From WHO (Public account ID) </param>///<param name= "Articlecount" > Text quantity </param>///<param Name= "Dtarticle" ></param>///<returns></returns> public static string Rearticle (string Fromusername, string tousername, int articlecount, System.Data.DataTable dtarticle) {string XML = ' <xml><tous ername><! [cdata["+ Fromusername +"]]></tousername><fromusername><! [cdata["+ Tousername +"]]></fromusername> ";/sent to WHO (OpenID), from WHO (Public account ID) XML + +" <CreateTime> "+ Commonmethod.convertdatetimeint (DateTime.Now) + "</CreateTime>";//reply Timestamp XML = "<msgtype><! [cdata[news]]></msgtype><content><!
 [cdata[]]></content><articlecount> "+ Articlecount + </ArticleCount><Articles>";
foreach (System.Data.DataRow Item in Dtarticle.rows)
 {XML = "<item><title><! [cdata["+ item[" Title "] +"]]></title><description><! [cdata["+ item[" Description "] +"]]></description><picurl><! [cdata["+ item[" Picurl "] +"]]></picurl><url><!
 [cdata["+ item[" URL "] +"]]></url></item> ";
 XML = = "</Articles><FuncFlag>0</FuncFlag></xml>";

 return XML;

 } #endregion}

OK, plus your own logical code, is not the perfect implementation of the reply?

Seventh Pit, I really do not want to count, are you sure this reply is OK? Seriously, the baby is not sure, because you wrote after you know where to call it, my darling, Ni-ma, server verification by adding to the reply is the most insurance. I've lost my integrity.

So what are we going to say, let's talk about getting user information, because we're generally based on H5 pages. So, we need to use what we have previously configured

This dongdong, in fact, this relative to the front of at least a lot less pit, sincerely, the baby will not say he pits. Last code.

Micro-trust Web page Authorization 2.0 public class Oauth2 {JavaScriptSerializer Jss = new JavaScriptSerializer (); Public Oauth2 () {}///<summary>///to page for authorization///</summary>///<param name= "Appid" > Micro-Letter Application id< /param>///<param name= "Redirect_uri" > Callback page </param>///<param name= "Scope" > Apply authorization Scope snsapi_ UserInfo (does not eject the authorization page, direct jump, can only obtain user OpenID), Snsapi_userinfo (pop-up authorization page, can get the nickname, Sex, location by OpenID. And, even in the event of no concern, as long as the user authorized to obtain its information) </param>///<returns> Authorized address </returns> public string Getcodeurl (string Appid, String Redirect_uri, string scope) {return string. Format ("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=
 Code&scope={2}&state=state#wechat_redirect ", Appid, Redirect_uri, scope); ///<summary>///to page for authorization///</summary>///<param name= "Appid" > Micro-Letter Application id</param>///& Lt;param name= "Redirect_uri" > Callback page </param>///<param name= "Scope" > Application authorization Scope snsapi_useRinfo (does not eject the authorization page, direct jump, can only obtain user OpenID), Snsapi_userinfo (pop-up authorization page, can get the nickname, Sex, location by OpenID. And, even in the event of no concern, as long as the user authorized to obtain its information) </param>///<returns> Authorized address </returns> public string Getcodeurl (string Appid, String Redirect_uri, string scope,string state} {return string. Format ("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=
 CODE&SCOPE={2}&STATE={3} #wechat_redirect ", Appid, Redirect_uri, scope, state); ///<summary>///Use code in exchange for OpenID This method is generally not to get user nicknames when using///</summary>///<param name= "Appid" ></ param>///<param name= "Appsecret" ></param>///<param name= "code" > callback page with code parameters </param>// /<returns> micro-Credit User Unique identifier openid</returns> public string Codegetopenid (string Appid, String Appsecret, String Code ) {String url = string. Format ("Https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type =authorization_code ", Appid, APPSECRET, Code); String retext = Commonmethod.webrequestpostorget (URL, "");//post/get method gets information dictionary<string, object> DicText = (
 Dictionary<string, object>) jss.deserializeobject (Retext); if (!
 Dictext.containskey ("OpenID")) return ""; return dictext["OpenID"].
 ToString (); 
 ///<summary>///uses code in exchange for obtaining user information (including non-concern users)///</summary>///<param name= "Appid" ></param> <param name= "Appsecret" ></param>///<param name= "code" > callback page with code parameters </param>///<retu  Rns> Get user information (JSON format) </returns> public string GetUserInfo (string Appid, String Appsecret, String Code) {string url = string. Format ("Https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type
 =authorization_code ", Appid, Appsecret, code); String retext = Commonmethod.webrequestpostorget (URL, "");//post/get method gets information dictionary<string, object> DicText = ( Dictionary<string, object>) jss.deserializeobject (ReTEXT); if (! Dictext.containskey ("OpenID")) {log. Error ("Get OpenID failed, wrong code:" + dictext["Errcode"].

 ToString ());

 Return ""; else {return Commonmethod.webrequestpostorget ("https://api.weixin.qq.com/sns/userinfo?access_token=" + dictext["a")

 Ccess_token "] +" &openid= "+ dictext[" OpenID "] +" &LANG=ZH_CN "," "); }///<summary>///get user information via OpenID///</summary>///<param name= "Accesstoken" ></para m>///<param name= "OpenID" ></param>///<returns></returns> public string GetUserInfo (stri Ng Accesstoken, String OpenID) {string url = string. Format ("Https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_cn",
 Accesstoken, OpenID);

 Return Commonmethod.webrequestpostorget (URL, "");//post/get method Get Info}}

We need to call the time directly using the inside method, access to micro-letter Web page authorization, such as for a controller under the B view to obtain authorization, and to obtain the user's relevant information, then we can call directly, such as Getcodeurl (AppID, "http://" + Url + "/a/b "," Snsapi_userinfo ")

I'll just spit it out here.

eighth Pit, micro-letter menu JSON URL stitching, the front is not added JS verification mody, so, special Mody, or obediently plus http://.

However, after the authorization, because the user's a lot of information we have to use, this is the H5 page transfer value problem, I used in the project is the session, directly write a common method, if the session has a value, then directly take the value. For some of the inside, I would like to explain, not all the code will be posted, my side of the code is only I personally think need to post. So inside the method may have everybody to see, if need, can leave a message this baby, thank you.

public string getsession () {log.
 Error ("GetSession");
 String oauthstr = ""; try {if (Session!= null && (session["oauthstr"] = = NULL | | string. IsNullOrEmpty (session["Oauthstr"). ToString ())) {if (!string).
  IsNullOrEmpty (request.querystring["code"]) {Oauth2 OAuth = new Oauth2 ();
  String code = convert.tostring (request["Code"]); Oauthstr = OAuth.
   GetUserInfo (configurationmanager.appsettings["AppID"], configurationmanager.appsettings["AppSecret"], code);
  session["oauthstr"] = oauthstr;
  Tools.WAEntity.OAuthUser oauthuser = new Tools.WAEntity.OAuthUser ();
  Oauthuser = tools.jsonhelper.parsefromjson<tools.waentity.oauthuser> (OAUTHSTR);

 return oauthstr;
  else {Tools.WAEntity.OAuthUser Oauthuser = new Tools.WAEntity.OAuthUser (); Oauthuser = tools.jsonhelper.parsefromjson<tools.waentity.oauthuser> (session["OauthStr").
  ToString ()); return session["Oauthstr"].

 ToString (); } catch (Exception e) {log. Error (E.tostring ()); ReTurn oauthstr;

};

 }

And then every time I encounter a page that needs to get information, I usually call this on it.

Basically the rest is our own business logic to deal with, continue to say the pit.

The nineth Pit, the micro-letter upload picture, the pit is definitely not just yourself. Believe it or not, the baby really believes it. Special pictures cannot be uploaded for loops. Of course, this apple-only model, big Android is still no problem.
The first mentioned JS security verification problem, here is to invoke these authentication, request some permissions, and then get picture information and so on.

Rest assured that the baby is now talking on the map, no picture of a little brother Ah ...

Let's go back and look at the code.

Let's start with JSON.

public class Jsapi {JavaScriptSerializer Jss = new JavaScriptSerializer (); Public Jsapi () {} const string url_format_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={

 0}&type=jsapi "; #region Verify JSAPI permissions configuration///<summary>///get JSAPI Permissions configuration array/Four parameters///</summary>///<param name= "Appid" > Application I
 d</param>///<param name= "Appsecret" > key </param>///<returns>json format four parameters </returns>

 public string Getjsapiinfo (string Appid, String appsecret) {string jsapi_ticket = ""; Ticket Cache 7,200 sec if (system.web.httpcontext.current.session["jsapi_ticket"] = = null) {string ticketurl = string. Format (Url_format_ticket, Basicapi.getaccesstoken (Appid, Appsecret));/"Https://api.weixin.qq.com/cgi-bin/ticket /getticket?access_token= "+ Getaccesstoken (Appid, Appsecret) +" &type=jsapi "Jsapi_ticket =
  Commonmethod.webrequestpostorget (Ticketurl, "");//basicapi.gettokensession System.web.httpcontext.current.session["Jsapi_ticket "] = Jsapi_ticket;
  System.Web.HttpContext.Current.Session.Timeout = 7200;


 Basicapi.writetxt ("Jsapi_ticket1:" + jsapi_ticket); else {jsapi_ticket = system.web.httpcontext.current.session["Jsapi_ticket"].
  ToString ();
 Basicapi.writetxt ("Jsapi_ticket2:" + jsapi_ticket);
 dictionary<string, object> respdic = (dictionary<string, object>) jss.deserializeobject (Jsapi_ticket); Jsapi_ticket = respdic["Ticket"]. ToString ();//gets ticket string timestamp = Commonmethod.convertdatetimeint (DateTime.Now). ToString ();//Generate signature timestamp string noncestr = Commonmethod.getrandcode (16);//generate signed random string url =
 System.Web.HttpContext.Current.Request.Url.AbsoluteUri.ToString ()//Current address basicapi.writetxt ("url:" + URL);
 String[] ArrayList = {"jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + noncestr, "url=" + URL};
 Array.Sort (ArrayList); String signature = String.
 Join ("&", ArrayList); Signature = Formsauthentication.hashpasswordforstoringinconfiGfile (Signature, "SHA1").
 ToLower (); String r = "{\" appid\ ": \" "+ appId +" \ "," timestamp\ ":" + timestamp + ", \" noncestr\ ": \" "+ Noncestr +" \ ", \" signature\ ": \" "+ signature +" \ "," jsapilist\ ": [\" chooseimage\ ", \" previewimage\ ", \" uploadimage\ ", \" downloadimage\ ", \"
 Scanqrcode\ ", \" Onmenushareqq\ "]}";
 Basicapi.writetxt ("R:" + R.replace ("", ""));

 Return R.replace ("", "");

 }

}

Then look at the specific call.

Background code is actually very simple, direct output configuration file, and then the front desk JS direct call can be.

Jsapi Jsapi = new Jsapi ();
string config = Jsapi.getjsapiinfo (appId, appsecret);
viewbag.config = config;

The front code, in fact, is not difficult, this has an official example.

<script type= "Text/javascript" > Wx.config (@Html. Raw (Viewbag.config))//Background micro-letter configuration file Wx.ready (function () {$ ("# Avatar "). Click (function () {wx.chooseimage ({count:1,//Picture quantity default 9 sizetype: [' compressed '],//can specify whether it is an artwork or a compression diagram, both of which are ' Original ', SourceType: [' album ', ' Camera '],//can specify whether the source is an album or a camera, both of which have success:function (res) {var localids = RES.L Ocalids; Returns a list of local IDs for the selected photos, localid can display pictures as the SRC attribute of the img tag wx.uploadimage ({localid: ' + localids, isshowprogresstips:1, Su
    Ccess:function (res) {ServerID = Res.serverid;

   Getwxphoto (ServerID);

  }

   });

 }

  });

 });

 });
 Wx.error (function (res) {alert ("Interface validation failed, details: \ n" + json.stringify (res));
 });
 var types = 1; function Getwxphoto (mediaId) {$.ajax ({async:false, type: "Post", url: "/activityregistration/downloadwxphoto",//
  Your own processing method data: {Mediaid:mediaid, types:types}, Success:function (data) {$ ("#imageico"). Val (Data.result);
  $ ("#hed_pic"). attr (' src ', "..." + data.result); $("#hed_pic"). attr (' Alt ', ' avatarimg ');

 }

 });

 } </script>

OK, the background method is actually very simple, is a binary file processing, not, simple egg, special Mody, because the path of the problem, pit the baby One hours, special mody. There are suggestions here, such as micro-letter pictures downloaded after the download to the front desk to load the picture, to ensure that each picture is loaded to complete, to ensure that the background of the upload of pictures completed.  

<summary>///Download multimedia files///</summary>///<param name= "UserName" > Public number </param>///<param nam E= "MediaId" > Media id</param>///<param name= "Data" > Return download Success </param>///<param name= "Types" > The added picture type </param>///<returns> returns the multimedia file data, or null if the download fails.
 </returns> Public Jsonresult Downloadwxphoto (string mediaId, int types) {ErrorMessage errormessage; String access_token = Basicapi.getaccesstoken (configurationmanager.appsettings["AppID"),
 configurationmanager.appsettings["Appsecret"]);
 byte[] data = Mediahelper.download (Access_token, mediaId, out errormessage);
 string files = String.Empty, fileName = String.Empty;
 Files = Server.MapPath ("~/wxinphoto/"); if (!
 Directory.Exists (Files)) {directory.createdirectory (files);
 FileName = files + DateTime.Now.Ticks + ". jpg";
 if (data!= null) {BOOL flag = WriteFile (data, fileName); if (flag) {errormessage = new ErrorMessage (Errormessage.successcode, "downloading multimedia file succeeded.")
 ");
} else {errormessage = new ErrorMessage (Errormessage.exceptioncode, "Downloading a multimedia file from a micro-trust server failed."
 "); } else ErrorMessage = new ErrorMessage (Errormessage.exceptioncode, "Downloading multimedia file from a micro-trust server failed."
 ");

Return Json (New {result = "/" + Urlconvertor (fileName), errormessage = errormessage});
 }//Read fileName to byte[] private byte[] ReadFile (string fileName) {FileStream pfilestream = null;
 byte[] Preadbyte = new Byte[0];
 try {pfilestream = new FileStream (FileName, FileMode.Open, FileAccess.Read);
 BinaryReader r = new BinaryReader (pfilestream); R.basestream.seek (0, Seekorigin.begin);
 Set the file pointer to the file open Preadbyte = r.readbytes ((int) r.basestream.length);
 return preadbyte;
 catch {return preadbyte;

 finally {if (Pfilestream!= null) pfilestream.close (); 

 }//write byte[] to fileName private bool WriteFile (byte[] preadbyte, string fileName) {FileStream = null;
 try {pfilestream = new FileStream (FileName, FileMode.OpenOrCreate); Pfilestream.write (preadbyte, 0, preadbYte.
 Length);
 catch {return false;

 finally {if (Pfilestream!= null) pfilestream.close ();

return true; ///<summary>///determine if the target byte array is at the beginning of the source byte array///</summary>///<param name= "source" > Source byte array </param>/ <param name= "target" > Target byte array </param>///<returns> returns whether the destination byte array is at the beginning of the source byte array </returns> private

 BOOL Startswithbytes (byte[] source, byte[] Target {if Source = null && target = null) return true;
 If Source = null && target!= null | | Source!= NULL && target = null) return false; if (source. Length < target.
 Length) return false;
 bool StartsWith = true; for (int i = 0; i < target. Length;

  i++) {if (Source[i]!= target[i]) {startswith = false;

 Break

} return startswith;

 }

Do not think that this is done, my darling, Avatar uploaded, micro-letter camera also special Mody call to call the baby is happy, the baby is also a cow, remember the front of the east, the baby has not said the pit.
To repeat our nineth pit, special, you JS write a for loop if you can cycle the picture uploaded to the background, the baby is convinced, really, the baby convinced.

Just say it, and in the end I thought for myself, also discussed with the team, probably because of the micro-letter verification, resulting in a photo upload after the success of a picture, but our iphone is a special case, big Android is no problem, the iphone is a problem, and the problem is not small, Upload four pictures bar, Lotte is the last one, finally, to find a universal netizen, thank you, but the baby has forgotten where to find, embarrassed ....

<script type= "Text/javascript" > var types = 2;

 var urllist= "";

 var i = 0;  function up (Resurl) {if (I < resurl.localIds.length) {//upload photo Resu.localids[i] Wx.uploadimage ({localid: " 
   + Resurl.localids[i], isshowprogresstips:1, success:function (res) {//Alert ("Res.serverid:" + Res.serverid);
   MediaId = Res.serverid; $.ajax ({async:false, type: "Post", url: "/activityregistration/downloadwxphoto", data: {Mediaid:mediai D, Types:types}, Success:function (data) {$ ("#picPath"). Append (' <li><div class= "Imgbox" ><img SR

    C= "/img/cechanadd.png" id= "picture ' + i + '" alt= ""/></div></li> ");
    $ ("#picture" + i). attr (' src ', data.result);

    $ ("#picPath"). Append (' <input value= ' + data.result + ' type= ' hidden ' id= ' picurl ' + i + ' "class= ' Picclass '/> ');

    i++; if (i = = resurl.localids.length-1) {$ ("#picPath"). Append (' <li><div class= "Imgbox" ><img src= "/img/Cechanadd.png "id=" Picture "alt=" "/></div></li>");
    } up (Resurl);

   }
   });
  }
  });
  else {i = 0;
 }//Upload picture Wx.config (@Html. Raw (Viewbag.config)); Wx.ready (function () {$ ("#picPath"). Click (function () {wx.chooseimage ({count:3,//Default 9 Sizetype: [' Compresse d ',//can specify whether the original or the compression diagram, the default both have ' original ', SourceType: [' album ', ' Camera '],//can specify whether the source is an album or a camera, the default both have Success:function (r ESU) {var localids = Resu.localids;//Returns a list of local IDs for the selected photos, Localid can display the picture if (Localids.indexof ("Wxlocalresour") as the SRC attribute of the IMG tag
   Ce ")!=-1) {localids = Localids.replace (" Wxlocalresource "," Wxlocalresource ");
   @ (index + + 1) if (localids!= ') {$ ("#picPath"). HTML ("");
    var sear = new RegExp (', ');
    if (Sear.test (Localids)) {up (resu);  else {$ (' #picPath '). Append (' <li><div class= "Imgbox" ><img src= "/img/cechanadd.png" "Picture"
    + ' @index ' + ' "alt=", "/></div></li>"); $ ("#piCture "+" @index "). attr (' src ', localids);
     Upload photos wx.uploadimage ({localid: ' + localids, isshowprogresstips:1, Success:function (res) {

     MediaId = Res.serverid; $.ajax ({async:false, type: "Post", url: "/activityregistration/downloadwxphoto", data: {Media Id:mediaid, Types:types}, Success:function (data) {$ ("#picPath"). Append (' <input value= ' + data.resul

      T + ' type= ' hidden ' id= ' picurl ' + @index + ' class= ' picclass '/> '); $ ("#picPath"). Append ("<li><div class=" Imgbox "><img src="/img/cechanadd.png "id=" "Picture" alt= ""
      ></div></li> ');

    }
     });
    }
    }); }//$ ("#picPath"). Append (' <li><div class= "Imgbox" ><img src= "/img/cechanadd.png" id= "" Picture "alt=" "

   ></div></li> ');
  }
   }
  });
 });
 });
 Wx.error (function (res) {alert ("Interface validation failed, details: \ n" + json.stringify (res));
 });

 </script>

Remember, recursion is a special thing to do.

Speaking of Here, the baby has not wanted to say anything more, the product of the special you can not install force, you have seen that micro-letter can reply to a direct jump to the Web page, you do not go to excrement, Lenovo to a few days ago, big Ali Moon cakes time, suddenly feel that we programmers very tragic, the success of the products are special, And then what went wrong was the pot of our programmers? Ask a moment, this pot sincerity our programmer should carry.

Forget it, or do not spit, has been powerless .... Baby 92 comes, now indeed 82 years of skin ah, alas, the baby tired, really.

By the way, give some advice on the H5 page. For example, when you click the return button, we need to refresh the page, is the so-called Judgment page should not refresh, there are many ways, but the micro-letter inside the baby still feel so reliable.

<script type= "Text/javascript" >
 if (window.name!= "Hasload") {
 location.reload ();
 Window.name = "Hasload";
 } else {
 window.name = "";
 }
</script>

Also, after the implementation of the micro-letter to directly exit the current interface into the micro-public number interface, directly invoke the micro-letter a built-in method. Remember to write to <script></script> inside.

Weixinjsbridge.call (' CloseWindow '); This is the micro-letter close the current page

So confident that they have done all, you run, you have to run, ah hum, do not defy.

Micro-letter public account refers to the tenth pit , I add, haha, is the front of JS verification, you do not have the first file, how to handle these things, haha. Whether the baby won. Oh perfect,i like it.

<script src= "Http://res.wx.qq.com/open/js/jweixin-1.0.0.js" ></script>

This thing must not forget ha.

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.

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.