springboot实现微信小程序二维码生成

您所在的位置:网站首页 携程小程序二维码 springboot实现微信小程序二维码生成

springboot实现微信小程序二维码生成

2024-07-16 10:33:17| 来源: 网络整理| 查看: 265

一、微信小程序创建

先要去微信公众平台注册一个小程序,每个小程序都有相应的AppID(小程序ID)和AppSecret(小程序密钥),它们是获取ACCESS_TOKEN所需要的。微信公众平台地址:

https://mp.weixin.qq.com/

注册添加小程序后会取得AppID(小程序ID)和AppSecret(小程序密钥):

二、依赖引入 com.alibaba fastjson 1.2.41 org.apache.httpcomponents httpclient org.apache.httpcomponents httpmime com.google.code.gson gson 三、核心代码 @RequestMapping("/QR") @RestController public class QRCodeController { @RequestMapping("/getCode") public void createQRCode(String param, String page, HttpServletResponse response) { OutputStream stream = null; try { //获取AccessToken String accessToken = getAccessToken(); //设置响应类型 response.setContentType("image/png"); String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken; //组装参数 Map paraMap = new HashMap(); //二维码携带参数 不超过32位 参数类型必须是字符串 paraMap.put("scene", param); //二维码跳转页面 paraMap.put("page", page); //二维码的宽度 paraMap.put("width", 450); //自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调 paraMap.put("auto_color", false); //是否需要透明底色, is_hyaline 为true时,生成透明底色的小程序码 paraMap.put("is_hyaline", false); //执行post 获取数据流 byte[] result = HttpClientUtils.doImgPost(url, paraMap); //输出图片到页面 response.setContentType("image/jpg"); stream = response.getOutputStream(); stream.write(result); stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取ACCESS_TOKEN * 官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html *

* 需要正确的 appid 和 secret 查看自己的微信开放平台 */ public String getAccessToken() { //这里需要换成你d的小程序appid String appid = "wx141ac029d803ce4c"; //这里需要换成你的小程序secret String appSecret = "bb245ef5f0add972bccd718087b7dd50"; //获取微信ACCESS_TOKEN 的Url String accent_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; String url = accent_token_url.replace("APPID", appid).replace("APPSECRET", appSecret); //发送请求 String result = HttpClientUtils.doGet(url); Map resultMap = (Map) JsonUtil.jsonToMap(result); System.out.println("access_token------>" + resultMap.get("access_token").toString()); return resultMap.get("access_token").toString(); } } public class HttpClientUtils { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class); private static ConnectionSocketFactory plainsf = null; private static LayeredConnectionSocketFactory sslsf = null; private static Registry registry = null; private static PoolingHttpClientConnectionManager cm = null; private static HttpRequestRetryHandler httpRequestRetryHandler = null; private static RequestConfig requestConfig = null; private static CloseableHttpClient httpClient = null; static { plainsf = PlainConnectionSocketFactory.getSocketFactory(); sslsf = SSLConnectionSocketFactory.getSocketFactory(); registry = RegistryBuilder.create() .register("http", plainsf) .register("https", sslsf) .build(); cm = new PoolingHttpClientConnectionManager(registry); // 最大连接数 cm.setMaxTotal(30); // 每个路由基础的连接 cm.setDefaultMaxPerRoute(10); //请求重试处理 httpRequestRetryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(5000) .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); } /** * get请求 * * @param url 访问ur * @return */ public static String doGet(String url) { String result = null; CloseableHttpResponse response = null; HttpGet httpget = new HttpGet(url); try { String resultEnc = "UTF-8"; httpget.setConfig(requestConfig); response = httpClient.execute(httpget, HttpClientContext.create()); result = EntityUtils.toString(response.getEntity(), resultEnc); } catch (Exception e) { LOGGER.error("get请求 doPost", e); return result; } finally { if (null != response) { try { response.close(); } catch (IOException e) { LOGGER.error("get请求 doPost IOException", e); } } httpget.abort(); } return result; } /** * 获取数据流 * * @param url * @param paraMap * @return */ public static byte[] doImgPost(String url, Map paraMap) { byte[] result = null; HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); try { // 设置请求的参数 JSONObject postData = new JSONObject(); for (Map.Entry entry : paraMap.entrySet()) { postData.put(entry.getKey(), entry.getValue()); } httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8")); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toByteArray(entity); } catch (ConnectionPoolTimeoutException e) { e.printStackTrace(); } catch (ConnectTimeoutException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { httpPost.releaseConnection(); } return result; } } public class JsonUtil { private static Gson gson = new Gson(); public static Map jsonToMap(String jsonStr) { Map objMap = null; if (gson != null) { Type type = new com.google.gson.reflect.TypeToken



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭