赞
踩
- /// <summary>
- /// 创建小程序码
- /// </summary>
- /// <returns>返回Base64图片字符串</returns>
- public static ToResultJson GetWxaCodeUnlimit(CreateMpCodeInputDto inputDto)
- {
- string secret = string.Empty;
-
- CollectMoneyInfoDto coll = new CompService().GetCollectMoneyInfo(inputDto.CompCode);
- inputDto.AppID = coll.AppID;
- var authorizationInfo = new CompService().GetCollectMoneyAuthorizationInfo(inputDto.AppID);
- if (authorizationInfo != null)
- {
- secret = authorizationInfo.AppSecret;
- }
- else
- {
- secret = new CompService().GetPlatformAppSecret(inputDto.AppID);
- }
- string token = GetMPToken(inputDto.AppID, secret);
- if (string.IsNullOrEmpty(token))
- {
- return new ToResultJson(0, "990201");//获取小程序令牌失败
- }
- string strURL = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", token);
- int aCodeWidth = inputDto.width;
- if (inputDto.width < 280)
- {
- aCodeWidth = 280;
- }
- if (inputDto.width > 1280)
- {
- aCodeWidth = 1280;
- }
-
- GetWxaCodeUnlimitInputDto getWxaCodeUnlimitInputDto = new GetWxaCodeUnlimitInputDto()
- {
- auto_color = false,
- is_hyaline = false,
- line_color = new GetWxaCodeUnlimitLineColorDto
- {
- r = 0,
- g = 0,
- b = 0
- },
- width = aCodeWidth,
- page = string.IsNullOrWhiteSpace(inputDto.page) ? string.Empty : inputDto.page,
- scene = string.IsNullOrWhiteSpace(inputDto.scene) ? string.Empty : inputDto.scene,
- };
- string dataJson = JsonConvert.SerializeObject(getWxaCodeUnlimitInputDto);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
- request.Method = "POST";
- request.ContentType = "application/json;charset=UTF-8";
- byte[] payload = Encoding.UTF8.GetBytes(dataJson);
- request.ContentLength = payload.Length;
- Stream writer = request.GetRequestStream();
- writer.Write(payload, 0, payload.Length);
- writer.Close();
- System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- var stream = response.GetResponseStream();//返回图片数据流
- var memoryStream = new MemoryStream();
- //将基础流写入内存流
- const int bufferLength = 1024;
- byte[] buffer = new byte[bufferLength];
- int count = 0;
- while ((count = stream.Read(buffer, 0, bufferLength)) > 0)
- {
- memoryStream.Write(buffer, 0, count);
- }
- memoryStream.Position = 0;
- string strBase64 = Convert.ToBase64String(memoryStream.GetBuffer());
- return new ToResultJson(1, "000000") { data = strBase64 };
- }
- /// <summary>
- /// 获取小程序token
- /// </summary>
- /// <returns></returns>
- public static string GetMPToken(string appid, string secret)
- {
- string token = string.Empty;
- string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
- var url = string.Format(strUrl, appid, secret);
- var response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, null, null);
- if (response.StatusCode == HttpStatusCode.OK)
- {
- Stream receiveStream = response.GetResponseStream();
- StreamReader streamReader = new StreamReader(receiveStream, Encoding.UTF8);
- string jsonStr = streamReader.ReadToEnd();
- if (!string.IsNullOrEmpty(jsonStr))
- {
- try
- {
- var objToken = JsonConvert.DeserializeObject<JObject>(jsonStr);
- if (objToken != null && objToken.GetValue("errcode") == null)
- {
- return objToken.GetValue("access_token").ToString();
- }
- return string.Empty;
- }
- catch (Exception ex)
- {
- LoggerHelper.Error("获取小程序token失败", ex);
- }
- }
-
- }
-
- return token;
- }
$.http.post('/Setup/Store/CreateMpCode', { Id: obj.data.Id }, function (res) { if (res.status == "1") { layer.open({ type: 1, title: I18n.T('查看二维码'), area: ['26%', 'auto'], shadeClose: false, anim: -1, isOutAnim: false, content: $(".qrcode"), success: function (index, layero) { img = "data:image/jpg;base64," + res.data; $("#code").attr("src", img); //$(".downCode").attr("i", res.data.img); } }) } else { $.luck.error(res.msg); } });
- [HttpPost]
- public JsonResult CreateMpCode(string Id)
- {
- var json = new ToResultJson();
- CreateMpCodeInputDto inputDto = new CreateMpCodeInputDto();
- inputDto.CompCode = WorkContext.CompCode;
- inputDto.scene = Id;
- inputDto.page = "pages/index/index";
- inputDto.width = 280;
- json = WxCommService.GetWxaCodeUnlimit(inputDto);
- return Json(json, JsonRequestBehavior.AllowGet);
- }
//下载图片 function downImg() { downloadFile('qrcode.jpg', img); } function downloadFile(fileName, content) { let aLink = document.createElement('a'); let blob = this.base64ToBlob(content); // new Blob([content]); let evt = document.createEvent('HTMLEvents'); evt.initEvent('click', true, true);// initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为 aLink.download = fileName; aLink.href = URL.createObjectURL(blob); aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));// 兼容火狐 } // base64转blob function base64ToBlob(code) { let parts = code.split(';base64,'); let contentType = parts[0].split(':')[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }
---------------------------------------------------------------------------------------------------------
转载请记得说明作者和出处哦-.-
作者:KingDuDu
原文出处:https://www.cnblogs.com/kingdudu/articles/12675554.html
---------------------------------------------------------------------------------------------------------
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。