关于.NET HttpClient方式获取微信小程序码(二维码)

  • 2019 年 10 月 3 日
  • 筆記

随着微信小程序的火热应用,市面上有关小程序开发的需求也多了起来。近来分析了一项生成有关生成微信小程序码的需求——要求扫码跳转到小程序指定页面(带参数);看了下小程序官方文档,以及网上的例子,未看到多少有价值的采用C#调用小程序接口生成小程序码的例子,于是拾起多年前的代码,略作分析尝试,在此分享出来,以此抛砖引玉。

此文以HttpClient方式示例,当然采用老旧的HttpWebRequest也可以,在此不作分析。
生成微信小程序码(二维码)的接口主要有三个:

在此仅针对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");

 

path和width为可选参数,path根据自身项目需求传入即可,如Server.MapPath(savePath);width即生成的二维码宽度(默认430),具体参见接口文档;AccessToken为接口调用凭证;

注:由于腾讯限制,如果接口调用成功,会直接返回图片二进制内容,如果请求失败,会返回 JSON 格式的数据;方法里仅对返回二进制流作处理,其他可根据需求自行完善。