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

        /// <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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要用Java获取微信小程序,首先需要使用微信提供的API接口来实现。以下是一种实现方法: 1. 首先,需要引入相关的依赖包和类库,例如使用HttpClient库来发送HTTP请求,使用JSON库来处理返回的JSON数据。 2. 在代中构建请求URL,将appid和appsecret等参数拼接到URL中,例如: String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=YOUR_APPID&secret=YOUR_SECRET"; 3. 使用HttpClient库发送GET请求,并获取返回的JSON数据,例如: HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); int statusCode = httpClient.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { String response = getMethod.getResponseBodyAsString(); JSONObject json = new JSONObject(response); String accessToken = json.optString("access_token"); // 这里获取到的accessToken是后续获取小程序时需要用到的凭证 } 4. 构建获取小程序的请求URL,将需要的参数拼接到URL中,例如: String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"; JSONObject requestData = new JSONObject(); requestData.put("scene", "YOUR_SCENE"); requestData.put("page", "YOUR_PAGE"); // 这里的YOUR_SCENE和YOUR_PAGE是你自定义的场景值和小程序页面路径值 5. 使用HttpClient库发送POST请求,并将requestData转换为JSON字符串作为请求的内容,获取小程序的二进制数据,例如: HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(codeUrl); postMethod.setRequestEntity(new StringRequestEntity(requestData.toString(), "application/json", "UTF-8")); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { // 获取小程序的二进制数据 byte[] responseBody = postMethod.getResponseBody(); // 这里可以将responseBody保存为图片或其他适合的格式 } 以上是使用Java获取微信小程序的一个简单示例,具体操作还可能受微信官方接口的限制,因此在实际应用中还需要根据接口文档进行适当的调整和处理。 ### 回答2: 要通过Java获取微信小程序,需要使用微信官方提供的开发工具包和API接口。 首先,你需要在微信开放平台上注册一个小程序并获得小程序的唯一标识AppID。 然后,在Java项目中引入相关的开发工具包,例如微信官方提供的Java SDK或第三方封装的SDK。 接下来,通过SDK提供的接口调用微信的API来获取小程序。你可以使用微信官方提供的CreateWXAQRCode接口,该接口可以生成小程序的图片或base64编,并保存在指定的路径。 具体的步骤如下: 1. 创建一个HttpClient对象,并通过HttpPost请求访问微信的API接口。 2. 设置请求的URL为微信的API地址,例如https://api.weixin.qq.com/wxa/getwxacodeunlimit。 3. 设置请求的参数,包括小程序的AppID、Access Token(获取方法见微信开放平台文档)、参数scene(小程序的参数,根据不同的需求进行设置)等。 4. 设置请求的Header信息,包括Content-Type等。 5. 发送请求并获取响应结果。 6. 解析响应结果,判断请求是否成功,如果成功,则从响应结果中提取出小程序的图片或base64编,并保存或处理。 需要注意的是,微信小程序的生成是有一定限制的,例如小程序的有效期等,你需要根据需要在代中进行相应的处理。 总结起来,通过上述步骤,你就可以使用Java来获取微信小程序了。当然,具体的实现细节还需要参考微信开放平台的开发文档和SDK的使用说明。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值