ibcadmin 发表于 2019-10-12 10:21:54

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

<p>随着微信小程序的火热应用,市面上有关小程序开发的需求也多了起来。迩来分析了一项天生有关天生微信小程序码的需求——要求扫码跳转到小程序指定页面(带参数);看了下小程序官方文档,以及网上的例子,未看到多少有代价的采取C#调用小程序接口天生小程序码的例子,于是拾起多年前的代码,略作分析实验,在此分享给有须要的人,并以此抛砖引玉。<br /><br /></p>
<p>此文以HttpClient方式示例,当然采取老旧的HttpWebRequest也可以,在此不作分析。<br />天生微信小程序码(二维码)的接口告急有三个:</p>
<ul>
<li>https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html</li>
<li>https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html</li>
<li>https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html</li>













</ul>
<p>在此仅针对createwxaqrcode(二维码)和get(小程序码/葵花码)讲解,getUnlimited原理同;</p>
<p>两者的接口地址分别如下:</p>
<p>https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN</p>
<p>https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN</p>
<p>由于请求小程序接口,其返回的是图片二进制流,采取HttpClient方式时务必针对二进制数据进行处理处罚;不多说,直接上关键代码,扼要示比方下:</p>

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

<p> </p>
<p>一共4个参数:</p>
<ol>
<li>requestUri请求的接口URL;</li>
<li>filePath小程序码(二维码)存储的绝对路径;</li>
<li>jsonString提交的json数据对象;</li>
<li>webapiBaseUrl接口根路径(可忽略)</li>
</ol>
<p> </p>
<p>由于腾讯接口要求,提交数据必须json对象,因此<strong>httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"),</strong>此处尤为告急,不能像提交form表单一样以字典方式提交;其次,处理处罚二进制数据流采取以下情势处理处罚并生存图片;此处不赘述。</p>

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


<p>  </p>
<p>扼要封装及调用示比方下:</p>

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


<p>  </p>

new NameSpace.GetQrCode(@"D:\QrCode.jpg", path: "pages/index/index");

<p> </p>
<p>filePath为生存小程序码(二维码)图片的绝对路径,如Server.MapPath(savePath);path(小程序页面地址)和width(二维码宽度,默认430)均为可选参数,具体拜见接口文档;AccessToken为接口调用凭证;</p>
<p>注:由于腾讯限定,假如接口调用乐成,会直接返回图片二进制内容,假如请求失败,会返回 JSON 格式的数据;方法里仅对返回二进制流作处理处罚,其他可根据需求自行完善。</p>
<p> </p><br><br/><br/><br/><br/><br/>来源:<a href="https://www.cnblogs.com/ang/p/11620940.html" target="_blank">https://www.cnblogs.com/ang/p/11620940.html</a>
页: [1]
查看完整版本: 关于.NET HttpClient方式获取微信小程序码(二维码)