当前位置:   article > 正文

【第二十六篇】获取微信小程序码_c#getwxacodeunlimit

c#getwxacodeunlimit
  1. /// <summary>
  2. /// 创建小程序码
  3. /// </summary>
  4. /// <returns>返回Base64图片字符串</returns>
  5. public static ToResultJson GetWxaCodeUnlimit(CreateMpCodeInputDto inputDto)
  6. {
  7. string secret = string.Empty;
  8. CollectMoneyInfoDto coll = new CompService().GetCollectMoneyInfo(inputDto.CompCode);
  9. inputDto.AppID = coll.AppID;
  10. var authorizationInfo = new CompService().GetCollectMoneyAuthorizationInfo(inputDto.AppID);
  11. if (authorizationInfo != null)
  12. {
  13. secret = authorizationInfo.AppSecret;
  14. }
  15. else
  16. {
  17. secret = new CompService().GetPlatformAppSecret(inputDto.AppID);
  18. }
  19. string token = GetMPToken(inputDto.AppID, secret);
  20. if (string.IsNullOrEmpty(token))
  21. {
  22. return new ToResultJson(0, "990201");//获取小程序令牌失败
  23. }
  24. string strURL = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", token);
  25. int aCodeWidth = inputDto.width;
  26. if (inputDto.width < 280)
  27. {
  28. aCodeWidth = 280;
  29. }
  30. if (inputDto.width > 1280)
  31. {
  32. aCodeWidth = 1280;
  33. }
  34. GetWxaCodeUnlimitInputDto getWxaCodeUnlimitInputDto = new GetWxaCodeUnlimitInputDto()
  35. {
  36. auto_color = false,
  37. is_hyaline = false,
  38. line_color = new GetWxaCodeUnlimitLineColorDto
  39. {
  40. r = 0,
  41. g = 0,
  42. b = 0
  43. },
  44. width = aCodeWidth,
  45. page = string.IsNullOrWhiteSpace(inputDto.page) ? string.Empty : inputDto.page,
  46. scene = string.IsNullOrWhiteSpace(inputDto.scene) ? string.Empty : inputDto.scene,
  47. };
  48. string dataJson = JsonConvert.SerializeObject(getWxaCodeUnlimitInputDto);
  49. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
  50. request.Method = "POST";
  51. request.ContentType = "application/json;charset=UTF-8";
  52. byte[] payload = Encoding.UTF8.GetBytes(dataJson);
  53. request.ContentLength = payload.Length;
  54. Stream writer = request.GetRequestStream();
  55. writer.Write(payload, 0, payload.Length);
  56. writer.Close();
  57. System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  58. var stream = response.GetResponseStream();//返回图片数据流
  59. var memoryStream = new MemoryStream();
  60. //将基础流写入内存流
  61. const int bufferLength = 1024;
  62. byte[] buffer = new byte[bufferLength];
  63. int count = 0;
  64. while ((count = stream.Read(buffer, 0, bufferLength)) > 0)
  65. {
  66. memoryStream.Write(buffer, 0, count);
  67. }
  68. memoryStream.Position = 0;
  69. string strBase64 = Convert.ToBase64String(memoryStream.GetBuffer());
  70. return new ToResultJson(1, "000000") { data = strBase64 };
  71. }
  1. /// <summary>
  2. /// 获取小程序token
  3. /// </summary>
  4. /// <returns></returns>
  5. public static string GetMPToken(string appid, string secret)
  6. {
  7. string token = string.Empty;
  8. string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
  9. var url = string.Format(strUrl, appid, secret);
  10. var response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, null, null);
  11. if (response.StatusCode == HttpStatusCode.OK)
  12. {
  13. Stream receiveStream = response.GetResponseStream();
  14. StreamReader streamReader = new StreamReader(receiveStream, Encoding.UTF8);
  15. string jsonStr = streamReader.ReadToEnd();
  16. if (!string.IsNullOrEmpty(jsonStr))
  17. {
  18. try
  19. {
  20. var objToken = JsonConvert.DeserializeObject<JObject>(jsonStr);
  21. if (objToken != null && objToken.GetValue("errcode") == null)
  22. {
  23. return objToken.GetValue("access_token").ToString();
  24. }
  25. return string.Empty;
  26. }
  27. catch (Exception ex)
  28. {
  29. LoggerHelper.Error("获取小程序token失败", ex);
  30. }
  31. }
  32. }
  33. return token;
  34. }
 
  1. $.http.post('/Setup/Store/CreateMpCode', { Id: obj.data.Id }, function (res) {
  2. if (res.status == "1") {
  3. layer.open({
  4. type: 1,
  5. title: I18n.T('查看二维码'),
  6. area: ['26%', 'auto'],
  7. shadeClose: false,
  8. anim: -1,
  9. isOutAnim: false,
  10. content: $(".qrcode"),
  11. success: function (index, layero) {
  12. img = "data:image/jpg;base64," + res.data;
  13. $("#code").attr("src", img);
  14. //$(".downCode").attr("i", res.data.img);
  15. }
  16. })
  17. } else {
  18. $.luck.error(res.msg);
  19. }
  20. });
 

 

  1. [HttpPost]
  2. public JsonResult CreateMpCode(string Id)
  3. {
  4. var json = new ToResultJson();
  5. CreateMpCodeInputDto inputDto = new CreateMpCodeInputDto();
  6. inputDto.CompCode = WorkContext.CompCode;
  7. inputDto.scene = Id;
  8. inputDto.page = "pages/index/index";
  9. inputDto.width = 280;
  10. json = WxCommService.GetWxaCodeUnlimit(inputDto);
  11. return Json(json, JsonRequestBehavior.AllowGet);
  12. }
  1. //下载图片
  2. function downImg() {
  3. downloadFile('qrcode.jpg', img);
  4. }
  5. function downloadFile(fileName, content) {
  6. let aLink = document.createElement('a');
  7. let blob = this.base64ToBlob(content); // new Blob([content]);
  8. let evt = document.createEvent('HTMLEvents');
  9. evt.initEvent('click', true, true);// initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
  10. aLink.download = fileName;
  11. aLink.href = URL.createObjectURL(blob);
  12. aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));// 兼容火狐
  13. }
  14. // base64转blob
  15. function base64ToBlob(code) {
  16. let parts = code.split(';base64,');
  17. let contentType = parts[0].split(':')[1];
  18. let raw = window.atob(parts[1]);
  19. let rawLength = raw.length;
  20. let uInt8Array = new Uint8Array(rawLength);
  21. for (let i = 0; i < rawLength; ++i) {
  22. uInt8Array[i] = raw.charCodeAt(i);
  23. }
  24. return new Blob([uInt8Array], { type: contentType });
  25. }

 

--------------------------------------------------------------------------------------------------------- 

转载请记得说明作者和出处哦-.-
作者:KingDuDu
原文出处:https://www.cnblogs.com/kingdudu/articles/12675554.html

---------------------------------------------------------------------------------------------------------

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/942353
推荐阅读
相关标签
  

闽ICP备14008679号