2 コミット 70891f447f ... e9d4f56649

作者 SHA1 メッセージ 日付
  2510966293@qq.com e9d4f56649 Merge remote-tracking branch 'origin/master' 5 年 前
  2510966293@qq.com 7053ff02b3 小程序二维码生成 5 年 前
共有3 個のファイルを変更した351 個の追加0 個の削除を含む
  1. 231 0
      src/main/java/com/yc/education/controller/WxController.java
  2. 120 0
      src/main/java/com/yc/education/util/JsonTools.java
  3. 0 0
      src/main/webapp/qrcode/none.txt

+ 231 - 0
src/main/java/com/yc/education/controller/WxController.java

@@ -0,0 +1,231 @@
+package com.yc.education.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.yc.education.model.Provider;
+import com.yc.education.service.IProviderService;
+import com.yc.education.util.JsonTools;
+import com.yc.education.util.WxConfig;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.*;
+import org.springframework.stereotype.Controller;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.client.RestTemplate;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Author: BlueSky
+ * @CreateTime: 2019-10-10 15:55
+ * @Description: 小程序二维码生成
+ */
+@Controller
+@RequestMapping("/qr")
+public class WxController {
+
+    final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WxController.class);
+
+
+    @Autowired
+    private IProviderService iProviderService;
+
+    String token = "26_CAB5DE5JCoFo1GDwhWaxLKowWL_YyDrnuDbJx_6LuI7AJaP-36KgveN3u1VycOrAiq3T6CuXw_AZw00bKw2ijaqZmG2LzptZzl8Lx7WV-K_OBmBoFNIGK8QPmnceLfmKmWJbYVtDbW21ICQ9BQYgAEAGVD-jtZ3A36lZOatzTYxDiNcY2UeQMJhPZCCfAAALOO";
+
+    String contextPath = "";
+
+    /**
+    * @Description: 获取二维码
+    * @Author: BlueSky
+    * @CreateTime: 2019/10/10 16:39
+    */
+    @RequestMapping("/qrcode")
+    @ResponseBody
+    public ResponseEntity<byte[]> getaccess_tokenurl(String shopId, HttpServletRequest request) {
+        contextPath = request.getSession().getServletContext().getRealPath("/");
+        HttpSession session=request.getSession();
+        String access_token="";
+        if (session.getAttribute("userInfo")!=null){
+            access_token= JsonTools.getJsonValue((String) session.getAttribute("userInfo"), "access_token");
+        }else {
+            String getaccess_tokenurl = "https://api.weixin.qq.com/cgi-bin/token?" +
+                    "grant_type=client_credential" +
+                    "&appid=" + WxConfig.APP_ID +
+                    "&secret=" + WxConfig.APP_SECRET;
+            RestTemplate restTemplate1 = new RestTemplate();
+            String response1 = restTemplate1.getForObject(getaccess_tokenurl, String.class);
+            session.setAttribute("userInfo",response1);
+            access_token = JsonTools.getJsonValue(response1, "access_token");
+        }
+        return getOnlyOneCode(access_token,shopId);
+    }
+
+    
+
+    /**
+    * @Description: getwxacodeunlimit接口,二维码无限制,需要小程序已审核上线后才可调用。
+    * @Author: BlueSky
+    * @CreateTime: 2019/10/10 16:46
+    */
+    public  ResponseEntity<byte[]> getminiqrQr(String accessToken,String shopId) {
+        RestTemplate rest = new RestTemplate();
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+        try {
+            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
+            Map<String,Object> param = new HashMap<>();
+            param.put("path", "pages/facilitator/maintain/detail/detail");
+            param.put("width", 430);
+            param.put("scene", shopId);
+            param.put("auto_color", true);
+            Map<String,Object> line_color = new HashMap<>();
+            line_color.put("r", 0);
+            line_color.put("g", 0);
+            line_color.put("b", 0);
+            param.put("line_color", line_color);
+            LOGGER.info("调用生成微信URL接口传参:" + param);
+            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
+
+            ObjectMapper objectMapper = new ObjectMapper();
+            String s = objectMapper.writeValueAsString(param);
+
+            List<String> list = new ArrayList<String>();
+            list.add("Content-Type");
+            list.add("application/json");
+            headers.put("header",list);
+            HttpEntity requestEntity = new HttpEntity(s, headers);
+
+            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
+
+            LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());
+            byte[] result = entity.getBody();
+            inputStream = new ByteArrayInputStream(result);
+            Provider shop = iProviderService.selectByKey(Long.valueOf(shopId));
+
+            File file = new File(contextPath+"/qrcode/"+shop.getName()+".png");
+            outputStream = new FileOutputStream(file);
+            int len = 0;
+            byte[] buf = new byte[1024];
+            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
+                outputStream.write(buf, 0, len);
+            }
+            outputStream.flush();
+
+            HttpHeaders headers_1 = new HttpHeaders();
+            //下载显示的文件名,解决中文名称乱码
+
+            String downLoadFileName = new String (shop.getName().getBytes("UTF-8"),"iso-8859-1");
+            headers_1.setContentDispositionFormData("attachment",downLoadFileName+".png");
+            headers_1.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+
+            return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),
+                    headers_1, HttpStatus.CREATED);
+        } catch (Exception e) {
+            LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);
+        } finally {
+            if(inputStream != null){
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if(outputStream != null){
+                try {
+                    outputStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+    * @Description: getwxacode接口。有数量限制型二维码
+    * @Author: BlueSky
+    * @CreateTime: 2019/10/10 16:40
+    */
+    public  ResponseEntity<byte[]> getOnlyOneCode(String accessToken,String shopId) {
+        RestTemplate rest = new RestTemplate();
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+        try {
+            String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken;
+            Map<String,Object> param = new HashMap<>();
+            param.put("path", "pages/facilitator/maintain/detail/detail");
+            param.put("width", 430);
+            param.put("auto_color", true);
+            Map<String,Object> line_color = new HashMap<>();
+            line_color.put("r", 0);
+            line_color.put("g", 0);
+            line_color.put("b", 0);
+            param.put("line_color", line_color);
+            LOGGER.info("调用生成微信URL接口传参:" + param);
+            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
+
+            ObjectMapper objectMapper = new ObjectMapper();
+            String s = objectMapper.writeValueAsString(param);
+
+            List<String> list = new ArrayList<String>();
+            list.add("Content-Type");
+            list.add("application/json");
+            headers.put("header",list);
+            HttpEntity requestEntity = new HttpEntity(s, headers);
+
+            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
+
+            LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());
+            byte[] result = entity.getBody();
+            inputStream = new ByteArrayInputStream(result);
+
+            Provider shop = iProviderService.selectByKey(Long.valueOf(shopId));
+            File file = new File(contextPath+"/qrcode/"+shop.getName()+".png");
+            outputStream = new FileOutputStream(file);
+            int len = 0;
+            byte[] buf = new byte[1024];
+            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
+                outputStream.write(buf, 0, len);
+            }
+            outputStream.flush();
+
+            HttpHeaders headers_1 = new HttpHeaders();
+            //下载显示的文件名,解决中文名称乱码
+
+
+            String downLoadFileName = new String (shop.getCompanyName().getBytes("UTF-8"),"iso-8859-1");
+            headers_1.setContentDispositionFormData("attachment",downLoadFileName+".png");
+            headers_1.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+
+            return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),
+                    headers_1, HttpStatus.CREATED);
+        } catch (Exception e) {
+            LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);
+        } finally {
+            if(inputStream != null){
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if(outputStream != null){
+                try {
+                    outputStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return null;
+    }
+
+}

+ 120 - 0
src/main/java/com/yc/education/util/JsonTools.java

@@ -0,0 +1,120 @@
+package com.yc.education.util;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @Author: BlueSky
+ * @CreateTime: 2019-10-10 15:58
+ * @Description:
+ */
+public class JsonTools {
+    /**
+     *  该方法是传入string 并转化为json,再根据传入的key获取相关值
+     * @param rescontent 字符串
+     * @param key 字符串中的json关键字
+     * @return
+     */
+    public static String getJsonValue(String rescontent, String key) {
+        org.json.JSONObject jsonObject;
+        String v = null;
+        try {
+            jsonObject = new org.json.JSONObject(rescontent);
+            v = jsonObject.getString(key);
+        } catch (Exception e1) {
+            // TODO Auto-generated catch block
+            e1.printStackTrace();
+        }
+        return v;
+    }
+    //
+    public static JSONObject MapStrString(Map<String,Object> map) {
+        JSONObject a;
+        return a = new JSONObject(map);
+    }
+    /**
+     * 该方法是传入string 并转化为json
+     * @param rescontent
+     * @return
+     */
+    public static org.json.JSONObject StringStrJson(String rescontent) {
+        org.json.JSONObject jsonObject = null;
+        String v = null;
+        try {
+            jsonObject = new org.json.JSONObject(rescontent);
+
+        } catch (Exception e1) {
+            // TODO Auto-generated catch block
+            e1.printStackTrace();
+        }
+        return jsonObject;
+    }
+    /**
+     * json 字符串 转 Map
+     *
+     * @param json
+     * @return
+     */
+    public static Map<String, Object> jsonStrToMap(String json) {
+        Map<String, Object> map = new HashMap<String, Object>();
+        if (json == null || "".equals(json)) {
+            return map;
+        }
+        JSONObject jsonObject = JSON.parseObject(json);
+        Set<String> keys = jsonObject.keySet();
+        for (String key : keys) {
+            map.put(key, jsonObject.get(key));
+        }
+
+        return map;
+    }
+
+    /**
+     * json 字符串 转 java Object
+     *
+     * @param json
+     * @return
+     */
+    public static Object jsonStrToJsonObject(String json, Class<?> clazz) {
+        if (clazz == String.class) {
+            if (json.length() > 2) {
+                // 去掉首尾的引号
+                json = json.substring(1, json.length() - 1);
+            }
+            return json;
+        } else {
+            JSONObject parse = JSON.parseObject(json);
+            return JSON.toJavaObject(parse, clazz);
+        }
+    }
+
+    /**
+     * 对象-->json
+     *
+     * @param obj
+     * @return
+     */
+    public static String toJson(Object obj) {
+        return JSON.toJSONString(obj);
+    }
+
+    public static Map<String, Object> objToMap(Object obj) {
+        String json = toJson(obj);
+        Map<String, Object> map = jsonStrToMap(json);
+        return map;
+    }
+
+
+    public static void main(String[] args) {
+        String json = "{ \"firstName\": \"Brett\", \"lastName\":\"McLaughlin\", \"email\": \"aaaa\" }";
+        Map<String, Object> map = jsonStrToMap(json);
+//		String js = "{\"+\"}";
+        System.err.println(map);
+    }
+
+}
+

+ 0 - 0
src/main/webapp/qrcode/none.txt