c#后台生成指定页面带参数的小程序码

出于安全考虑,小程序禁用了直接在小程序端调用api.weixin.qq.com的功能,只能通过后台来调用,以下是实现的过程。

这是官方的文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html;

1.首先获取accesstoken 

 public string GetAccessToken(string strAPPID, string strSecret) { string str = ""; string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + strAPPID + "&secret=" + strSecret + ""; System.Net.WebRequest wRequest = System.Net.WebRequest.Create(url); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; System.Net.WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default); str = reader.ReadToEnd(); //url返回的值  return str; }

我这里没有对strAPPID和strSecret进行加密,如果安全性要求较高的可以加密,然后接口进行解密。

 

c#后台生成指定页面带参数的小程序码

2.根据获取的accesstoken调用接口保存小程序码。返回小程序的地址

 public string GetQrcode(string strToken, string content) { string strResult = ""; string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + strToken; System.Net.WebRequest wRequest = System.Net.WebRequest.Create(url); wRequest.Method = "post"; wRequest.ContentType = "application/x-www-form-urlencoded"; #region 添加Post 参数 byte[] data = Encoding.UTF8.GetBytes(content); wRequest.ContentLength = data.Length; using (Stream reqStream = wRequest.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } #endregion HttpWebResponse resp = (HttpWebResponse)wRequest.GetResponse(); Stream stream = resp.GetResponseStream(); ////获取响应内容 //using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) //{ // strResult = reader.ReadToEnd(); //} Image img = Image.FromStream(stream);
        //服务器硬盘位置,在接口web.config中配置
        //
<add key="strMiniProgramUrl" value="D:W-E-Bxcx_mls" />
string strImageWebUrl = ConfigurationManager.AppSettings["strMiniProgramUrl"]; string str = DateTime.Now.ToString("yyyyMM"); string str2 = DateTime.Now.ToString("yyyyMMdd"); string path = strImageWebUrl + @"uploads"; string path2 = @"https://服务器域名/" + @"/uploads"; if (!Directory.Exists(path + @"audio" + str)) { Directory.CreateDirectory(path + @"audio" + str); } path = path + @"qrcode" + str; path2 = path2 + @"/qrcode/" + str; if (!Directory.Exists(path + @"" + str2)) { Directory.CreateDirectory(path + @"" + str2); } path = path + @"" + str2; path2 = path2 + @"/" + str2; int num = new Random().Next(0x2710); string str6 = DateTime.Now.ToString("yyyyMMddHHmmss") + num.ToString() + Guid.NewGuid().ToString() + ".jpg"; string filename = path + @"" + str6; path2 = path2 + @"/" + str6; try { img.Save(filename, ImageFormat.Jpeg); this.model.value = path2; this.model.code = "1000"; } catch { this.model.code = "0001"; } finally { if (img != null) { img.Dispose(); img = null; } } return this.bllcommon.returnStr(JsonConvert.ExportToString(this.model)).Replace("暂无", ""); }
path2为保存后的小程序码图片地址

相关文章