• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
        /// <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

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
获取小程序指定页面的小程序码发布时间:2022-07-18
下一篇:
微信小程序通过二维码获取参数运行发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap