Problems before the development of php WeChat public account
Mar 21, 2017 pm 04:08 PMThis article mainly introduces the five pitfalls before the development of PHP WeChat public accounts in detail. It has certain reference value. Interested friends can refer to the
WeChat public account development document, official Version (https://mp.weixin.qq.com/wiki)
First of all, you must have a public platform account. Okay, let’s start planning the trap.
The first pitfall, Don’t think that you can’t develop if you don’t have an enterprise account. There are many more interfaces that can apply for a test account than the so-called subscription account interface.
After entering the background management, click on the developer tools, you can see the public platform test account, and enter directly. Start filling in your own configuration.
Pay attention to the graffiti part. This part is something that must be configured in the program. If it is not configured, this is It will definitely not be successful.
The second pit, of course, your configuration must be unsuccessful. Don’t ask me why. I don’t have a picture to say a few words. . .
#Please don’t think that Emperor Penguin is joking. This is true. It must be port 80. In fact, it is just a website with a domain name. Because the domain name websites are all out of port 80, let’s continue with the topic.
Emperor Penguin told us that to use a WeChat account, we must have a server and then configure the website we publish. Please note that the token is set by yourself. This is not automatically generated. set up. . The URL is the name of the website we publish
The third pitfall is that if the website is not published, the interface configuration information will never be configured. Remember, it is forever.
The purpose of the JS interface secure domain name is to download pictures, call the WeChat picture interface, etc. For example, when you need to call the camera, or when you need to upload photos, you need a JS secure interface. , the specific content will not be described in detail for the time being.
In the version background of the WeChat public account test account, there is an experience interface permission table that must be configured. It is not necessary to configure, but this interface can obtain some information of WeChat users. It is worth reminding that each ID corresponding to each public account is unique. In other words, even if the intranet of the website remains unchanged, if the public account is changed, the data of the WeChat public account at this time cannot be shared. is only unique relative to the public number.
The fourth pit, When applying for WeChat webpage authorization, here is the basic information of the webpage authorized user, this There is no problem in itself, but there is a problem if there is no prompt.
The URL here, please note that must not contain www, and there is no backslash after it, that is It says that the callback format of the URL here is abc.com OK, please remember this format, you must do this. Okay, let’s leave the server like this for now and let’s start talking in code.
First let’s start with server verification. There is an example of this on the official website, but it is for PHP. In fact, to put it bluntly, the first step is to verify a random number, and then in the case of POST, detect the return value. Directly upload the code
public ActionResult Index() { if (Request.HttpMethod.ToLower() == "post") { if (CheckSignature())//驗(yàn)證服務(wù)器是否通過(guò) { GetMenuList();//加載菜單 } else { Response.Write("<h1>Oh</h1><h2>我們相遇在火星吧?。?!</h2>"); Response.End(); } } else { CheckWechat(); } return View(); } /// <summary> /// 返回隨機(jī)數(shù)表示驗(yàn)證成功 /// </summary> private void CheckWechat() { if (string.IsNullOrEmpty(Request.QueryString["echoStr"])) { Response.Write("消息并非來(lái)自微信"); Response.End(); } string echoStr = Request.QueryString["echoStr"]; if (CheckSignature()) { Response.Write(echoStr); Response.End(); } } /// <summary> /// 驗(yàn)證微信簽名 /// </summary> /// <returns></returns> /// 將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 /// 將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 /// 開(kāi)發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來(lái)源于微信。 private bool CheckSignature() { string signature = Convert.ToString(Request["signature"]); string timestamp = Convert.ToString(Request["timestamp"]); string nonce = Convert.ToString(Request["nonce"]); 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; } }
Then, the public platform can customize the menu if it has permission, but once you start customizing the menu, the original manually edited menu cannot be In other words, if the server verification passes, you must use your own code to control it.
我們一起來(lái)看GetMenuList()這個(gè)方法,這個(gè)其實(shí)很簡(jiǎn)單的,就是隨便憑借一個(gè)JSON格式字符串。然后調(diào)用微信的接口即可。 public void GetMenuList()
<em id="__mceDel"> { string weixin1 = ""; weixin1 = @" { ""button"":[ { ""type"":""click"", ""name"":""你好!"", ""key"":""hello"" }, { ""type"":""view"", ""name"":""公司簡(jiǎn)介"", ""url"":""http://www.xnfhtech.com"" }, { ""name"":""產(chǎn)品介紹"", ""sub_button"":[ { ""type"":""click"", ""name"":""產(chǎn)品1"", ""key"":""p1"" }, { ""type"":""click"", ""name"":""產(chǎn)品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);//獲取token、拼湊url string respText = WebRequestPostOrGet(setMenuUrl, MenuJson); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); return respDic["errcode"].ToString();//返回0發(fā)布成功 } /// <summary> /// Post/get 提交調(diào)用抓取 /// </summary> /// <param name="url">提交地址</param> /// <param name="param">參數(shù)</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 使用可以釋放using段內(nèi)的內(nèi)存 { reqStream.Write(bt, 0, bt.Length); reqStream.Flush(); } try { using (WebResponse res = req.GetResponse()) { //在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理 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錯(cuò)誤時(shí)候回報(bào)錯(cuò) } }
好吧,我承認(rèn)我是一個(gè)不明真相的吃貨,怎么又多了一個(gè)access_token=IsExistAccess_Token();呢,莫著急,寶寶告訴你。
當(dāng)我們閱讀文檔的時(shí)候,我們會(huì)發(fā)現(xiàn),這里的Access_Token是每?jī)蓚€(gè)小時(shí)就過(guò)期的。這里的方法就是讓他過(guò)期的時(shí)候自動(dòng)獲取。
第五坑,這里的JSON字符串,也就是要展示的菜單,我希望大家都用小寫(xiě),如果用了大寫(xiě),那么,呵呵,哈哈了真心的,很操蛋的,他會(huì)告訴你沒(méi)有用UTF8編碼,但是你真心是編碼過(guò)的,可惜還是出錯(cuò),所以,還是小寫(xiě)吧,唉
繼續(xù)說(shuō)兩個(gè)小時(shí)自動(dòng)獲取之后,就是通過(guò)MenuCreate(調(diào)用微信菜單接口)輸出即可。上代碼。
/// <summary> /// 防止每次請(qǐng)求的token兩個(gè)小時(shí)的變化 /// </summary> public class WA_GetAccess_Token { public WA_GetAccess_Token() { } public static WAEntity.Access_token GetAccess_Token() { string url = "https://api.weixin.qq.com/cgi-bin/token?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{ //記錄日志} return entity; } /// <summary> /// 根據(jù)當(dāng)前日期 判斷Access_Token 是否超期 如果超期返回新的Access_Token 否則返回之前的Access_Token /// </summary> /// <param name="datetime"></param> /// <returns></returns> public static string IsExistAccess_Token() { try { string Token = string.Empty; DateTime YouXRQ; //讀取XML文件中的數(shù)據(jù),并顯示出來(lái) 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 "";//記錄日志 } } } public class Access_token { public Access_token() { } public string access_token { get; set; } public string expires_in { get; set; } } public class JsonHelper { /// <summary> /// 生成Json格式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string 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> /// 獲取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); } } }
原諒我又不明真相了,所謂的XMLFile.xml這又是什么鬼,好吧,我其實(shí)不想說(shuō)的這么直白的,還是代碼直接上比較好。
<?xml version="1.0" encoding="utf-8"?> <xml> <Access_Token>獲取TOKEN</Access_Token> <Access_YouXRQ>2015/9/12 17:56:31</Access_YouXRQ> </xml>
The above is the detailed content of Problems before the development of php WeChat public account. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)