完成收货地址数据库与接口开发

完成小程序openid接口开发对接
pull/52/head
riverflow 8 months ago
parent fef53ce0b6
commit 09cda3409b

@ -48,6 +48,11 @@
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>

@ -0,0 +1,29 @@
package com.itmk.utils;
public class BusinessException extends RuntimeException {
private Integer code;
private String message;
public BusinessException(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -0,0 +1,22 @@
package com.itmk.utils;
public enum BusinessExceptionEnum {
SERVER_ERROR(500, "服务器异常!"),
;
private Integer code;
private String message;
BusinessExceptionEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}

@ -0,0 +1,150 @@
package com.itmk.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class FastJsonTools {
private static SerializeConfig CONFIG = null;
static {
CONFIG = new SerializeConfig();
// 使用和json-lib兼容的日期输出格式
CONFIG.put(java.util.Date.class, new JSONLibDataFormatSerializer());
// 使用和json-lib兼容的日期输出格式
CONFIG.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
}
private static final SerializerFeature[] FEATURES = {
// 输出空置字段
SerializerFeature.WriteMapNullValue,
// list字段如果为null输出为[]而不是null
SerializerFeature.WriteNullListAsEmpty,
// 数值字段如果为null输出为0而不是null
SerializerFeature.WriteNullNumberAsZero,
// Boolean字段如果为null输出为false而不是null
SerializerFeature.WriteNullBooleanAsFalse,
// 字符类型字段如果为null输出为""而不是null
SerializerFeature.WriteNullStringAsEmpty
};
/**
* Object
*
* @param object
* @return
*/
public static String toJSONFeaturesString(Object object) {
return JSON.toJSONString(object, CONFIG, FEATURES);
}
/**
* Object
*
* @param object
* @return
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object, CONFIG);
}
/**
* jsonmap
*
* @param s
* @return
*/
public static Map stringToCollect(String s) {
Map m = JSONObject.parseObject(s);
return m;
}
/**
* mapstring
*
* @param m
* @return
*/
public static String collectToString(Map m) {
String s = JSONObject.toJSONString(m);
return s;
}
/**
* fastjson json JavaBean
*
* @param jsonString
* @param cls
* @return
*/
public static <T> T getJson(String jsonString, Class<T> cls) {
T t = null;
try {
t = JSON.parseObject(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* fastjson json List<JavaBean> List<String>
*
* @param jsonString
* @param cls
* @return
*/
public static <T> List<T> getArrayJson(String jsonString, Class<T> cls) {
List<T> list = new ArrayList<T>();
try {
list = JSON.parseArray(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* fastjson json List<JavaBean> List<String>
*
* @param jsonString
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> getArrayJson(String jsonString) {
List<T> list = new ArrayList<T>();
try {
list = (List<T>) JSON.parseArray(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* fastjson jsonString List<Map<String,Object>>
*
* @param jsonString
* @return
*/
public static List<Map<String, Object>> getListMap(String jsonString) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
list = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}

@ -0,0 +1,143 @@
package com.itmk.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Http
*/
public class HttpClientUtil {
//连接超时时间默认10秒
private static final int socketTimeout = 10000;
//传输超时时间默认30秒
private static final int connectTimeout = 30000;
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}

@ -0,0 +1,37 @@
package com.itmk.web.address.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.address.entity.UserAddress;
import com.itmk.web.address.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/address")
public class UserAddressController {
@Autowired
private UserAddressService userAddressService;
//新增地址
@PostMapping
public ResultVo add(@RequestBody UserAddress userAddress){
if(userAddressService.save(userAddress)){
return ResultUtils.success("新增地址成功!");
}
return ResultUtils.error("新增地址失败!");
}
//列表
@GetMapping("/list")
public ResultVo list(){
//排序按status排序默认的排在第一条
QueryWrapper<UserAddress> query = new QueryWrapper<>();
query.lambda().orderByDesc(UserAddress::getStatus);
List<UserAddress> list = userAddressService.list(query);
return ResultUtils.success("查询成功",list);
}
}

@ -0,0 +1,19 @@
package com.itmk.web.address.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user_address")
public class UserAddress {
@TableId(type = IdType.AUTO)
private Long addressId;
private String openid;
private String userName;
private String phone;
private String area;
private String address;
private String status;
}

@ -0,0 +1,7 @@
package com.itmk.web.address.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itmk.web.address.entity.UserAddress;
public interface UserAddressMapper extends BaseMapper<UserAddress> {
}

@ -0,0 +1,7 @@
package com.itmk.web.address.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.itmk.web.address.entity.UserAddress;
public interface UserAddressService extends IService<UserAddress> {
}

@ -0,0 +1,11 @@
package com.itmk.web.address.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmk.web.address.entity.UserAddress;
import com.itmk.web.address.mapper.UserAddressMapper;
import com.itmk.web.address.service.UserAddressService;
import org.springframework.stereotype.Service;
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {
}

@ -0,0 +1,59 @@
package com.itmk.web.wxapi.controller;
import com.itmk.utils.*;
import com.itmk.web.wxapi.entity.Code2Session;
import com.itmk.web.wxapi.entity.LoginParm;
import com.itmk.web.wxapi.entity.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/wxapi/user")
public class WxLoginController {
@Value("${Wechat.Applets.appId}")
private String appId;
@Value("${Wechat.Applets.appSecret}")
private String appSecret;
//小程序登录
@PostMapping("/wxLogin")
public ResultVo wxLogin(@RequestBody LoginParm parm){
String code = parm.getCode();
log.info("wxlogin - code: " + code);
String url = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> param = new HashMap<>();
param.put("appid", appId);
param.put("secret", appSecret);
param.put("js_code", code);
param.put("grant_type", "authorization_code");
log.info("param: " + param);
try {
//发送请求
String wxResult = HttpClientUtil.doGet(url, param);
//转换参数
Code2Session userJson = FastJsonTools.getJson(wxResult, Code2Session.class);
log.info("userJson: " + userJson);
if(userJson == null) throw new BusinessException(500,"小程序获取open失败");
String openid = userJson.getOpenid();
String sessionKey = userJson.getSession_key();
log.info("openid: " + openid);
log.info("sessionKey: " + sessionKey);
LoginVo vo = new LoginVo();
vo.setOpenid(openid);
vo.setSessionKey(sessionKey);
return ResultUtils.success("获取成功",vo);
} catch (Exception e) {
e.printStackTrace();
log.error(String.format("WxLoginController.wxLogin Error", e));
}
return ResultUtils.error("小程序获取open失败");
}
}

@ -0,0 +1,18 @@
package com.itmk.web.wxapi.entity;
import lombok.Data;
@Data
public class Code2Session {
private String openid; //用户唯一标识
private String session_key; //会话密钥
private String unionid; //用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
private Integer errcode; //错误码
private String errmsg; //错误信息
}

@ -0,0 +1,8 @@
package com.itmk.web.wxapi.entity;
import lombok.Data;
@Data
public class LoginParm {
private String code;
}

@ -0,0 +1,9 @@
package com.itmk.web.wxapi.entity;
import lombok.Data;
@Data
public class LoginVo {
private String openid;
private String sessionKey;
}

@ -30,6 +30,14 @@ mybatis-plus:
# 配置MyBatis Plus在更新时间更新非空和非NULL的字段
update-strategy: not_empty
# 微信小程序相关
Wechat:
Applets:
# 小程序appID
appId: wx6a41b250d82adc97
# 小程序秘钥
appSecret: 3bd822fb2c28fe7ba492ae7afd1fbd6e
# 日志配置
logging:
level:

@ -0,0 +1,7 @@
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itmk.web.address.mapper.UserAddressMapper">
</mapper>
Loading…
Cancel
Save