Ver código fonte

微信小程序

魏熙美 6 anos atrás
pai
commit
08a8b4d8e7

+ 26
- 0
whole-estate/pom.xml Ver arquivo

@@ -123,6 +123,32 @@
123 123
             <version>2.7.0</version>
124 124
         </dependency>
125 125
 
126
+        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
127
+        <dependency>
128
+            <groupId>com.squareup.okhttp3</groupId>
129
+            <artifactId>okhttp</artifactId>
130
+            <version>3.11.0</version>
131
+        </dependency>
132
+
133
+        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
134
+        <dependency>
135
+            <groupId>com.google.guava</groupId>
136
+            <artifactId>guava</artifactId>
137
+            <version>26.0-jre</version>
138
+        </dependency>
139
+
140
+        <dependency>
141
+            <groupId>org.jodd</groupId>
142
+            <artifactId>jodd-bean</artifactId>
143
+            <version>3.7.1</version>
144
+        </dependency>
145
+
146
+        <dependency>
147
+            <groupId>commons-collections</groupId>
148
+            <artifactId>commons-collections</artifactId>
149
+            <version>3.2.1</version>
150
+        </dependency>
151
+
126 152
     </dependencies>
127 153
 
128 154
     <build>

+ 237
- 0
whole-estate/src/main/java/com/example/wholeestate/common/http/OkHttpRequestUtils.java Ver arquivo

@@ -0,0 +1,237 @@
1
+package com.example.wholeestate.common.http;
2
+
3
+import com.google.common.collect.Maps;
4
+import okhttp3.*;
5
+
6
+import java.io.ByteArrayOutputStream;
7
+import java.io.File;
8
+import java.io.FileInputStream;
9
+import java.util.Iterator;
10
+import java.util.Map;
11
+
12
+/**
13
+ * 封装请求
14
+ * @author weiximei
15
+ */
16
+public class OkHttpRequestUtils {
17
+
18
+    // 定义请求客户端
19
+    private static OkHttpClient client = new OkHttpClient();
20
+
21
+    /**
22
+     * get 请求
23
+     * @param url 请求URL
24
+     * @return
25
+     * @throws Exception
26
+     */
27
+    public static String doGet(String url) throws Exception {
28
+       return doGet(url, Maps.newHashMap());
29
+    }
30
+
31
+
32
+    /**
33
+     * get 请求
34
+     * @param url 请求URL
35
+     * @param query 携带参数参数
36
+     * @return
37
+     * @throws Exception
38
+     */
39
+    public static String doGet(String url, Map<String, Object> query) throws Exception {
40
+
41
+        return doGet(url, Maps.newHashMap(), query);
42
+    }
43
+
44
+    /**
45
+     * get 请求
46
+     * @param url url
47
+     * @param header 请求头参数
48
+     * @param query 参数
49
+     * @return
50
+     */
51
+    public static String doGet(String url, Map<String, Object> header, Map<String, Object> query) throws Exception {
52
+
53
+        // 创建一个请求 Builder
54
+        Request.Builder builder = new Request.Builder();
55
+        // 创建一个 request
56
+        Request request = builder.url(url).build();
57
+
58
+        // 创建一个 HttpUrl.Builder
59
+        HttpUrl.Builder urlBuilder = request.url().newBuilder();
60
+        // 创建一个 Headers.Builder
61
+        Headers.Builder headerBuilder = request.headers().newBuilder();
62
+
63
+        // 装载请求头参数
64
+        Iterator<Map.Entry<String, Object>> headerIterator = header.entrySet().iterator();
65
+        headerIterator.forEachRemaining(e -> {
66
+            headerBuilder.add(e.getKey(), (String) e.getValue());
67
+        });
68
+
69
+        // 装载请求的参数
70
+        Iterator<Map.Entry<String, Object>> queryIterator = query.entrySet().iterator();
71
+        queryIterator.forEachRemaining(e -> {
72
+            urlBuilder.addQueryParameter(e.getKey(), (String) e.getValue());
73
+        });
74
+
75
+        // 设置自定义的 builder
76
+        builder.url(urlBuilder.build()).headers(headerBuilder.build());
77
+
78
+        try (Response execute = client.newCall(builder.build()).execute()) {
79
+            return execute.body().string();
80
+        }
81
+    }
82
+
83
+    /**
84
+     * post 请求, 请求参数 并且 携带文件上传
85
+     * @param url
86
+     * @param header
87
+     * @param parameter
88
+     * @param file
89
+     * @return
90
+     * @throws Exception
91
+     */
92
+    public static String doPost(String url, Map<String, Object> header, Map<String, Object> parameter, File file) throws Exception {
93
+
94
+        // 创建一个请求 Builder
95
+        Request.Builder builder = new Request.Builder();
96
+        // 创建一个 request
97
+        Request request = builder.url(url).build();
98
+
99
+        // 创建一个 Headers.Builder
100
+        Headers.Builder headerBuilder = request.headers().newBuilder();
101
+
102
+        // 装载请求头参数
103
+        Iterator<Map.Entry<String, Object>> headerIterator = header.entrySet().iterator();
104
+        headerIterator.forEachRemaining(e -> {
105
+            headerBuilder.add(e.getKey(), (String) e.getValue());
106
+        });
107
+
108
+        MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
109
+
110
+        // 状态请求参数
111
+        Iterator<Map.Entry<String, Object>> queryIterator = parameter.entrySet().iterator();
112
+        queryIterator.forEachRemaining(e -> {
113
+            requestBuilder.addFormDataPart(e.getKey(), (String) e.getValue());
114
+        });
115
+
116
+        if (null != file) {
117
+            // application/octet-stream
118
+            requestBuilder.addFormDataPart("uploadFiles", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
119
+        }
120
+
121
+        // 设置自定义的 builder
122
+        builder.headers(headerBuilder.build()).post(requestBuilder.build());
123
+
124
+        // 然后再 build 一下
125
+        try (Response execute = client.newCall(builder.build()).execute()) {
126
+            return execute.body().string();
127
+        }
128
+    }
129
+
130
+    /**
131
+     * post 请求, 请求参数 并且 携带文件上传二进制流
132
+     * @param url
133
+     * @param header
134
+     * @param parameter
135
+     * @param fileName 文件名
136
+     * @param fileByte 文件的二进制流
137
+     * @return
138
+     * @throws Exception
139
+     */
140
+    public static String doPost(String url, Map<String, Object> header, Map<String, Object> parameter, String fileName, byte [] fileByte) throws Exception {
141
+// 创建一个请求 Builder
142
+        Request.Builder builder = new Request.Builder();
143
+        // 创建一个 request
144
+        Request request = builder.url(url).build();
145
+
146
+        // 创建一个 Headers.Builder
147
+        Headers.Builder headerBuilder = request.headers().newBuilder();
148
+
149
+        // 装载请求头参数
150
+        Iterator<Map.Entry<String, Object>> headerIterator = header.entrySet().iterator();
151
+        headerIterator.forEachRemaining(e -> {
152
+            headerBuilder.add(e.getKey(), (String) e.getValue());
153
+        });
154
+
155
+        MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
156
+
157
+        // 状态请求参数
158
+        Iterator<Map.Entry<String, Object>> queryIterator = parameter.entrySet().iterator();
159
+        queryIterator.forEachRemaining(e -> {
160
+            requestBuilder.addFormDataPart(e.getKey(), (String) e.getValue());
161
+        });
162
+
163
+        if (fileByte.length > 0) {
164
+            // application/octet-stream
165
+            requestBuilder.addFormDataPart("uploadFiles", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), fileByte));
166
+        }
167
+
168
+        // 设置自定义的 builder
169
+        builder.headers(headerBuilder.build()).post(requestBuilder.build());
170
+
171
+        try (Response execute = client.newCall(builder.build()).execute()) {
172
+            return execute.body().string();
173
+        }
174
+    }
175
+
176
+
177
+    /**
178
+     * post 请求  携带文件上传
179
+     * @param url
180
+     * @param file
181
+     * @return
182
+     * @throws Exception
183
+     */
184
+    public static String doPost(String url, File file) throws Exception {
185
+        return doPost(url, Maps.newHashMap(), Maps.newHashMap(), file);
186
+    }
187
+
188
+    /**
189
+     * post 请求
190
+     * @param url
191
+     * @param header 请求头
192
+     * @param parameter 参数
193
+     * @return
194
+     * @throws Exception
195
+     */
196
+    public static String doPost(String url, Map<String, Object> header, Map<String, Object> parameter) throws Exception {
197
+        return doPost(url, header, parameter, null);
198
+    }
199
+
200
+    /**
201
+     * post 请求
202
+     * @param url
203
+     * @param parameter 参数
204
+     * @return
205
+     * @throws Exception
206
+     */
207
+    public static String doPost(String url, Map<String, Object> parameter) throws Exception {
208
+        return doPost(url, Maps.newHashMap(), parameter, null);
209
+    }
210
+
211
+    public static void main(String[] args) throws Exception {
212
+
213
+        byte [] fileByte = null;
214
+
215
+        File file = new File("C:\\Users\\szc\\Pictures\\file-read-4182.jpg");
216
+        FileInputStream fileInputStream = new FileInputStream(file);
217
+
218
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
219
+        byte[] b = new byte[1024];
220
+        int n;
221
+        while ((n = fileInputStream.read(b)) != -1)
222
+        {
223
+            bos.write(b, 0, n);
224
+        }
225
+        fileInputStream.close();
226
+        bos.close();
227
+        fileByte = bos.toByteArray();
228
+
229
+
230
+        Map<String, Object> queryMap = Maps.newHashMap();
231
+        queryMap.put("pageNum","2");
232
+        queryMap.put("pageSize","50");
233
+        System.out.println(OkHttpRequestUtils.doPost("http://localhost:8080/uploadImage" , Maps.newHashMap(), Maps.newHashMap(),file.getName(), fileByte));
234
+
235
+    }
236
+
237
+}

+ 1
- 0
whole-estate/src/main/java/com/example/wholeestate/controller/CustomerController.java Ver arquivo

@@ -82,4 +82,5 @@ public class CustomerController extends BaseController {
82 82
         return responseBean;
83 83
     }
84 84
 
85
+
85 86
 }

+ 12
- 0
whole-estate/src/main/java/com/example/wholeestate/controller/WxUserController.java Ver arquivo

@@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation;
10 10
 import org.springframework.beans.factory.annotation.Autowired;
11 11
 import org.springframework.web.bind.annotation.*;
12 12
 
13
+import javax.servlet.http.HttpSession;
14
+
13 15
 @RestController
14 16
 @RequestMapping("/")
15 17
 @Api(value = "微信小程序 用户 API", description = "微信小程序 用户 API")
@@ -41,4 +43,14 @@ public class WxUserController extends BaseController {
41 43
         return responseBean;
42 44
     }
43 45
 
46
+    @RequestMapping(value = "/wx/getOpenid/{code}", method = RequestMethod.GET)
47
+    @ApiOperation(value = "微信小程序获取 openid", notes = "微信小程序获取 openid")
48
+    @ApiImplicitParams({
49
+            @ApiImplicitParam(paramType = "path", dataTypeClass=String.class, name = "code", value = "code"),
50
+    })
51
+    public ResponseBean getOpenid(@PathVariable(value = "code") String code, HttpSession session){
52
+        ResponseBean  responseBean = iCustomerService.wxOpenid(code);
53
+        return responseBean;
54
+    }
55
+
44 56
 }

+ 4
- 0
whole-estate/src/main/java/com/example/wholeestate/model/Customer.java Ver arquivo

@@ -49,5 +49,9 @@ public class Customer implements Serializable {
49 49
 
50 50
     private String avatar;
51 51
 
52
+    /**
53
+     * 0 未注册 1 已注册
54
+     */
55
+    private Integer hasReg;
52 56
 
53 57
 }

+ 8
- 0
whole-estate/src/main/java/com/example/wholeestate/service/ICustomerService.java Ver arquivo

@@ -42,4 +42,12 @@ public interface ICustomerService extends IService<Customer> {
42 42
      */
43 43
     ResponseBean getWXCustomer(String openid);
44 44
 
45
+    /**
46
+     * 根据 code 获取 openid
47
+     *
48
+     * @param code
49
+     * @return
50
+     */
51
+    ResponseBean wxOpenid(String code);
52
+
45 53
 }

+ 43
- 2
whole-estate/src/main/java/com/example/wholeestate/service/impl/CustomerServiceImpl.java Ver arquivo

@@ -13,6 +13,8 @@ import com.example.wholeestate.dao.CustomerMapper;
13 13
 import com.example.wholeestate.model.Building;
14 14
 import com.example.wholeestate.model.Customer;
15 15
 import com.example.wholeestate.service.ICustomerService;
16
+import com.example.wholeestate.utils.BeanTools;
17
+import com.example.wholeestate.wx.mini.IWxMini;
16 18
 import org.springframework.beans.factory.annotation.Autowired;
17 19
 import org.springframework.stereotype.Service;
18 20
 
@@ -35,6 +37,9 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
35 37
     @Autowired
36 38
     private CustomerMapper customerMapper;
37 39
 
40
+    @Autowired
41
+    private IWxMini iWxMini;
42
+
38 43
     private IdGen idGen = IdGen.get();
39 44
 
40 45
     @Override
@@ -73,9 +78,20 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
73 78
         Customer customer = JSONObject.parseObject(parameter, Customer.class);
74 79
         customer.setCreateDate(LocalDateTime.now());
75 80
         customer.setStatus(1);
81
+        customer.setHasReg(1);
76 82
 
77
-        customer.setCustomerId(idGen.nextId()+"");
78
-        customerMapper.insert(customer);
83
+        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
84
+        queryWrapper.eq("openid", customer.getOpenid());
85
+        Customer selectOne = customerMapper.selectOne(queryWrapper);
86
+        if (null == selectOne) {
87
+            responseBean.addError("用户不存在!");
88
+            return responseBean;
89
+        }
90
+
91
+        BeanTools.copyProperties(customer, selectOne);
92
+
93
+        customerMapper.update(selectOne, queryWrapper);
94
+        responseBean.addSuccess("操作成功!");
79 95
         return responseBean;
80 96
     }
81 97
 
@@ -93,4 +109,29 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
93 109
         responseBean.addSuccess(customer);
94 110
         return responseBean;
95 111
     }
112
+
113
+    @Override
114
+    public ResponseBean wxOpenid(String code) {
115
+        ResponseBean responseBean = new ResponseBean();
116
+        String openid = iWxMini.getOpenid(code);
117
+
118
+        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
119
+        queryWrapper.eq("openid", openid);
120
+        Customer customer = customerMapper.selectOne(queryWrapper);
121
+        if (null != customer) {
122
+            responseBean.addSuccess(customer);
123
+            return responseBean;
124
+        }
125
+
126
+        customer = new Customer();
127
+        customer.setCustomerId(idGen.nextId() + "");
128
+        customer.setCreateDate(LocalDateTime.now());
129
+        customer.setOpenid(openid);
130
+        customer.setHasReg(0);
131
+
132
+        customerMapper.insert(customer);
133
+
134
+        responseBean.addSuccess(customer);
135
+        return responseBean;
136
+    }
96 137
 }

+ 137
- 0
whole-estate/src/main/java/com/example/wholeestate/utils/BeanTools.java Ver arquivo

@@ -0,0 +1,137 @@
1
+package com.example.wholeestate.utils;
2
+
3
+import jodd.bean.BeanCopy;
4
+import jodd.typeconverter.TypeConverterManager;
5
+import org.apache.commons.collections.BeanMap;
6
+import org.springframework.beans.BeanUtils;
7
+import org.springframework.beans.BeanWrapper;
8
+import org.springframework.beans.BeanWrapperImpl;
9
+
10
+import java.beans.PropertyDescriptor;
11
+import java.lang.reflect.Method;
12
+import java.util.*;
13
+
14
+@SuppressWarnings("deprecation")
15
+public final class BeanTools {
16
+
17
+    private static Map<String, Object> toBeanMethodMap = new HashMap<String, Object>();
18
+
19
+    /**
20
+     * <pre>
21
+     * 功能:实现BEAN的属性对拷
22
+     * 创建人:JokenWang
23
+     * </pre>
24
+     *
25
+     * @param fromBean        待转换的源bean
26
+     * @param toBeanClassName 转换成目标bean的名称 形如:ItemSeries.class.getName()
27
+     * @return 目标BEAN类
28
+     */
29
+    public static <T> T convertBean(Object fromBean, Class<T> toBeanClassName) {
30
+        T toBean = null;
31
+        try {
32
+            toBean = getBeanInstance(toBeanClassName.getName());
33
+            return convertBean(fromBean, toBean);
34
+        } catch (Exception e) {
35
+            e.printStackTrace();
36
+        }
37
+        return toBean;
38
+    }
39
+
40
+    private static <T> T convertBean(Object fromBean, T toBean) {
41
+        TypeConverterManager.register(String.class, new StringConverter());
42
+        BeanCopy.beans(fromBean, toBean).copy();
43
+        return toBean;
44
+    }
45
+
46
+    public static Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
47
+        Method method;
48
+        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
49
+            try {
50
+                method = clazz.getDeclaredMethod(methodName, parameterTypes);
51
+                return method;
52
+            } catch (Exception ignored) {
53
+
54
+            }
55
+        }
56
+        return null;
57
+    }
58
+
59
+    @SuppressWarnings("unchecked")
60
+    public static <T> T getBeanInstance(String clazzName)
61
+            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
62
+
63
+        return (T) Class.forName(clazzName).newInstance();
64
+    }
65
+
66
+    public static Map<String, Object> toBeanMethodMap(String toBean)
67
+            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
68
+
69
+        Class<?> toBeanClazz = getBeanInstance(toBean).getClass();
70
+        Method[] toBeanMethods = toBeanClazz.getDeclaredMethods();
71
+        if (!toBeanClazz.isInstance(Object.class))// 非超类Object
72
+        {
73
+            for (Method method : toBeanMethods) {
74
+                String methodName = method.getName();
75
+                toBeanMethodMap.put(methodName, method);
76
+            }
77
+
78
+            Class<?> toBeanSuperclazz = toBeanClazz.getSuperclass();// 获取父类
79
+            toBeanMethodMap(toBeanSuperclazz.getName());
80
+        }
81
+
82
+        return toBeanMethodMap;
83
+    }
84
+
85
+    public static Map<String, Object> toMap(Object object) {
86
+        Map<String, Object> map = new HashMap<String, Object>();
87
+
88
+        if (object == null) {
89
+            return map;
90
+        }
91
+
92
+        BeanMap beanMap;
93
+        beanMap = new BeanMap(object);
94
+        @SuppressWarnings("unchecked")
95
+        Iterator<String> it = beanMap.keyIterator();
96
+        while (it.hasNext()) {
97
+            String name = it.next();
98
+            Object value = beanMap.get(name);
99
+            // 转换时会将类名也转换成属性,此处去掉
100
+            if (value != null && !name.equals("class")) {
101
+                map.put(name, value);
102
+            }
103
+        }
104
+
105
+        return map;
106
+    }
107
+
108
+    public static Map<String, Object> toMap(Object... objs) {
109
+        Map<String, Object> map = new HashMap<>();
110
+        for (Object object : objs) {
111
+            if (object != null) {
112
+                map.putAll(toMap(object));
113
+            }
114
+        }
115
+        return map;
116
+    }
117
+
118
+    public static String[] getNullPropertyNames (Object source) {
119
+        final BeanWrapper src = new BeanWrapperImpl(source);
120
+        PropertyDescriptor[] pds = src.getPropertyDescriptors();
121
+
122
+        Set<String> emptyNames = new HashSet<String>();
123
+        for(PropertyDescriptor pd : pds) {
124
+            Object srcValue = src.getPropertyValue(pd.getName());
125
+            if (srcValue == null) {
126
+                emptyNames.add(pd.getName());
127
+            }
128
+        }
129
+        String[] result = new String[emptyNames.size()];
130
+        return emptyNames.toArray(result);
131
+    }
132
+
133
+    public static void copyProperties(Object src, Object target) {
134
+        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
135
+    }
136
+
137
+}

+ 72
- 0
whole-estate/src/main/java/com/example/wholeestate/utils/StringConverter.java Ver arquivo

@@ -0,0 +1,72 @@
1
+package com.example.wholeestate.utils;
2
+
3
+import jodd.typeconverter.TypeConversionException;
4
+import jodd.typeconverter.TypeConverter;
5
+import jodd.util.ArraysUtil;
6
+
7
+import java.sql.Clob;
8
+import java.sql.SQLException;
9
+import java.util.Date;
10
+
11
+public class StringConverter implements TypeConverter<String> {
12
+
13
+    public String convert(Object value) {
14
+        if (value == null) {
15
+            return null;
16
+        }
17
+
18
+        if (value instanceof CharSequence) { // for speed
19
+            return value.toString();
20
+        }
21
+        Class<?> type = value.getClass();
22
+        if (type == Class.class) {
23
+            return ((Class<?>) value).getName();
24
+        }
25
+        if (type.isArray()) {
26
+            if (type == char[].class) {
27
+                char[] charArray = (char[]) value;
28
+                return new String(charArray);
29
+            }
30
+            if (type == int[].class) {
31
+                return ArraysUtil.toString((int[]) value);
32
+            }
33
+            if (type == long[].class) {
34
+                return ArraysUtil.toString((long[]) value);
35
+            }
36
+            if (type == byte[].class) {
37
+                return ArraysUtil.toString((byte[]) value);
38
+            }
39
+            if (type == float[].class) {
40
+                return ArraysUtil.toString((float[]) value);
41
+            }
42
+            if (type == double[].class) {
43
+                return ArraysUtil.toString((double[]) value);
44
+            }
45
+            if (type == short[].class) {
46
+                return ArraysUtil.toString((short[]) value);
47
+            }
48
+            if (type == boolean[].class) {
49
+                return ArraysUtil.toString((boolean[]) value);
50
+            }
51
+            return ArraysUtil.toString((Object[]) value);
52
+        }
53
+        if (value instanceof Clob) {
54
+            Clob clob = (Clob) value;
55
+            try {
56
+                long length = clob.length();
57
+                if (length > Integer.MAX_VALUE) {
58
+                    throw new TypeConversionException("Clob is too big.");
59
+                }
60
+                return clob.getSubString(1, (int) length);
61
+            } catch (SQLException sex) {
62
+                throw new TypeConversionException(value, sex);
63
+            }
64
+        }
65
+        if (value instanceof Date) {
66
+            java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
67
+            return format1.format(value);
68
+        }
69
+
70
+        return value.toString();
71
+    }
72
+}

+ 26
- 0
whole-estate/src/main/java/com/example/wholeestate/wx/WxBase.java Ver arquivo

@@ -0,0 +1,26 @@
1
+package com.example.wholeestate.wx;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+import com.example.wholeestate.exception.WholeEstateException;
5
+
6
+/**
7
+ * @author weiximei
8
+ */
9
+public class WxBase {
10
+
11
+    protected void wxMiniErrCode(JSONObject jsonObject) {
12
+
13
+        Integer errcode = jsonObject.getInteger("errcode");
14
+        String errmsg = jsonObject.getString("errmsg");
15
+        switch (errcode) {
16
+            case -1:
17
+                throw new WholeEstateException(errmsg);
18
+            case 40029:
19
+                throw new WholeEstateException(errmsg);
20
+            case 45011:
21
+                throw new WholeEstateException(errmsg);
22
+        }
23
+
24
+    }
25
+
26
+}

+ 22
- 0
whole-estate/src/main/java/com/example/wholeestate/wx/WxConstant.java Ver arquivo

@@ -0,0 +1,22 @@
1
+package com.example.wholeestate.wx;
2
+
3
+/**
4
+ * 定义 微信相关 URL
5
+ * @author weiximei
6
+ */
7
+public class WxConstant {
8
+
9
+    // -------------   微信小程序 start  ---------------------
10
+
11
+    /**
12
+     * 根据 code 获取 openid, session_key, unionid 等
13
+     *
14
+     * 请求参数在发起请求的时候拼装
15
+     *
16
+     */
17
+    public static final String  WX_MINI_CODE2_SESSION = "https://api.weixin.qq.com/sns/jscode2session";
18
+
19
+
20
+    // ------------  微信小程序 end --------------------------
21
+
22
+}

+ 26
- 0
whole-estate/src/main/java/com/example/wholeestate/wx/WxMiniProperties.java Ver arquivo

@@ -0,0 +1,26 @@
1
+package com.example.wholeestate.wx;
2
+
3
+import lombok.Data;
4
+import org.springframework.boot.context.properties.ConfigurationProperties;
5
+import org.springframework.stereotype.Component;
6
+
7
+/**
8
+ * 微信小程序 参数
9
+ * @author weiximei
10
+ */
11
+@Data
12
+@Component
13
+@ConfigurationProperties(prefix = "wx.mini")
14
+public class WxMiniProperties {
15
+
16
+    /**
17
+     * 小程序 appId
18
+     */
19
+    private String appid;
20
+
21
+    /**
22
+     * 小程序 appSecret
23
+     */
24
+    private String secret;
25
+
26
+}

+ 20
- 0
whole-estate/src/main/java/com/example/wholeestate/wx/mini/IWxMini.java Ver arquivo

@@ -0,0 +1,20 @@
1
+package com.example.wholeestate.wx.mini;
2
+
3
+/**
4
+ * 微信小程序 接口
5
+ * @author weiximei
6
+ */
7
+public interface IWxMini {
8
+
9
+    /**
10
+     * 根据 code 获取
11
+     *
12
+     *      openid
13
+     *
14
+     * @param code
15
+     * @return
16
+     */
17
+    String getOpenid(String code);
18
+
19
+
20
+}

+ 55
- 0
whole-estate/src/main/java/com/example/wholeestate/wx/mini/impl/WxMiniImpl.java Ver arquivo

@@ -0,0 +1,55 @@
1
+package com.example.wholeestate.wx.mini.impl;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+import com.example.wholeestate.common.http.OkHttpRequestUtils;
5
+import com.example.wholeestate.wx.WxBase;
6
+import com.example.wholeestate.wx.WxConstant;
7
+import com.example.wholeestate.wx.WxMiniProperties;
8
+import com.example.wholeestate.wx.mini.IWxMini;
9
+import com.google.common.collect.Maps;
10
+import lombok.extern.slf4j.Slf4j;
11
+import org.springframework.beans.factory.annotation.Autowired;
12
+import org.springframework.stereotype.Service;
13
+
14
+import java.util.Map;
15
+
16
+/**
17
+ * 微信 小程序实现
18
+ * @author weiximei
19
+ */
20
+@Service
21
+@Slf4j
22
+public class WxMiniImpl extends WxBase implements IWxMini {
23
+
24
+    @Autowired
25
+    private WxMiniProperties wxMiniProperties;
26
+
27
+    @Override
28
+    public String getOpenid(String code) {
29
+
30
+        Map<String, Object> query = Maps.newHashMap();
31
+        query.put("appid", wxMiniProperties.getAppid());
32
+        query.put("secret",wxMiniProperties.getSecret());
33
+        query.put("js_code", code);
34
+        query.put("grant_type","authorization_code");
35
+
36
+        String result = null;
37
+        try {
38
+            result = OkHttpRequestUtils.doGet(WxConstant.WX_MINI_CODE2_SESSION, query);
39
+        } catch (Exception e) {
40
+            e.printStackTrace();
41
+            log.error("微信小程序--获取 openid 失败!", e);
42
+        }
43
+
44
+        JSONObject jsonObject = JSONObject.parseObject(result);
45
+
46
+        // 校验 errcode
47
+        wxMiniErrCode(jsonObject);
48
+
49
+        // 开始获取 openid
50
+        String openid = jsonObject.getString("openid");
51
+        return openid;
52
+    }
53
+
54
+
55
+}

+ 5
- 0
whole-estate/src/main/resources/application.yml Ver arquivo

@@ -29,4 +29,9 @@ logging:
29 29
   level:
30 30
     com.example.wholeestate.dao: debug
31 31
 
32
+# 微信配置
33
+wx:
34
+  mini:
35
+    appid:
36
+    secret:
32 37