隨著微信小程式的火熱應用,市面上有關小程式開發的需求也多了起來,近來分析了一項生成有關生成微信小程式碼的需求——要求掃碼跳轉到小程式指定頁面(帶引數);看了下小程式官方檔案,以及網上的例子,未看到多少有價值的采用C#呼叫小程式介面生成小程式碼的例子,于是拾起多年前的代碼,略作分析嘗試,在此分享給有需要的人,并以此拋磚引玉,
此文以HttpClient方式示例,當然采用老舊的HttpWebRequest也可以,在此不作分析,
生成微信小程式碼(二維碼)的介面主要有三個:
- https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
- https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html
- https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
在此僅針對createwxaqrcode(二維碼)和get(小程式碼/葵花碼)講解,getUnlimited原理同;
兩者的介面地址分別如下:
https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
由于請求小程式介面,其回傳的是圖片二進制流,采用HttpClient方式時務必針對二進制資料進行處理;不多說,直接上關鍵代碼,簡要示例如下:
public class HttpClientHelper { /// <summary> /// 保存介面回傳二進制流為檔案方法 /// </summary> /// <param name="requestUri">介面地址</param> /// <param name="filePath">檔案存盤路徑</param> /// <param name="jsonString">json資料物件</param> /// <param name="webapiBaseUrl"></param> /// <returns></returns> public static bool DownloadBufferImage(string requestUri, /*HttpContent httpContent,*/string filePath, string jsonString, string webapiBaseUrl = "") { try { HttpContent httpContent = new StringContent(jsonString); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using (HttpClient httpClient = new HttpClient()) { if (!string.IsNullOrWhiteSpace(webapiBaseUrl)) { httpClient.BaseAddress = new Uri(webapiBaseUrl); } bool result = false; httpClient.PostAsync(requestUri, httpContent).ContinueWith( (requestTask) => { HttpResponseMessage response = requestTask.Result; response.EnsureSuccessStatusCode(); var data =https://www.cnblogs.com/ang/p/ response.Content.ReadAsByteArrayAsync().Result; var folder = Path.GetDirectoryName(filePath); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } result = true; }).Wait(30000); return result; } } catch { return false; } }}
一共4個引數:
- requestUri請求的介面URL;
- filePath小程式碼(二維碼)存盤的絕對路徑;
- jsonString提交的json資料物件;
- webapiBaseUrl介面根路徑(可忽略)
由于騰訊介面要求,提交資料必須json物件,因此httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"),此處尤為重要,不能像提交form表單一樣以字典方式提交;其次,處理二進制資料流采用以下形式處理并保存圖片;此處不贅述,
var data = https://www.cnblogs.com/ang/p/response.Content.ReadAsByteArrayAsync().Result; using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)){ fs.Write(data, 0, data.Length); fs.Flush(); fs.Close();}
簡要封裝及呼叫示例如下:
public bool GetQrCode(string filePath, string path = "pages/default/default", int width = 430) { string postUrl = string.Format("https://api.weixin.qq.com/wxa/getwxacode?access_token={0}", AccessToken); var data = https://www.cnblogs.com/ang/p/new { path = path, width = width }; var result = HttpClientHelper.DownloadBufferImage(postUrl, filePath, Newtonsoft.Json.JsonConvert.SerializeObject(data)); return result; }
new NameSpace.GetQrCode(@"D:\QrCode.jpg", path: "pages/index/index");
filePath為保存小程式碼(二維碼)圖片的絕對路徑,如Server.MapPath(savePath);path(小程式頁面地址)和width(二維碼寬度,默認430)均為可選引數,具體參見介面檔案;AccessToken為介面呼叫憑證;
注:由于騰訊限制,如果介面呼叫成功,會直接回傳圖片二進制內容,如果請求失敗,會回傳 JSON 格式的資料;方法里僅對回傳二進制流作處理,其他可根據需求自行完善,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/12323.html
標籤:ASP.NET
