随着微信小程序的火热应用,市面上有关小程序开发的需求也多了起来。近来分析了一项生成有关生成微信小程序码的需求——要求扫码跳转到小程序指定页面(带参数);看了下小程序官方文档,以及网上的例子,未看到多少有价值的采用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.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个参数:
- requesturi请求的接口url;
- filepath小程序码(二维码)存储的绝对路径;
- jsonstring提交的json数据对象;
- 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 格式的数据;方法里仅对返回二进制流作处理,其他可根据需求自行完善。