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

隨着微信小程序的火熱應用,市面上有關小程序開發的需求也多了起來。近來分析了一項生成有關生成微信小程序碼的需求——要求掃碼跳轉到小程序指定頁面(帶參數);看了下小程序官方文檔,以及網上的例子,未看到多少有價值的採用C#調用小程序接口生成小程序碼的例子,因而拾起多年前的代碼,略做分析嘗試,在此分享給有須要的人,並以此拋磚引玉。

html

此文以HttpClient方式示例,固然採用老舊的HttpWebRequest也能夠,在此不做分析。
生成微信小程序碼(二維碼)的接口主要有三個:web

在此僅針對createwxaqrcode(二維碼)和get(小程序碼/葵花碼)講解,getUnlimited原理同;json

二者的接口地址分別以下:小程序

https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN微信小程序

https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKENapi

因爲請求小程序接口,其返回的是圖片二進制流,採用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 = 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個參數:app

  1. requestUri請求的接口URL;
  2. filePath小程序碼(二維碼)存儲的絕對路徑;
  3. jsonString提交的json數據對象;
  4. webapiBaseUrl接口根路徑(可忽略)

 

因爲騰訊接口要求,提交數據必須json對象,所以httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"),此處尤其重要,不能像提交form表單同樣以字典方式提交;其次,處理二進制數據流採用如下形式處理並保存圖片;此處不贅述。post

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();
}

  

簡要封裝及調用示例以下:spa

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 格式的數據;方法裏僅對返回二進制流做處理,其餘可根據需求自行完善。

相關文章
相關標籤/搜索