Prechádzať zdrojové kódy

微信公众号服务配置-搜索商品

chao 3 rokov pred
rodič
commit
f2a1bc1822

+ 8 - 7
src/main/java/com/caimei365/wechat/service/impl/WechatServerServiceImpl.java

@@ -65,6 +65,7 @@ public class WechatServerServiceImpl implements WechatServerService {
         String timestamp = request.getParameter("timestamp");
         String nonce = request.getParameter("nonce");
         String echostr = request.getParameter("echostr");
+        log.info("验证消息的确来自微信服务器,signature:"+signature+",timestamp:"+timestamp+",nonce:"+nonce+",echostr:"+echostr);
         boolean flag = SignUtil.checkSignature(signature, timestamp, nonce);
         if (flag) {
             return echostr;
@@ -106,13 +107,11 @@ public class WechatServerServiceImpl implements WechatServerService {
             }
         }
         log.info(">>>>>>>>>>模糊搜索:" + keyword);
+        // 搜索商品: https://core.caimei365.com/commodity/search/query/product?keyword=
         WechatArticleDetail article = null;
-        RestTemplate restTemplate = new RestTemplate();
-        // https://core.caimei365.com/commodity/search/query/product?keyword=
-        String uri = coreDomain + "/commodity/search/query/product?keyword="+keyword;
         try {
-            String jsonResult = HttpUtil.httpRequest(URLEncoder.encode(uri, "UTF-8"), "GET", null);
-            log.info(">>>>>>>>>>uri:" + uri + ",jsonResult:" + jsonResult);
+            String uri = coreDomain + "/commodity/search/query/product?keyword="+URLEncoder.encode(keyword, "UTF-8" );
+            String jsonResult = HttpUtil.sendGet(uri);
             if(StringUtils.hasLength(jsonResult)){
                 JSONObject jsonObject = JSON.parseObject(jsonResult);
                 String data = jsonObject.getString("data");
@@ -124,7 +123,7 @@ public class WechatServerServiceImpl implements WechatServerService {
                             article = new WechatArticleDetail();
                             article.setTitle("帮您匹配到"+ total + "个商品,点击查看");
                             article.setPicUrl(imageDomain + "/group1/M00/03/EC/rB-lGGHg9ZOAe8VdAAJevlD1ofg562.png");
-                            String url = wwwDomain + "product/list.html?keyword="+keyword;
+                            String url = wwwDomain + "/product/list.html?keyword="+keyword;
                             try {
                                 url = URLEncoder.encode(url, "UTF-8");
                             } catch (UnsupportedEncodingException ignored) {}
@@ -133,7 +132,9 @@ public class WechatServerServiceImpl implements WechatServerService {
                     }
                 }
             }
-        } catch (Exception ignored) {}
+        } catch (Exception e) {
+            log.error(e.toString());
+        }
         if (null != article) {
             List<WechatArticleDetail> articles = new ArrayList<>();
             articles.add(article);

+ 99 - 4
src/main/java/com/caimei365/wechat/utils/HttpUtil.java

@@ -6,13 +6,13 @@ import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocketFactory;
 import javax.net.ssl.TrustManager;
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
+import java.io.*;
 import java.net.URL;
+import java.net.URLConnection;
 import java.nio.charset.StandardCharsets;
 import java.security.cert.X509Certificate;
+import java.util.List;
+import java.util.Map;
 
 /**
  * HTTP 请求工具类
@@ -82,4 +82,99 @@ public class HttpUtil {
         return null;
     }
 
+    /**
+     * 向指定URL发送GET方法的请求
+     *
+     * @param url   发送请求的URL,请求参数应该是 name1=value1&name2=value2 的形式。
+     * @return 远程资源的响应结果
+     */
+    public static String sendGet(String url) throws Exception {
+        StringBuilder result = new StringBuilder();
+        BufferedReader in = null;
+        try {
+
+            URL realUrl = new URL(url);
+            // 打开和URL之间的连接
+            URLConnection connection = realUrl.openConnection();
+            // 设置通用的请求属性
+            connection.setRequestProperty("accept", "*/*");
+            connection.setRequestProperty("connection", "Keep-Alive");
+            connection.setRequestProperty("Accept-Charset", "utf-8");
+            connection.setRequestProperty("contentType", "utf-8");
+            connection.setConnectTimeout(5000);
+            // 建立实际的连接
+            connection.connect();
+            // 获取所有响应头字段
+            Map<String, List<String>> map = connection.getHeaderFields();
+            // 定义 BufferedReader输入流来读取URL的响应
+            in = new BufferedReader(new InputStreamReader(
+                    connection.getInputStream()));
+            String line;
+            while ((line = in.readLine()) != null) {
+                result.append(line);
+            }
+        }
+        // 使用finally块来关闭输入流
+        finally {
+            if (in != null) {
+                in.close();
+            }
+        }
+        return result.toString();
+    }
+
+    /**
+     * 向指定 URL 发送POST方法的请求
+     *
+     * @param url 发送请求的 URL
+     * @param paramMap 请求参数
+     * @return 所代表远程资源的响应结果
+     */
+    public static String sendPost(String url, Map<String, ?> paramMap) throws Exception{
+        PrintWriter out = null;
+        BufferedReader in = null;
+        StringBuilder result = new StringBuilder();
+
+        StringBuilder param = new StringBuilder();
+
+        for (String key : paramMap.keySet()) {
+            param.append(key).append("=").append(paramMap.get(key)).append("&");
+        }
+
+        try {
+            URL realUrl = new URL(url);
+            // 打开和URL之间的连接
+            URLConnection conn = realUrl.openConnection();
+            // 设置通用的请求属性
+            conn.setRequestProperty("accept", "*/*");
+            conn.setRequestProperty("connection", "Keep-Alive");
+            conn.setRequestProperty("Accept-Charset", "utf-8");
+            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
+            // 发送POST请求必须设置如下两行
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(conn.getOutputStream());
+            // 发送请求参数
+            out.print(param);
+            // flush输出流的缓冲
+            out.flush();
+            // 定义BufferedReader输入流来读取URL的响应
+            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
+            String line;
+            while ((line = in.readLine()) != null) {
+                result.append(line);
+            }
+        }
+        //使用finally块来关闭输出流、输入流
+        finally{
+            if(out!=null){
+                out.close();
+            }
+            if(in!=null){
+                in.close();
+            }
+        }
+        return result.toString();
+    }
 }

+ 2 - 1
src/main/java/com/caimei365/wechat/utils/MessageUtil.java

@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.dom4j.Document;
 import org.dom4j.Element;
 import org.dom4j.io.SAXReader;
+import org.springframework.util.StringUtils;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.InputStream;
@@ -120,7 +121,7 @@ public class MessageUtil {
             if (null != article) {
                 content.append("<item>");
                 content.append("<Title><![CDATA[").append(article.getTitle()).append("]]></Title>");
-                content.append("<Description><![CDATA[").append(article.getDescription()).append("]]></Description>");
+                content.append("<Description><![CDATA[").append(StringUtils.hasLength(article.getDescription()) ? article.getDescription() : "").append("]]></Description>");
                 content.append("<PicUrl><![CDATA[").append(article.getPicUrl()).append("]]></PicUrl>");
                 content.append("<Url><![CDATA[").append(article.getUrl()).append("]]></Url>");
                 content.append("</item>");

+ 10 - 9
src/main/java/com/caimei365/wechat/utils/SignUtil.java

@@ -1,6 +1,7 @@
 package com.caimei365.wechat.utils;
 
 import com.caimei365.wechat.entity.WeChatConstant;
+import lombok.extern.slf4j.Slf4j;
 
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
@@ -12,6 +13,7 @@ import java.util.Arrays;
  * @author : Charles
  * @date : 2022/1/13
  */
+@Slf4j
 public class SignUtil {
 
     /**
@@ -27,21 +29,20 @@ public class SignUtil {
         // 微信 - 服务器配置 -令牌(Token)
         String token = WeChatConstant.TOKEN;
         String[] arr = new String[] {token, timestamp, nonce};
-        // 将token、timestamp、nonce三个参数进行字典序排序
-        Arrays.sort(arr);
-        StringBuilder content = new StringBuilder();
-        for (String s : arr) {
-            content.append(s);
-        }
-        MessageDigest md = null;
         String tmpStr = null;
         try {
-            md = MessageDigest.getInstance("SHA-1");
+            // 将token、timestamp、nonce三个参数进行字典序排序
+            Arrays.sort(arr);
+            StringBuilder content = new StringBuilder();
+            for (String s : arr) {
+                content.append(s);
+            }
+            MessageDigest md = MessageDigest.getInstance("SHA-1");
             // 将三个参数字符串拼接成一个字符串进行sha1加密
             byte[] digest = md.digest(content.toString().getBytes());
             tmpStr = byteToStr(digest);
         } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
+            log.error(e.toString());
         }
         // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
         return tmpStr != null && tmpStr.equals(signature.toUpperCase());