1. 程式人生 > >關於.NET HttpClient方式獲取微信小程式碼(二維碼)

關於.NET HttpClient方式獲取微信小程式碼(二維碼)

隨著微信小程式的火熱應用,市面上有關小程式開發的需求也多了起來。近來分析了一項生成有關生成微信小程式碼的需求——要求掃碼跳轉到小程式指定頁面(帶引數);看了下小程式官方文件,以及網上的例子,未看到多少有價值的採用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
    {
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 = response.Content.ReadAsByteArrayAsync().Result;
                        
                           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個引數:

  1. requestUri請求的介面URL;
  2. filePath小程式碼(二維碼)儲存的絕對路徑;
  3. jsonString提交的json資料物件;
  4. webapiBaseUrl介面根路徑(可忽略)

 

由於騰訊介面要求,提交資料必須json物件,因此httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"),此處尤為重要,不能像提交form表單一樣以字典方式提交;其次,處理二進位制資料流採用以下形式處理並儲存圖片;此處不贅述。

var data = 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 = 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 格式的資料;方法裡僅對返回二進位制流作處理,其他可根據需求自行完善。

&n