diff --git a/back-end_code/pom.xml b/back-end_code/pom.xml index 3bde7b47cc4b04650d182234ecb66b9b1048d19b..49c3a0e8040d4e010a4d2c0568314176883bdbf5 100644 --- a/back-end_code/pom.xml +++ b/back-end_code/pom.xml @@ -10,7 +10,7 @@ com.shop service - 1.0.1-SNAPSHOT + 3.1.1-SNAPSHOT com.shop.service 购物网站后台 @@ -47,6 +47,20 @@ qiniu-java-sdk 7.2.7 + + + com.alibaba + fastjson + 1.2.47 + + + + com.sf + sfExpress + 2.1.7 + system + ${pom.basedir}/src/main/java/com/shop/sflib/SF-CSIM.jar + @@ -79,7 +93,6 @@ org.springframework.boot spring-boot-devtools true - true @@ -87,13 +100,84 @@ jasypt-spring-boot-starter 2.0.0 + + + + + + + com.alipay.sdk + alipay-sdk-java + 4.22.49.ALL + + + + org.springframework.boot + spring-boot-starter-data-redis + 1.4.7.RELEASE + + + + org.apache.commons + commons-pool2 + + + org.apache.httpcomponents + httpclient + 4.5.13 + + + + org.bouncycastle + bcprov-jdk15on + 1.54 + + + commons-lang + commons-lang + 2.5 + + + commons-codec + commons-codec + 1.6 + + + junit + junit + 4.12 + + + + com.github.yitter + yitter-idgenerator + 1.0.6 + + + + + src/main/java/com/shop/sflib + + + lib + + + + *.jar + + + + org.springframework.boot spring-boot-maven-plugin + + true + diff --git a/back-end_code/src/main/java/com/shop/Enum/AftApplicationState.java b/back-end_code/src/main/java/com/shop/Enum/AftApplicationState.java new file mode 100644 index 0000000000000000000000000000000000000000..4a606fb484cc60fcd806ee64ad064fca3586a50f --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/AftApplicationState.java @@ -0,0 +1,27 @@ +package com.shop.Enum; + +public enum AftApplicationState { + Process, + // 处理中 + Accept, + // 同意 + Refuse, + // 拒绝 + Cancel; + // 已关闭 + + AftApplicationState() { + } + public static AftApplicationState toenum(String str){ + if (str.equals("Process")){ + return Process; + }else if (str.equals("Accept")){ + return Accept; + }else if (str.equals("Refuse")){ + return Refuse; + }else if (str.equals("Cancel")){ + return Cancel; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/AftApplicationType.java b/back-end_code/src/main/java/com/shop/Enum/AftApplicationType.java new file mode 100644 index 0000000000000000000000000000000000000000..1c5602468c3c4269913ebcc3a44003a06968a570 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/AftApplicationType.java @@ -0,0 +1,20 @@ +package com.shop.Enum; + +public enum AftApplicationType { + Refund, + //退款 + Return; + //退货 + + AftApplicationType() { + } + + public static AftApplicationType toenum(String str){ + if (str.equals("Refund")){ + return Refund; + }else if (str.equals("Return")){ + return Return; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/ContactType.java b/back-end_code/src/main/java/com/shop/Enum/ContactType.java new file mode 100644 index 0000000000000000000000000000000000000000..a2f6839284956c23b132656394ccc8206a6efb5e --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/ContactType.java @@ -0,0 +1,47 @@ +package com.shop.Enum; + +public enum ContactType { + Buyer, + //买家 + Seller; + //卖家 + + ContactType() { + } + + public static ContactType toenum(String str){ + if (str.equals("Buyer")){ + return Buyer; + }else if (str.equals("Seller")){ + return Seller; + }else + return null; + } + + public static Integer toInteger(String str){ + if (str.equals("Buyer")){ + return 2; + }else if (str.equals("Seller")){ + return 1; + }else + return 0; + } + + public static Integer toInteger(ContactType str){ + if (str == ContactType.Buyer){ + return 2; + }else if (str == ContactType.Seller){ + return 1; + }else + return 0; + } + + public static String toString(ContactType str){ + if (str == ContactType.Buyer){ + return "buyer"; + }else if (str == ContactType.Seller){ + return "seller"; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/GoodState.java b/back-end_code/src/main/java/com/shop/Enum/GoodState.java new file mode 100644 index 0000000000000000000000000000000000000000..52eb27b20b1615a6f2e6ef566415e3cdc5851724 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/GoodState.java @@ -0,0 +1,24 @@ +package com.shop.Enum; + +public enum GoodState { + Selling, + // 在售 + Sell_out, + // 售罄 + Sell_down; + // 下架 + + GoodState() { + } + public static GoodState toenum(String str){ + if (str.equals("Selling")){ + return Selling; + }else if (str.equals("Sell_out")){ + return Sell_out; + }else if (str.equals("Sell_down")){ + return Sell_down; + }else + return null; + } + +} diff --git a/back-end_code/src/main/java/com/shop/Enum/OrderState.java b/back-end_code/src/main/java/com/shop/Enum/OrderState.java new file mode 100644 index 0000000000000000000000000000000000000000..aa56820014cd0bd87003c773316f870020e07c05 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/OrderState.java @@ -0,0 +1,43 @@ +package com.shop.Enum; + +public enum OrderState { + Unpaid, + // 待支付 + Unconfirmed, + // 待确认 + Unpicked, + // 待备货 + Undelivered, + // 待发货 + Delivered, + // 已发货 + Finish, + // 交易成功 + SCancel, + // 商家取消订单 + BCancel; + // 买家取消订单 + + OrderState() { + } + public static OrderState toenum(String str){ + if (str.equals("Unpaid")){ + return Unpaid; + }else if (str.equals("Unconfirmed")){ + return Unconfirmed; + }else if (str.equals("Unpicked")){ + return Unpicked; + }else if (str.equals("Undelivered")){ + return Undelivered; + }else if (str.equals("Delivered")){ + return Delivered; + }else if (str.equals("Finish")){ + return Finish; + }else if (str.equals("SCancel")){ + return SCancel; + }else if (str.equals("BCancel")){ + return BCancel; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/PackageState.java b/back-end_code/src/main/java/com/shop/Enum/PackageState.java new file mode 100644 index 0000000000000000000000000000000000000000..c431f509caf6bbefea995e34538d5e063e079bf5 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/PackageState.java @@ -0,0 +1,23 @@ +package com.shop.Enum; + +public enum PackageState { + Finished, + //已收到货 + UnFinished, + //未收到货 + Undelivered; + //未发货 + + PackageState() { + } + public static PackageState toenum(String str){ + if (str.equals("Finished")){ + return Finished; + }else if (str.equals("UnFinished")){ + return UnFinished; + }else if (str.equals("Undelivered")){ + return Undelivered; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/Permission.java b/back-end_code/src/main/java/com/shop/Enum/Permission.java new file mode 100644 index 0000000000000000000000000000000000000000..9d9c44ccb5c53f4fb1f7eaac91e5e487d0385a44 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/Permission.java @@ -0,0 +1,25 @@ +package com.shop.Enum; + +public enum Permission { + Buyer, + // 买家 + Seller, + // 商家 + Administrator; + // 管理员 + + Permission() { + } + + public static Permission toenum(String str){ + if (str.equals("Buyer")){ + return Buyer; + }else if (str.equals("Seller")){ + return Seller; + }else if (str.equals("Administrator")){ + return Administrator; + }else + return null; + } + +} diff --git a/back-end_code/src/main/java/com/shop/Enum/RefundState.java b/back-end_code/src/main/java/com/shop/Enum/RefundState.java new file mode 100644 index 0000000000000000000000000000000000000000..29969fa0a45a541fa0a78ca5242ef58130a78e22 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/RefundState.java @@ -0,0 +1,22 @@ +package com.shop.Enum; + +public enum RefundState { + Process, + // 处理中 + Success, + // 退款成功 + Fail; + // 退款失败 + RefundState() { + } + public static RefundState toenum(String str){ + if (str.equals("Success")){ + return Success; + }else if (str.equals("Fail")){ + return Fail; + }else if (str.equals("Process")){ + return Fail; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/Enum/Select.java b/back-end_code/src/main/java/com/shop/Enum/Select.java new file mode 100644 index 0000000000000000000000000000000000000000..e545a9f8767682d70f838affa4f25f3414a5a5a2 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/Enum/Select.java @@ -0,0 +1,18 @@ +package com.shop.Enum; + +public enum Select { + Selected, + // 已选择 + UnSelected; + // 未选择 + Select() { + } + public static Select toenum(String str){ + if (str.equals("Selected")){ + return Selected; + }else if (str.equals("UnSelected")){ + return UnSelected; + }else + return null; + } +} diff --git a/back-end_code/src/main/java/com/shop/ServiceApplication.java b/back-end_code/src/main/java/com/shop/ServiceApplication.java index dcb44b5536204b58dc02968be174211b60acf1af..9a7c7c4eb47179eeae32f7f979df3a6646b83643 100644 --- a/back-end_code/src/main/java/com/shop/ServiceApplication.java +++ b/back-end_code/src/main/java/com/shop/ServiceApplication.java @@ -1,4 +1,6 @@ package com.shop; +import com.github.yitter.contract.IdGeneratorOptions; +import com.github.yitter.idgen.YitIdHelper; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -8,6 +10,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class ServiceApplication { public static void main(String[] args) { + // 创建 IdGeneratorOptions 对象,请在构造函数中输入 WorkerId: + IdGeneratorOptions options = new IdGeneratorOptions((short) 1); +// options.WorkerIdBitLength = 10; // WorkerIdBitLength 默认值6,支持的 WorkerId 最大值为2^6-1,若 WorkerId 超过64,可设置更大的 WorkerIdBitLength +// ...... 其它参数设置参考 IdGeneratorOptions 定义,一般来说,只要再设置 WorkerIdBitLength (决定 WorkerId 的最大值)。 + +// 保存参数(必须的操作,否则以上设置都不能生效): + YitIdHelper.setIdGenerator(options); SpringApplication.run(ServiceApplication.class, args); } diff --git a/back-end_code/src/main/java/com/shop/controller/AddressController.java b/back-end_code/src/main/java/com/shop/controller/AddressController.java new file mode 100644 index 0000000000000000000000000000000000000000..09098667327a9856e2cc73245b49ba461cea5997 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/AddressController.java @@ -0,0 +1,111 @@ +package com.shop.controller; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.Select; +import com.shop.entity.Address; +import com.shop.service.AddressService; +import com.shop.utils.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/address") +public class AddressController { + @Autowired + private AddressService addressService; + + //添加地址 + @PostMapping("/Address") + public Object addAddress(@RequestBody Address address){ + try{ + if (addressService.searchUserSelectedAddress(address.getUsername()) == null) { + address.setSelected(Select.Selected); + } + else { + address.setSelected(Select.UnSelected); + } + if (addressService.addAddress(address) < 1) + return Result.fail("添加地址失败"); + }catch (Exception e){ + return Result.fail(e.toString()); + } + return Result.ok(); + } + + //根据买家username查找地址 + @GetMapping("/Address") + public Object searchUserAddress(@RequestParam String username){ + try{ + JSONObject jsonObject = new JSONObject(); + List
addresses =addressService.searchUserAddress(username); + jsonObject.put("addresses",addresses); + return Result.ok(jsonObject); + }catch (Exception e){ + return Result.fail(e.toString()); + } + } + + //根据买家username查找默认地址 + @GetMapping("/Selected") + public Object searchUserSelectedAddress(@RequestParam String username){ + try{ + JSONObject jsonObject = new JSONObject(); + Address address =addressService.searchUserSelectedAddress(username); + jsonObject.put("address",address); + return Result.ok(jsonObject); + }catch (Exception e){ + return Result.fail(e.toString()); + } + } + + //更新地址 + @PutMapping("/Address") + public Object updateAddress(@RequestBody Address address){ + try { + if (address.getSelected() == Select.Selected) { + if (addressService.setUnselected(address.getUsername()) < 1) { + return Result.fail("更新地址失败"); + } + } + if (addressService.updateAddress(address) < 1) + return Result.fail("更新地址失败"); + } catch (Exception e) { + return Result.fail(e.toString()); + } + return Result.ok(); + } + + //删除地址 + @DeleteMapping("/Address") + public Object deleteAddressByAddressId(@RequestParam String username , @RequestParam int address_id){ + try { + if (addressService.deleteAddressByAddressId(username,address_id) < 1) + return Result.fail("删除地址失败"); + } catch (Exception e) { + return Result.fail(e.toString()); + } + return Result.ok(); + } + + //修改默认地址 + @PutMapping("/Selected") + public Object updateSelected(@RequestBody JSONObject jsonObject){ + try { + String username = jsonObject.getString("username"); + Integer address_id = jsonObject.getInteger("address_id"); + Address addressSelected= addressService.searchUserSelectedAddress(username); + if (addressService.setUnselected(username) < 1 && !(addressService.searchUserSelectedAddress(username) == null)) + return Result.fail("更新地址失败"); + if (addressService.setSelected(address_id,username) < 1){ + addressService.setSelected(addressSelected.getAddress_id(),addressSelected.getUsername()); + return Result.fail("更新地址失败"); + } + } catch (Exception e) { + return Result.fail(e.toString()); + } + return Result.ok("更新地址成功"); + } + +} diff --git a/back-end_code/src/main/java/com/shop/controller/AftApplicationController.java b/back-end_code/src/main/java/com/shop/controller/AftApplicationController.java new file mode 100644 index 0000000000000000000000000000000000000000..aa9c8fac7019c55136a897461faa215886dcb70d --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/AftApplicationController.java @@ -0,0 +1,111 @@ +package com.shop.controller; + +import com.shop.Enum.AftApplicationState; +import com.shop.Enum.AftApplicationType; +import com.shop.Enum.PackageState; +import com.shop.entity.AftApplication; +import com.shop.entity.Order; +import com.shop.service.AftApplicationService; +import com.shop.service.OrderService; +import com.shop.utils.Result; +import com.alibaba.fastjson.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +@RestController +@RequestMapping("/aftApplication") +public class AftApplicationController { + @Autowired + private AftApplicationService aftApplicationService; + @Autowired + private OrderService orderService; + + //添加申诉 + @PostMapping("/AftApplication") + public Object addAftApplication(@RequestBody JSONObject jsonObject){ + Order order = orderService.searchOrderByOrderId(jsonObject.getLong("order_id")); + if (order.getBuyer_username().equals(jsonObject.getString("aftApplication_buyerusername")) && !order.getSeller_username().equals(jsonObject.getString("aftApplication_sellerusername"))){ + return Result.fail("买家或卖家用户名错误"); + } + AftApplication aftApplication = new AftApplication(order, AftApplicationType.toenum(jsonObject.getString("aftApplication_type")) ,jsonObject.getString("aftApplication_reason"), PackageState.toenum(jsonObject.getString("package_state")),jsonObject.getString("aftApplication_images")); + aftApplication.setCreate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + if (aftApplicationService.isAftApplicationById(aftApplication.getOrder_id()) != null){ + return Result.fail("重复添加"); + } + if (aftApplicationService.addAftApplication(aftApplication) < 1 || orderService.buyerSubmitAftApplication(order.getBuyer_username(), order.getOrder_id()) < 1) + return Result.fail("添加申诉失败"); + order = orderService.searchOrderByOrderId(aftApplication.getOrder_id()); + jsonObject.put("order",order); + return Result.ok(jsonObject); + } + + //买家根据aftApplication_buyerusername,aftApplication_type,aftApplication_state查找申诉 + @PutMapping("/buyer") + public Object searchBuyerAftApplication(@RequestBody JSONObject jsonObject){ + String aftApplication_buyerusername = jsonObject.getString("buyer_username"); + AftApplicationType aftApplication_type = AftApplicationType.toenum(jsonObject.getString("type")); + AftApplicationState aftApplication_state = AftApplicationState.toenum(jsonObject.getString("state")); + List aftApplications =aftApplicationService.searchBuyerAftApplication(aftApplication_buyerusername,aftApplication_type,aftApplication_state); + jsonObject.clear(); + jsonObject.put("aftApplications",aftApplications); + return Result.ok(jsonObject); + } + + //卖家根据aftApplication_buyerusername,aftApplication_type,aftApplication_state查找申诉 + @PutMapping("/seller") + public Object searchSellerAftApplication(@RequestBody JSONObject jsonObject){ + String aftApplication_sellerusername = jsonObject.getString("seller_username"); + AftApplicationType aftApplication_type = AftApplicationType.toenum(jsonObject.getString("type")); + AftApplicationState aftApplication_state = AftApplicationState.toenum(jsonObject.getString("state")); + List aftApplications =aftApplicationService.searchSellerAftApplication(aftApplication_sellerusername,aftApplication_type,aftApplication_state); + jsonObject.clear(); + jsonObject.put("aftApplications",aftApplications); + return Result.ok(jsonObject); + } + + //买家修改申诉 + @PutMapping("/update") + public Object updateAftApplication(@RequestBody JSONObject jsonObject){ + AftApplication aftApplication = new AftApplication(jsonObject); + if (aftApplicationService.updateAftApplication(aftApplication) < 1) + return Result.fail("更新申诉失败"); + return Result.ok(); + } + + //买家取消申诉 + @PutMapping("/cancel") + public Object cancelAftApplication(@RequestBody JSONObject jsonObject){ + AftApplication aftApplication = new AftApplication(jsonObject); + aftApplication.setFinish_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + if (aftApplicationService.cancelAftApplication(aftApplication) < 1) + return Result.fail("更新申诉失败"); + return Result.ok(); + } + + //卖家同意申诉 + @PutMapping("/accept") + public Object acceptAftApplication(@RequestBody JSONObject jsonObject){ + AftApplication aftApplication = new AftApplication(jsonObject); + aftApplication.setFinish_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + if (aftApplicationService.acceptAftApplication(aftApplication) < 1 + && orderService.sellerAcceptAftApplication(aftApplication.getAftApplication_sellerusername(),aftApplication.getOrder_id()) < 1) + return Result.fail("同意申诉失败"); + return Result.ok(); + } + + //卖家拒绝申诉 + @PutMapping("/refuse") + public Object refuseAftApplication(@RequestBody JSONObject jsonObject){ + AftApplication aftApplication = new AftApplication(jsonObject); + aftApplication.setFinish_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + if (aftApplicationService.refuseAftApplication(aftApplication) < 1 + && orderService.sellerRefuseAftApplication(aftApplication.getAftApplication_sellerusername(),aftApplication.getOrder_id()) < 1) + return Result.fail("拒绝申诉失败"); + return Result.ok(); + } + +} diff --git a/back-end_code/src/main/java/com/shop/controller/AlipayController.java b/back-end_code/src/main/java/com/shop/controller/AlipayController.java new file mode 100644 index 0000000000000000000000000000000000000000..77780a67f1751f627df960738f1d1dea3fd75acc --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/AlipayController.java @@ -0,0 +1,108 @@ +package com.shop.controller; + +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.internal.util.AlipaySignature; +import com.shop.entity.Order; +import com.shop.service.AlipayServiceImpl; +import com.shop.service.OrderService; +import com.shop.utils.AlipayUtil; +import com.shop.utils.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * @author mumuwei + * @date 0004 + */ +@RestController +@RequestMapping("/pay") +public class AlipayController { + + private AlipayUtil alipayUtil; + @Autowired + private AlipayServiceImpl alipayService; + + @Autowired + public void setAlipayUtil(AlipayUtil alipayUtil) { + this.alipayUtil = alipayUtil; + } + @Autowired + private OrderService orderService; + + + @PostMapping("/create") + public String create(@RequestBody JSONObject jsonObject){ + String pay = null; + String id = jsonObject.getString("id"); + Float price= Float.valueOf(jsonObject.getString("price")); + String title= jsonObject.getString("title"); + try { + pay = alipayService.webPagePay(id, price,title); + } catch (Exception e) { + e.printStackTrace(); + } + return pay; + } +// public String create(String id, String price, String title, Model model){ +// String pay = alipayUtil.pay(id, price, title); +// model.addAttribute("form", pay); +// return "pay"; +// } + @GetMapping("/return") + public String returnNotice(String out_trade_no, Model model){ + String query = alipayUtil.query(out_trade_no); + model.addAttribute("query", query); + return "query"; + } + +// @PostMapping("/notify") +// public void notifyUrl(String trade_no, String total_amount, String trade_status){ +// System.err.println("支付宝订单编号:" + trade_no + ", 订单金额: " + total_amount + ",订单状态:" + trade_status); +// +// } +@RequestMapping(value="/notify") +public String alipay(HttpServletRequest request, HttpServletResponse response) throws Exception { + + //获取支付宝POST过来反馈信息 + Map params = new HashMap(); + Map requestParams = request.getParameterMap(); + for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { + String name = (String) iter.next(); + String[] values = (String[]) requestParams.get(name); + String valueStr = ""; + for (int i = 0; i < values.length; i++) { + valueStr = (i == values.length - 1) ? valueStr + values[i] + : valueStr + values[i] + ","; + } + //乱码解决,这段代码在出现乱码时使用 +// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); + params.put(name, valueStr); + } + + // 商户订单号 + String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); + // 支付宝交易号 + String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); + // 交易状态 + String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8"); + // 付款金额 + String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"); + + if (trade_status.equals("TRADE_SUCCESS")){ + orderService.buyerPayOrder(Long.valueOf(out_trade_no)); + } +// System.out.println("out_trade_no:"+out_trade_no); +// System.out.println("trade_no:"+trade_no); +// System.out.println("trade_status:"+trade_status); +// System.out.println("total_amount:"+total_amount); + return "success"; +} +} diff --git a/back-end_code/src/main/java/com/shop/controller/GOController.java b/back-end_code/src/main/java/com/shop/controller/GOController.java index ffb45d1755bb1dcfd59172bf4b6cf003dda87f5d..a48f0c1d5d4d02b479e88a3c1fc4a618f77ce0ed 100644 --- a/back-end_code/src/main/java/com/shop/controller/GOController.java +++ b/back-end_code/src/main/java/com/shop/controller/GOController.java @@ -27,7 +27,7 @@ public class GOController { public Object addGO(HttpServletRequest request, HttpServletResponse response){ String message = "error"; int item_id = Integer.parseInt(request.getParameter("item_id")); - int order_id = Integer.parseInt(request.getParameter("order_id")); + Long order_id = Long.valueOf(request.getParameter("order_id")); JSONObject jsonObject = new JSONObject(); int result = GOService.addGO(item_id,order_id); if(result>=1){ @@ -42,7 +42,7 @@ public class GOController { public Object searchGOByItemId(HttpServletRequest request, HttpServletResponse response){ String message = "error"; int item_id = Integer.parseInt(request.getParameter("item_id")); -// int order_id = Integer.parseInt(request.getParameter("order_id")); +// Long order_id = Long.valueOf(request.getParameter("order_id")); JSONObject jsonObject = new JSONObject(); GO go = GOService.searchGOByItemId(item_id); if(go != null){ @@ -59,7 +59,7 @@ public class GOController { public Object searchGOByOrderId(HttpServletRequest request, HttpServletResponse response){ String message = "error"; // int item_id = Integer.parseInt(request.getParameter("item_id")); - int order_id = Integer.parseInt(request.getParameter("order_id")); + Long order_id = Long.valueOf(request.getParameter("order_id")); JSONObject jsonObject = new JSONObject(); GO go = GOService.searchGOByOrderId(order_id); if(go != null){ diff --git a/back-end_code/src/main/java/com/shop/controller/GoodsController.java b/back-end_code/src/main/java/com/shop/controller/GoodsController.java index 99535955f855727b6d950d236979a7addeadaffb..0873d84ff66d64540144811e7d3c43794e2c427c 100644 --- a/back-end_code/src/main/java/com/shop/controller/GoodsController.java +++ b/back-end_code/src/main/java/com/shop/controller/GoodsController.java @@ -1,31 +1,22 @@ package com.shop.controller; import com.shop.entity.*; -import com.shop.service.GOService; -import com.shop.service.GoodsService; -import com.shop.service.OrderService; -import com.shop.service.UploadImageService; +import com.shop.service.*; import com.shop.utils.Result; -import com.shop.utils.StringUtil; -import net.minidev.json.JSONObject; +import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Map; @RestController @RequestMapping("/goods") public class GoodsController { - - @Autowired private GoodsService goodsService; @@ -35,39 +26,42 @@ public class GoodsController { @Autowired private GOService goService; + @Autowired + private SnapshotService snapshotService; + @Resource UploadImageService uploadImageService; //向Goods表中添加商品 - @PostMapping(value = "/addGoods") - public Object addGoods(@RequestBody Goods goods) { - String message = "error"; - String goods_name = goods.getGoods_name(); - String seller_username = "admin"; - int goods_stock =goods.getGoods_stock(); -// String goods_img = uploadImageService.uploadQNImg((FileInputStream) file.getInputStream(), StringUtil.getRandomImgName(file.getOriginalFilename())); - String goods_img = goods.getGoods_img(); - String goods_discribe = goods.getGoods_discribe(); - float goods_price = goods.getGoods_price(); - int goods_category = goods.getGoods_category(); - JSONObject jsonObject = new JSONObject(); - if (goods_name.length() >= 2 && goods_name.length() <= 20 && - goods_stock >= 0 && - goods_img.length() <= 2000 && - goods_discribe.length() >= 2 && goods_discribe.length() <= 2000 && - goods_price >= 0 && - goods_category >= 0 - ){ - Goods newGoods = new Goods(goods_name,seller_username,goods_stock,goods_img,goods_discribe,goods_category,goods_price); - int result = goodsService.addGoods( newGoods); - if (result >= 1) { - message = "success"; - }else { - message = "error"; + @PostMapping("/Good") + public Object addGoods(@RequestBody JSONObject jsonObject) { + String seller_username = jsonObject.getString("seller_username"); + Iterator objectIterator = jsonObject.getJSONArray("goods").iterator(); + JSONObject jb = null; + Goods good = null; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + jb = (JSONObject) objectIterator.next(); + good = new Goods(jb,seller_username); + if (good.getGoods_name().length() >= 2 && good.getGoods_name().length() <= 20 && + good.getGoods_stock() >= 0 && + good.getGoods_img().length() <= 2000 && + good.getGoods_describe().length() >= 2 && good.getGoods_describe().length() <= 2000 && + good.getGoods_price() >= 0 && + good.getGoods_category() >= 0 + ){ + if (goodsService.addGoods(good) >= 1) { + snapshotService.addSnapshot(goodsService.getNewItem(good.getGoods_name(),good.getGoods_img(),good.getGoods_describe())); + sb.append("商品: ").append(good.getGoods_name()).append(" 添加成功\n"); + continue; + }else { + sb.append("商品: ").append(good.getGoods_name()).append(" 添加失败\n"); + continue; + } } + } - jsonObject.put("message",message); - return jsonObject; + return Result.ok(sb.toString()); } //买家在goods表中查询goods详细信息 @@ -121,9 +115,7 @@ public class GoodsController { try{ JSONObject jsonObject = new JSONObject(); List goods = goodsService.searchWelcomeGoods(); - List stringList = orderService.searchSellingGoodsBuyerRealname(); jsonObject.put("goods",goods); - jsonObject.put("Strings",stringList); return Result.ok(jsonObject); }catch (Exception e){ return Result.fail(); @@ -166,76 +158,27 @@ public class GoodsController { public boolean isHaveSellingGoods(String username){return goodsService.isHaveSellingGoods(username);} //修改商品信息 - @PostMapping(value = "/updateGoods") - public Object updateGoods(@RequestBody Goods goods){ + @PutMapping("/Good") + public Object updateGoods(@RequestBody JSONObject jsonObject){ + Goods good = new Goods(jsonObject); String message = "error"; -// int item_id = Integer.parseInt(request.getParameter("item_id")); -// String goods_name = request.getParameter("goods_name"); -// String seller_username = "admin"; -// int goods_stock = Integer.parseInt(request.getParameter("goods_stock")); -// String goods_img = uploadImageService.uploadQNImg((FileInputStream) file.getInputStream(), StringUtil.getRandomImgName(file.getOriginalFilename())); -// String goods_img = request.getParameter("goods_img"); -// String goods_discribe = request.getParameter("goods_discribe"); -// int goods_category = Integer.parseInt(request.getParameter("goods_category")); -// float goods_price = Float.parseFloat(request.getParameter("goods_price")); -// // - int item_id = goods.getItem_id(); - String goods_name = goods.getGoods_name(); - String seller_username = "admin"; - int goods_stock =goods.getGoods_stock(); -// String goods_img = uploadImageService.uploadQNImg((FileInputStream) file.getInputStream(), StringUtil.getRandomImgName(file.getOriginalFilename())); - String goods_img = goods.getGoods_img(); - String goods_discribe = goods.getGoods_discribe(); - float goods_price = goods.getGoods_price(); - int goods_category = goods.getGoods_category(); - // - JSONObject jsonObject = new JSONObject(); - if (goods_name.length() >= 2 && goods_name.length() <= 20 && - goods_stock >= 0 && - goods_img.length() <= 2000 && - goods_discribe.length() >= 2 && goods_discribe.length() <= 2000 && - goods_price >= 0 && - goods_category >= 0 + if (good.getGoods_name().length() >= 2 && good.getGoods_name().length() <= 20 && + good.getGoods_stock() >= 0 && + good.getGoods_img().length() <= 2000 && + good.getGoods_describe().length() >= 2 && good.getGoods_describe().length() <= 2000 && + good.getGoods_price() >= 0 && + good.getGoods_category() >= 0 ){ - Goods newgoods = new Goods(item_id,goods_name,seller_username,goods_stock,goods_img,goods_discribe,goods_category,goods_price); - int result = goodsService.updateGoods(newgoods); - if (result >= 1) { - message = "success"; + if (goodsService.updateGoods(good) >= 1) { + snapshotService.addSnapshot(goodsService.getNewItem(good.getGoods_name(),good.getGoods_img(),good.getGoods_describe())); + message = "商品:"+good.getGoods_name()+"修改成功"; }else { - message = "error"; + message = "商品:"+good.getGoods_name()+"修改失败";; } + }else { + return Result.fail("商品:"+good.getGoods_name()+"数据不合法修改失败"); } - jsonObject.put("message",message); - return jsonObject; - } - - //查看冻结商品 - @GetMapping(value = "/searchFreezingGoods") - public Object searchFreezingGoods(@RequestParam String seller_username){ - String message = "error"; - JSONObject jsonObject = new JSONObject(); - List goodsList = goodsService.searchFreezingGoods(seller_username); - List list = new ArrayList(); - for (int i=0;i < goodsList.size();i++){ - Goods good = (Goods) goodsList.get(i); - GO go = goService.searchGOByItemId(good.getItem_id()); - Order order = orderService.searchOrderByOrderId(seller_username, go.getOrder_id()); - Order_Goods order_goods = new Order_Goods( - order.getOrder_id(), - order.getBuyer_realname(), - order.getBuyer_phonenumber(), - order.getBuyer_address(), - good.getItem_id(), - good.getGoods_name(), - good.getGoods_price(), - good.getGoods_img(), - good.getGoods_discribe()); - list.add(order_goods); - } - message = "success"; - jsonObject.put("message",message); - jsonObject.put("list",list); - return jsonObject; + return Result.ok(message); } //通过类别查询商品 diff --git a/back-end_code/src/main/java/com/shop/controller/OrderController.java b/back-end_code/src/main/java/com/shop/controller/OrderController.java index 7e458ac9029b3f3f957a7e049d965afe62a76236..bd962c8592e4ed4b70312106ed1f1f8645ad4063 100644 --- a/back-end_code/src/main/java/com/shop/controller/OrderController.java +++ b/back-end_code/src/main/java/com/shop/controller/OrderController.java @@ -1,20 +1,16 @@ package com.shop.controller; -import com.shop.entity.GO; -import com.shop.entity.Goods; -import com.shop.entity.Order; -import com.shop.entity.User; -import com.shop.mapper.GoodsMapper; +import com.github.yitter.idgen.YitIdHelper; +import com.shop.Enum.GoodState; +import com.shop.entity.*; +import com.shop.entity.sf.ResultData; import com.shop.service.*; import com.shop.utils.Result; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; +import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @@ -38,376 +34,496 @@ public class OrderController { @Autowired private CartService cartService; - //查看商品意向购买买家 - @RequestMapping(value = "/searchWantBuyerlistByItemId") - public Object searchWantBuyerlistByItemId(HttpServletRequest request, HttpServletResponse response){ - String message = "error"; - String seller_username = request.getParameter("seller_username"); - int item_id = Integer.parseInt(request.getParameter("item_id")); - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.searchBuyerlist(seller_username,item_id); - message = "success"; - jsonObject.put("orders",orderList); - jsonObject.put("message",message); - return jsonObject; - } + @Autowired + private SnapshotService snapshotService; + + @Autowired + private OrderDetailService orderDetailService; + + @Autowired + private AddressService addressService; - //查看商品意向购买买家名 - @RequestMapping(value = "/searchSellingGoodsBuyerRealname") - public Object searchSellingGoodsBuyerRealname(HttpServletRequest request, HttpServletResponse response){ - String message = "error"; - int item_id = Integer.parseInt(request.getParameter("item_id")); + @Autowired + private SFService sfService; + + //根据订单ID查询订单 + @GetMapping("/ID") + public Object searchOrderByOrderId(@RequestParam Long order_id){ JSONObject jsonObject = new JSONObject(); - List stringList = orderService.searchSellingGoodsBuyerRealname(); - message = "success"; - jsonObject.put("strings",stringList); - jsonObject.put("message",message); - return jsonObject; + Order order = orderService.searchOrderByOrderId(order_id); + jsonObject.put("order",order); + return Result.ok(jsonObject); } - //查看交易中的某商品对应的订单信息 - @RequestMapping(value = "/searchFreezeGoodsBuyer") - public Object searchFreezeGoodsBuyer(HttpServletRequest request, HttpServletResponse response){ - String message = "error"; - String seller_username = request.getParameter("seller_username"); - int item_id = Integer.parseInt(request.getParameter("item_id")); - JSONObject jsonObject = new JSONObject(); - Order order = orderService.searchFreezeGoodsBuyer(seller_username,item_id); - if (order != null){ - message = "success"; - jsonObject.put("order",order); - }else { - message = "error"; + //用户下单 + @PostMapping("/Orders") + public Object addOrder(@RequestBody JSONObject jsonObject){ + Order order = new Order(jsonObject); + long newId = YitIdHelper.nextId(); + System.out.println("生成的id:"+newId); + order.setOrder_id(newId); + boolean cart = jsonObject.getBoolean("cart"); + Address address = addressService.searchAddressById(order.getAddress().getAddress_id()); + if (address == null || !order.getBuyer_username().equals(address.getUsername())){ + return Result.fail("地址有误"); } - jsonObject.put("message",message); - return jsonObject; + order.setCreate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + orderService.addOrder(order); + order = orderService.searchNewOrder(order); + List orderDetailList = new ArrayList(); + Iterator objectIterator = jsonObject.getJSONArray("goods").iterator(); + OrderDetail orderDetail = null ; + Integer item_id = null ; + Integer buy_stock = null ; + Float buy_amount = 0.0f; + Snapshot snapshot = null ; + JSONObject jb = null; + Goods good = null; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + jb = (JSONObject) objectIterator.next(); + item_id = jb.getInteger("item_id"); + good = goodsService.searchGoods(item_id); + if (good == null){ + sb.append("商品ID: ").append(item_id).append(" 下单失败").append(" ,原因:该商品不存在\n"); + continue; + } + if (good.getGoods_state() != GoodState.Selling){ + sb.append("商品: ").append(good.getGoods_name()).append(" 下单失败").append(" ,原因:该商品非售\n"); + continue; + } + buy_stock = jb.getInteger("buy_stock"); + if (buy_stock > good.getGoods_stock()) { + sb.append("商品: ").append(good.getGoods_name()).append(" 下单失败").append(" ,原因:该商品购买数量超库存\n"); + continue; + } + snapshot = snapshotService.searchNewSnapshotByGoodId(item_id); + orderDetailService.addOrderDetail(order.getOrder_id(),snapshot,buy_stock); + orderDetail = orderDetailService.searchNewOrderDetailByOrderId(order.getOrder_id()); + buy_amount += orderDetail.getBuy_sum(); + orderDetailList.add(orderDetail); + cartService.deleteCart(order.getBuyer_username(), good.getItem_id()); + goodsService.updateGoodStock(good.getItem_id(),good.getGoods_stock()-buy_stock); + if (cart){ + cartService.deleteCart(order.getBuyer_username(), good.getItem_id()); + } + sb.append("商品: ").append(good.getGoods_name()).append(" 下单成功\n"); + good = null; + snapshot = null; + orderDetail = null; + } + if (jsonObject.getFloat("buy_amount") == null) + orderService.setAmountByOrderId(order.getOrder_id(),order.getSeller_username(), buy_amount); + order = orderService.searchOrderByOrderId(order.getOrder_id()); + jsonObject.clear(); + jsonObject.put("result",sb.toString()); + jsonObject.put("order" ,order); + return Result.ok(jsonObject); } - //查看已完成交易商品的历史意向买家 - @RequestMapping(value = "/searchHistoryGoodsUnFinishedOrder") - public Object searchHistoryGoodsUnFinishedOrder(HttpServletRequest request, HttpServletResponse response){ - String message = "error"; - String seller_username = request.getParameter("seller_username"); - int item_id = Integer.parseInt(request.getParameter("item_id")); + //根据买家用户名查找所有订单 + @GetMapping("/buyer/history") + public Object buyerSearchHistoryOrders(@RequestParam String buyer_username){ JSONObject jsonObject = new JSONObject(); - List orderList = orderService.searchHistoryGoodsUnFinishedOrder(seller_username,item_id); - message = "success"; - jsonObject.put("message",message); + List orderList = orderService.buyerSearchHistoryOrders(buyer_username); + jsonObject.clear(); jsonObject.put("orders",orderList); - return jsonObject; + return Result.ok(jsonObject); } - //同意意向买家 - @RequestMapping(value = "/agreeOrderWanted") - public Object agreeOrderWanted(HttpServletRequest request, HttpServletResponse response) { - String message = "error"; - String seller_username = request.getParameter("seller_username"); - int order_id = Integer.parseInt(request.getParameter("order_id")); + //根据卖家用户名查找所有订单 + @GetMapping("/seller/history") + public Object sellerSearchHistoryOrders(@RequestParam String seller_username){ JSONObject jsonObject = new JSONObject(); - GO res = goService.searchGOByOrderId(order_id); - if (res == null){ - int result = goService.addGO(orderService.searchOrderByOrderId(seller_username,order_id).getItem_id(),order_id); - Order order = orderService.agreeOrderwanted(seller_username,order_id); - if (order != null){ - message = "success"; - jsonObject.put("order",order); - }else { - message = "error"; - } - } - jsonObject.put("message",message); - return jsonObject; + List orderList = orderService.sellerSearchHistoryOrders(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } - //根据用户名查看历史购买记录 - @GetMapping("/buyer/finished/{buyer_username}") - public Object searchFinishOrderByBuyerName(@PathVariable("buyer_username") String buyer_username){ + //买家查询待支付的订单 + @GetMapping("/buyer/unpaid") + public Object buyerSearchUnpaidOrder(@RequestParam String buyer_username){ JSONObject jsonObject = new JSONObject(); - List orderList = orderService.searchFinishOrderByBuyerName(buyer_username); + List orderList = orderService.buyerSearchUnpaidOrder(buyer_username); + jsonObject.clear(); jsonObject.put("orders",orderList); return Result.ok(jsonObject); } - //根据卖家用户名查找所有订单 - @GetMapping("/seller/{seller_username}") - public Object searchOrdersBySellerName(@PathVariable("seller_username") String seller_username){ + //卖家查询待支付的订单 + @GetMapping("/seller/unpaid") + public Object sellerSearchUnpaidOrder(@RequestParam String seller_username){ JSONObject jsonObject = new JSONObject(); - List orderList = orderService.searchOrdersBySellerName(seller_username); + List orderList = orderService.sellerSearchUnpaidOrder(seller_username); + jsonObject.clear(); jsonObject.put("orders",orderList); return Result.ok(jsonObject); } + //买家支付待支付的订单 + @PutMapping(value = "/buyer/pay") + public Object buyerPayOrder(@RequestBody JSONObject jsonObject){ + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String buyer_username = jsonObject.getString("buyer_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.buyerPayOrder(order_id) < 1) { + sb.append("订单号: ").append(order_id).append(" 支付失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 支付成功\n"); + continue; + } + } + return Result.ok(sb); + } + //买家查询待确认的订单 @GetMapping("/buyer/unconfirmed") public Object buyerSearchUnconfirmedOrder(@RequestParam String buyer_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.buyerSearchUnconfirmedOrder(buyer_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchUnconfirmedOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //卖家查询待确认的订单 @GetMapping("/seller/unconfirmed") public Object sellerSearchUnconfirmedOrder(@RequestParam String seller_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.sellerSearchUnconfirmedOrder(seller_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchUnconfirmedOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //卖家确认待确认的订单 @PutMapping(value = "/seller/confirm") - public Object confirmOrder(@RequestBody Order[] orders){ - for (Order order:orders) { - if(orderService.confirmOrder(order.getSeller_username(),order.getOrder_id()) < 1) { - return Result.fail("订单号为"+order.getOrder_id()+"的"+order.getGoods_name()+"确认失败,后续订单操作被迫中止"); + public Object sellerConfirmOrder(@RequestBody JSONObject jsonObject){ + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String seller_username = jsonObject.getString("seller_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.sellerConfirmOrder(seller_username,order_id) < 1) { + sb.append("订单号: ").append(order_id).append(" 确认失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 确认成功\n"); + continue; } } - return Result.ok(); + return Result.ok(sb); } //买家查询待备货的订单 @GetMapping("/buyer/unpicked") - public Object buyerSearchUnpickOrder(@RequestParam String buyer_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.buyerSearchUnpickOrder(buyer_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + public Object buyerSearchUnpickedOrder(@RequestParam String buyer_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchUnpickedOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //卖家查询待备货的订单 @GetMapping("/seller/unpicked") - public Object sellerSearchUnpickOrder(@RequestParam String seller_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.sellerSearchUnpickOrder(seller_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + public Object sellerSearchUnpickedOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchUnpickedOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //卖家完成备货订单 @PutMapping(value = "/seller/pick") - public Object pickOrder(@RequestBody Order[] orders){ - for (Order order:orders) { - if(orderService.pickOrder(order.getSeller_username(),order.getOrder_id()) < 1) { - return Result.fail("订单号为"+order.getOrder_id()+"的"+order.getGoods_name()+"完成备货失败,后续订单操作被迫中止"); + public Object sellerPickOrder(@RequestBody JSONObject jsonObject){ + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String seller_username = jsonObject.getString("seller_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.sellerPickOrder(seller_username,order_id) < 1) { + sb.append("订单号: ").append(order_id).append(" 备货失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 备货成功\n"); + continue; } } - return Result.ok(); + return Result.ok(sb); } //买家查询待发货的订单 @GetMapping("/buyer/undelivered") public Object buyerSearchUndeliveredOrder(@RequestParam String buyer_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.buyerSearchUndeliverOrder(buyer_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } - } - - //买家修改待发货的订单收货人信息 - @PutMapping(value = "/buyer/undelivered") - public Object buyerUpdateUndeliveredOrder(@RequestBody Map request){ - try { - JSONObject jsonObject = new JSONObject(); - String buyer_username = request.get("buyer_username"); - String buyer_realname = request.get("buyer_realname"); - String buyer_phonenumber = request.get("buyer_phonenumber"); - String buyer_address = request.get("buyer_address"); - int order_id = Integer.parseInt(request.get("order_id")); - Order order = new Order(order_id,buyer_username,buyer_realname,buyer_phonenumber,buyer_address); - System.out.println(order); - int result = orderService.buyerUpdateUndeliverOrder(order); - if (result >= 1){ - return Result.ok(); - }else { - return Result.fail(); - } - }catch (Exception e){ - return Result.fail(); - } + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchUndeliveredOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //卖家查询待发货的订单 - @GetMapping("/seller/Undelivered") + @GetMapping("/seller/undelivered") public Object sellerSearchUndeliveredOrder(@RequestParam String seller_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.sellerSearchUndeliverOrder(seller_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchUndeliveredOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + } + + //买家修改待发货的订单收货人信息 + @PutMapping(value = "/buyer/undelivered") + public Object buyerUpdateUndeliveredOrder(@RequestBody JSONObject jsonObject){ + Order order = new Order(jsonObject); + if (orderService.buyerUpdateUndeliveredOrder(order) >= 1){ + return Result.ok("订单:"+order.getOrder_id()+"地址修改成功\n"); + }else { + return Result.fail("订单:"+order.getOrder_id()+"地址修改失败\n"); } } //卖家发货订单 @PutMapping(value = "/seller/deliver") - public Object deliverOrder(@RequestBody Order[] orders){ - for (Order order:orders) { - if(orderService.deliverOrder(order.getSeller_username(),order.getOrder_id()) < 1) { - return Result.fail("订单号为"+order.getOrder_id()+"的"+order.getGoods_name()+"发货失败,后续订单操作被迫中止"); + public Object sellerDeliverOrder(@RequestBody JSONObject jsonObject) throws UnsupportedEncodingException { + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String seller_username = jsonObject.getString("seller_username"); + Long order_id; + Order order; + ResultData resultData; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + order = orderService.searchOrderByOrderId(order_id); + resultData = (ResultData) sfService.EXP_RECE_CREATE_ORDER(order); + if(resultData.getApiResultData().getSuccess() && orderService.sellerDeliverOrder(seller_username,order_id) >= 1) { + System.out.println(resultData.getApiResultData().getMsgData().getWaybillNoInfoList().get(0).getWaybillNo()); + orderService.setPackageNumberByOrderId(order_id,seller_username,resultData.getApiResultData().getMsgData().getWaybillNoInfoList().get(0).getWaybillNo()); + sb.append("订单号: ").append(order_id).append(" 发货成功\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 发货失败\n"); + continue; } } - return Result.ok(); + return Result.ok(sb); } - //卖家查询待收货的订单 - @GetMapping("/seller/Unfinished") - public Object sellerSearchUnfinishedOrder(@RequestParam String seller_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.sellerSearchUnfinishOrder(seller_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + //买家查询待收货的订单 + @GetMapping("/buyer/unarrived") + public Object buyerSearchUnarrivedOrder(@RequestParam String buyer_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchUnarrivedOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } + //卖家查询待收货的订单 + @GetMapping("/seller/unarrived") + public Object sellerSearchUnarrivedOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchUnarrivedOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + } //买家根据order_id(订单ID)完成交易 @PutMapping(value = "/buyer/finish") - public Object finishOrder(@RequestBody Map request) { - try { - String buyer_username = request.get("buyer_username"); - int order_id = Integer.parseInt(request.get("order_id")); - JSONObject jsonObject = new JSONObject(); - String finish_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - int result = orderService.finishOrder(buyer_username, order_id, finish_time); - if (result >= 1) { - return Result.ok(); - } else { - return Result.fail(); + public Object buyerFinishOrder(@RequestBody JSONObject jsonObject) { + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String buyer_username = jsonObject.getString("buyer_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.buyerFinishOrder(buyer_username, order_id, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) < 1) { + sb.append("订单号: ").append(order_id).append(" 确认收货失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 确认收货成功\n"); + continue; } - }catch (Exception e) { - return Result.fail(); } + return Result.ok(sb); } - //卖家根据order_id(订单ID)取消订单 - @PutMapping(value = "/seller/cancel") - public Object sellerCancelOrder(@RequestBody Order[] orders){ - for (Order order:orders) { - if(orderService.sellerCancelOrder(order.getOrder_id(),order.getSeller_username()) < 1) { - return Result.fail("订单号为"+order.getOrder_id()+"的"+order.getGoods_name()+"取消失败,后续订单操作被迫中止"); - } - } - return Result.ok(); + //买家查询已签收的订单 + @GetMapping("/buyer/finish") + public Object buyerSearchFinishOrder(@RequestParam String buyer_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchFinishOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + } + + //卖家查询已签收的订单 + @GetMapping("/seller/finish") + public Object sellerSearchFinishOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchFinishOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } //买家根据order_id(订单ID)取消订单 @PutMapping(value = "/buyer/cancel") - public Object buyerCancelOrder(@RequestBody Map request){ - try { - String buyer_username = request.get("buyer_username"); - int order_id = Integer.parseInt(request.get("order_id")); - JSONObject jsonObject = new JSONObject(); - goService.deleteGOByOrderId(order_id); - int result = orderService.buyerCancelOrder(order_id,buyer_username); - if (result >= 1) { - return Result.ok(); - } else { - return Result.fail(); + public Object buyerCancelOrder(@RequestBody JSONObject jsonObject) { + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String buyer_username = jsonObject.getString("buyer_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.buyerCancelOrder(buyer_username, order_id, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) < 1) { + sb.append("订单号: ").append(order_id).append(" 买家取消订单失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 买家取消订单成功\n"); + continue; } - }catch (Exception e) { - return Result.fail(); } + return Result.ok(sb); } - - //买家查询未完成的订单 - @GetMapping("/buyer/unfinished") - public Object buyerSearchUnfinishedOrder(@RequestParam String buyer_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.buyerSearchUnfinishOrder(buyer_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); + //卖家根据order_id(订单ID )取消订单 + @PutMapping(value = "/seller/cancel") + public Object sellerCancelOrder(@RequestBody JSONObject jsonObject) { + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + String seller_username = jsonObject.getString("seller_username"); + Long order_id; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + if(orderService.sellerCancelOrder(seller_username, order_id, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) < 1) { + sb.append("订单号: ").append(order_id).append(" 卖家取消订单失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 卖家取消订单成功\n"); + continue; + } } + return Result.ok(sb); } - - //买家查询已完成的订单 - @GetMapping("/buyer/finished") - public Object buyerSearchFinishOrder(@RequestParam String buyer_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.buyerSearchFinishOrder(buyer_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + //买家查询已取消的订单 + @GetMapping("/buyer/cancel") + public Object buyerSearchCancelOrder(@RequestParam String buyer_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.buyerSearchCancelOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } - //卖家查询已完成的订单 - @GetMapping("/seller/finished") - public Object sellerSearchFinishOrder(@RequestParam String seller_username){ - try{ - JSONObject jsonObject = new JSONObject(); - List orderList = orderService.sellerSearchFinishOrder(seller_username); - jsonObject.put("orders",orderList); - return Result.ok(jsonObject); - }catch (Exception e){ - return Result.fail(); - } + //卖家查询已取消的订单 + @GetMapping("/seller/cancel") + public Object sellerSearchCancelOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchCancelOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); } + //买家查询售后处理中的订单 + /*@GetMapping("/buyer/dealing") + public Object buyerSearchDealingOrder(@RequestBody JSONObject jsonObject){ + String buyer_username = jsonObject.getString("buyer_username"); + List orderList = orderService.buyerSearchDealingOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + }*/ + + //卖家查询售后处理中的订单 + /*@GetMapping("/seller/dealing") + public Object sellerSearchDealingOrder(@RequestBody JSONObject jsonObject){ + String seller_username = jsonObject.getString("seller_username"); + List orderList = orderService.sellerSearchDealingOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + }*/ + + //买家查询售后处理的订单 + /*@GetMapping("/buyer/aftApplication") + public Object buyerSearchAfterOrder(@RequestBody JSONObject jsonObject){ + String buyer_username = jsonObject.getString("buyer_username"); + List orderList = orderService.buyerSearchAfterOrder(buyer_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + }*/ + + //卖家查询售后处理的订单 + /*@GetMapping("/seller/aftApplication") + public Object sellerSearchAfterOrder(@RequestBody JSONObject jsonObject){ + String seller_username = jsonObject.getString("seller_username"); + List orderList = orderService.sellerSearchAfterOrder(seller_username); + jsonObject.clear(); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + }*/ + + //卖家查询同意退款的订单 + @GetMapping("/seller/aft_ok") + public Object sellerSearchAfterOkrOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchAfterOkrOrder(seller_username); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + } + //卖家查询拒绝退款的订单 + @GetMapping("/seller/aft_fail") + public Object sellerSearchAfterFailOrder(@RequestParam String seller_username){ + JSONObject jsonObject = new JSONObject(); + List orderList = orderService.sellerSearchAfterFailOrder(seller_username); + jsonObject.put("orders",orderList); + return Result.ok(jsonObject); + } - //意向购买者下单 - @PostMapping("/buyer/orders") - public Object addOrder(@RequestBody Order[] data){ - for (Order order:data) { - Goods good = goodsService.searchGoods(order.getItem_id()); - if (good.getGoods_state() != 1){ - return Result.fail("存在非在售商品:"+good.getGoods_name()); - } - if (order.getBuy_sum() > good.getGoods_stock()) { - return Result.fail("商品:"+good.getGoods_name()+"购买数量超出库存"); - } - order.setGoods_name(good.getGoods_name()); - order.setGoods_discribe(good.getGoods_discribe()); - order.setGoods_price(good.getGoods_price()); - order.setSeller_username(good.getSeller_username()); - order.setBuy_amount(order.getBuy_sum()*good.getGoods_price()); - order.setGoods_img(good.getGoods_img()); - order.setState(1); - if (order.getBuyer_phonenumber().length() != 11 && order.getBuyer_address().length() < 2 && order.getBuyer_address().length() > 100) { - return Result.fail("用户信息输入有误"); - } - order.setCreate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); - if(orderService.addOrder(order) < 1) { - return Result.fail("商品:"+good.getGoods_name()+"下单失败,后续下单被迫中止"); - } else { - cartService.deleteCart(order.getBuyer_username(), order.getItem_id()); - goodsService.updateGoodStock(good.getItem_id(),good.getGoods_stock()-order.getBuy_sum()); + //卖家根据order_id(订单ID)设置订单总金额 + @PutMapping(value = "/seller/amount") + public Object setAmountByOrderId(@RequestBody JSONObject jsonObject) { + String seller_username = jsonObject.getString("seller_username"); + Iterator objectIterator = jsonObject.getJSONArray("orders").iterator(); + Long order_id; + Float buy_amount; + StringBuilder sb = new StringBuilder(); + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + order_id = jb.getLong("order_id"); + buy_amount = jb.getFloatValue("buy_amount"); + if(orderService.setAmountByOrderId(order_id, seller_username, buy_amount) < 1) { + sb.append("订单号: ").append(order_id).append(" 设置金额失败\n"); + continue; + }else{ + sb.append("订单号: ").append(order_id).append(" 设置金额成功\n"); + continue; } } - return Result.ok(); + return Result.ok(sb); } - } diff --git a/back-end_code/src/main/java/com/shop/controller/PackageController.java b/back-end_code/src/main/java/com/shop/controller/PackageController.java new file mode 100644 index 0000000000000000000000000000000000000000..06a7e1ccab661840e57e20e2b4e1f10eec7e092f --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/PackageController.java @@ -0,0 +1,30 @@ +package com.shop.controller; + +import com.alibaba.fastjson.JSONObject; +import com.shop.entity.Order; +import com.shop.entity.sf.ResultData; +import com.shop.entity.sf.RouteResp; +import com.shop.entity.sf.RoutesResultData; +import com.shop.service.SFService; +import com.shop.utils.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.io.UnsupportedEncodingException; +import java.text.ParseException; + +@RestController +@RequestMapping("/package") +public class PackageController { + @Autowired + private SFService sfService; + + @GetMapping("/routes") + public Object SearchRoutes(@RequestParam String package_number) throws UnsupportedEncodingException, ParseException { + JSONObject jsonObject = new JSONObject(); + RoutesResultData resultData = (RoutesResultData) sfService.EXP_RECE_SEARCH_ROUTES(package_number); + RouteResp routeResp = resultData.getApiResultData().getMsgData().getRouteResps().get(0); + jsonObject.put("routes",routeResp); + return Result.ok(jsonObject); + } +} diff --git a/back-end_code/src/main/java/com/shop/controller/SnapshotController.java b/back-end_code/src/main/java/com/shop/controller/SnapshotController.java new file mode 100644 index 0000000000000000000000000000000000000000..50aedd77e8ef58d600dd4a7ac6c86cea572c7557 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/SnapshotController.java @@ -0,0 +1,67 @@ +package com.shop.controller; + +import com.shop.entity.Snapshot; +import com.shop.service.SnapshotService; +import com.shop.utils.Result; +import net.minidev.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/snapshot") +public class SnapshotController { + @Autowired + private SnapshotService snapshotService; + + //删除交易快照 + @DeleteMapping("/{snapshot_id}") + public Object deleteSnapshotBySnapshotId(@PathVariable Integer snapshot_id){ + try { + if (snapshotService.deleteSnapshotBySnapshotId(snapshot_id) < 1) + return Result.fail("删除交易快照失败"); + } catch (Exception e) { + return Result.fail(e.toString()); + } + return Result.ok(); + } + + //更新交易快照 + @PutMapping("/Snapshot") + public Object updateSnapshot(@RequestBody Snapshot snapshot){ + try { + if (snapshotService.updateSnapshot(snapshot) < 1) + return Result.fail("更新交易快照失败"); + } catch (Exception e) { + return Result.fail(e.toString()); + } + return Result.ok(); + } + + //根据商品Id查找商品的全部交易快照 + @GetMapping("/{item_id}") + public Object searchSnapshotByGoodId(@PathVariable Integer item_id){ + try{ + JSONObject jsonObject = new JSONObject(); + List snapshotes =snapshotService.searchSnapshotByGoodId(item_id); + jsonObject.put("snapshotes",snapshotes); + return Result.ok(jsonObject); + }catch (Exception e){ + return Result.fail(e.toString()); + } + } + + //根据SnapshotId查询Snapshot + @GetMapping("/{snapshot_id}") + public Object searchSnapshotBySnapshotId(@PathVariable Integer snapshot_id){ + try{ + JSONObject jsonObject = new JSONObject(); + Snapshot snapshot =snapshotService.searchSnapshotBySnapshotId(snapshot_id); + jsonObject.put("snapshot",snapshot); + return Result.ok(jsonObject); + }catch (Exception e){ + return Result.fail(e.toString()); + } + } +} diff --git a/back-end_code/src/main/java/com/shop/controller/UnipayController.java b/back-end_code/src/main/java/com/shop/controller/UnipayController.java new file mode 100644 index 0000000000000000000000000000000000000000..6f3900e8d3b0c6ce92b6afc622056cdc3177d6f9 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/controller/UnipayController.java @@ -0,0 +1,110 @@ +package com.shop.controller; + +import com.shop.service.UnionPaymentService; +import com.shop.utils.JsonResult; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by wangfei on 2017/4/22. + */ + +@Validated +@RestController +@RequestMapping("/union") +public class UnipayController { + + @Autowired + private UnionPaymentService service; + + /** + * 支付 + * @param request + * @param response + * @throws IOException + */ + @RequestMapping(value = "/pay", method = {RequestMethod.POST, RequestMethod.GET}) + public void pay(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + service.pay(request, response); + + } + + /** + * 后台回调 + * @param request + * @param response + * @throws IOException + */ + @RequestMapping(value = "/backRcvResponse", method = {RequestMethod.GET, RequestMethod.POST}) + public void backRcvResponse(HttpServletRequest request, HttpServletResponse response) throws IOException { + + service.backRcvResponse(request, response); + + } + + /** + * 前台回调 + * @param request + * @param response + * @throws IOException + */ + @RequestMapping(value = "/frontRcvResponse", method = RequestMethod.GET) + public void frontRcvResponse(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + + service.frontRcvResponse(request, response); + + } + + /** + * 成功后跳转 + * @param request + * @param response + * @throws IOException + */ + @RequestMapping(value = "/successRedict", method = RequestMethod.GET) + public void successRedict(HttpServletRequest request, HttpServletResponse response) throws IOException { + + service.successRedict(request, response); + + } + + /** + * 查询、检查交易状态 + * @param request + * @param response + */ + @RequestMapping(value = "/query", method = RequestMethod.POST) + public void query(HttpServletRequest request, HttpServletResponse response) throws IOException { + + service.query(request, response); + + } + + /** + * 交易状态查询 + * @param orderId + */ + @RequestMapping(value = "/check", method = RequestMethod.POST) + public JsonResult check(Long orderId) { + + try { + service.check(orderId); + return JsonResult.resultSuccess("已支付", ""); + } catch (Exception e) { + e.printStackTrace(); + return JsonResult.resultError("未发现支付信息"); + } + + } + + +} diff --git a/back-end_code/src/main/java/com/shop/controller/UserController.java b/back-end_code/src/main/java/com/shop/controller/UserController.java index 9c2328a24c22c25ccb05ea06b849e22ace7cb3e2..5390083b5902d78767a8778c8c6e82d66829f721 100644 --- a/back-end_code/src/main/java/com/shop/controller/UserController.java +++ b/back-end_code/src/main/java/com/shop/controller/UserController.java @@ -1,23 +1,13 @@ package com.shop.controller; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.shop.annotation.PassToken; import com.shop.annotation.UserLoginToken; import com.shop.entity.User; import com.shop.token.TokenService; -import com.shop.utils.JasyptUtil; -import net.minidev.json.JSONObject; +import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.shop.service.UserService; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -36,7 +26,7 @@ public class UserController { @PostMapping(value = "/login") public Object loginByPassword(@RequestBody User tryingUser){ String message = "error"; - String username =tryingUser.getUserName(); + String username =tryingUser.getUsername(); String password = tryingUser.getPassword(); JSONObject jsonObject = new JSONObject(); if(username.length()<=10&&username.length()>=3&&password.length()>=7&&password.length()<=15){ @@ -103,23 +93,16 @@ public class UserController { //用户注册 @PostMapping(value = "/registerUser") - public Object registerUser(@RequestBody User user){ + public Object registerUser(@RequestBody JSONObject jsonObject){ + System.out.println(jsonObject); String message = "error"; String info="注册成功"; - String username = user.getUserName(); - String password = user.getPassword(); - String nickname = user.getNickName(); - int permission = 1; - String phonenumber = user.getPhonenumber(); - String address = user.getAddress(); - String realname = user.getRealname(); - String user_head = user.getUserHead(); - if (user_head == null){ - user_head = "http://cdn.souldays.top/image/2021-12-06-eb3ac6b8edac4612806b08f967b88963.jpg"; + User user = new User(jsonObject); + if (jsonObject.getString("user_head") == null){ + user.setUser_head("http://cdn.souldays.top/image/2021-12-06-eb3ac6b8edac4612806b08f967b88963.jpg"); } - JSONObject jsonObject = new JSONObject(); - User newUser = new User(username,password,nickname,permission,phonenumber,address,realname,user_head); - int result = userService.registerUser(newUser); + jsonObject.clear(); + int result = userService.registerUser(user); if (result >= 1){ message = "success"; }else if (result==-1){ @@ -153,15 +136,8 @@ public class UserController { @PutMapping(value = "/updateUser") public Object updateUser(@RequestBody User user){ String message = "error"; - String username = user.getUserName(); - String nickname = user.getNickName(); - String realname = user.getRealname(); - String phonenumber = user.getPhonenumber(); - String address = user.getAddress(); - String user_head = user.getUserHead(); JSONObject jsonObject = new JSONObject(); - User newUser = new User(username,nickname,phonenumber,address,realname,user_head); - int result = userService.updateUser(newUser); + int result = userService.updateUser(user); if (result >= 1){ message = "success"; } diff --git a/back-end_code/src/main/java/com/shop/entity/Address.java b/back-end_code/src/main/java/com/shop/entity/Address.java new file mode 100644 index 0000000000000000000000000000000000000000..dabcf8821c1844f8e4ca8f819d06b246c1cc5141 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/Address.java @@ -0,0 +1,116 @@ +package com.shop.entity; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.Select; + +import java.util.Iterator; + +public class Address { + private int address_id; + private String username; + private String realname; + private String region; + private String detail; + private String phonenumber; + private Select selected ; + + public Address(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getInteger("address_id") != null) + this.address_id = jsonObject.getInteger("address_id"); + if (jsonObject.getString("username") != null) + this.username = jsonObject.getString("username"); + if (jsonObject.getString("realname") != null) + this.realname = jsonObject.getString("realname"); + if (jsonObject.getString("region") != null) + this.region = jsonObject.getString("region"); + if (jsonObject.getString("detail") != null) + this.detail = jsonObject.getString("detail"); + if (jsonObject.getString("phonenumber") != null) + this.phonenumber = jsonObject.getString("phonenumber"); + if (jsonObject.getString("selected") != null) + this.selected = Select.toenum(jsonObject.getString("selected")); + } + + public Address(int address_id, String username, String realname, String region, String detail, String phonenumber, Select selected) { + this.address_id = address_id; + this.username = username; + this.realname = realname; + this.region = region; + this.detail = detail; + this.phonenumber = phonenumber; + this.selected = selected; + } + + public int getAddress_id() { + return address_id; + } + + public void setAddress_id(int address_id) { + this.address_id = address_id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getRealname() { + return realname; + } + + public void setRealname(String realname) { + this.realname = realname; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getDetail() { + return detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public String getPhonenumber() { + return phonenumber; + } + + public void setPhonenumber(String phonenumber) { + this.phonenumber = phonenumber; + } + + public Select getSelected() { + return selected; + } + + public void setSelected(Select selected) { + this.selected = selected; + } + + public Address() { + } + + @Override + public String toString() { + return "Address{" + + "address_id=" + address_id + + ", username='" + username + '\'' + + ", realname='" + realname + '\'' + + ", region='" + region + '\'' + + ", detail='" + detail + '\'' + + ", phonenumber='" + phonenumber + '\'' + + ", selected=" + selected + + '}'; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/AftApplication.java b/back-end_code/src/main/java/com/shop/entity/AftApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..8c833eb6c376009f974a287a89c687abc37caa8a --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/AftApplication.java @@ -0,0 +1,167 @@ +package com.shop.entity; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.AftApplicationState; +import com.shop.Enum.AftApplicationType; +import com.shop.Enum.PackageState; +import com.shop.service.OrderService; + +import java.util.Iterator; + +public class AftApplication { + private Integer aftApplication_id; + private Long order_id; + private String aftApplication_buyerusername; + private String aftApplication_sellerusername; + private PackageState package_state;// 快递状态 + private AftApplicationType aftApplication_type;// 申诉类型 + private String aftApplication_reason; + private String aftApplication_images; + private AftApplicationState aftApplication_state; // 申诉状态 + private String create_time; + private String finish_time; + + public AftApplication() { + } + + public AftApplication(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getInteger("aftApplication_id") != null) + this.aftApplication_id = jsonObject.getInteger("aftApplication_id"); + if (jsonObject.getLong("order_id") != null) + this.order_id = jsonObject.getLong("order_id"); + if (jsonObject.getString("aftApplication_buyerusername") != null) + this.aftApplication_buyerusername = jsonObject.getString("aftApplication_buyerusername"); + if (jsonObject.getString("aftApplication_sellerusername") != null) + this.aftApplication_sellerusername = jsonObject.getString("aftApplication_sellerusername"); + if (jsonObject.getString("package_state") != null) + this.package_state = PackageState.toenum(jsonObject.getString("package_state")); + if (jsonObject.getString("aftApplication_type") != null) + this.aftApplication_type = AftApplicationType.toenum(jsonObject.getString("aftApplication_type")); + if (jsonObject.getString("aftApplication_reason") != null) + this.aftApplication_reason = jsonObject.getString("aftApplication_reason"); + if (jsonObject.getString("aftApplication_images") != null) + this.aftApplication_images = jsonObject.getString("aftApplication_images"); + if (jsonObject.getString("aftApplication_state") != null) + this.aftApplication_state = AftApplicationState.toenum(jsonObject.getString("aftApplication_state")); + if (jsonObject.getString("create_time") != null) + this.create_time = jsonObject.getString("create_time"); + if (jsonObject.getString("finish_time") != null) + this.finish_time = jsonObject.getString("finish_time"); + } + + public AftApplication(Order order,AftApplicationType aftApplication_type,String aftApplication_reason,PackageState package_state,String aftApplication_images) { + this.order_id = order.getOrder_id(); + this.aftApplication_buyerusername = order.getBuyer_username(); + this.aftApplication_sellerusername = order.getSeller_username(); + this.package_state = package_state; + this.aftApplication_type = aftApplication_type; + if (aftApplication_reason != null) + this.aftApplication_reason = aftApplication_reason; + if (aftApplication_images != null) + this.aftApplication_images = aftApplication_images; + this.create_time = order.getCreate_time(); + if (order.getFinish_time() != null) + this.finish_time = order.getFinish_time(); + } + + public AftApplication(Long order_id, String aftApplication_buyerusername, String aftApplication_sellerusername, PackageState package_state, AftApplicationType aftApplication_type, String aftApplication_reason, String aftApplication_images, AftApplicationState aftApplication_state, String create_time) { + this.order_id = order_id; + this.aftApplication_buyerusername = aftApplication_buyerusername; + this.aftApplication_sellerusername = aftApplication_sellerusername; + this.package_state = package_state; + this.aftApplication_type = aftApplication_type; + this.aftApplication_reason = aftApplication_reason; + this.aftApplication_images = aftApplication_images; + this.aftApplication_state = aftApplication_state; + this.create_time = create_time; + } + + public Integer getAftApplication_id() { + return aftApplication_id; + } + + public void setAftApplication_id(Integer aftApplication_id) { + this.aftApplication_id = aftApplication_id; + } + + public long getOrder_id() { + return order_id; + } + + public void setOrder_id(Long order_id) { + this.order_id = order_id; + } + + public String getAftApplication_buyerusername() { + return aftApplication_buyerusername; + } + + public void setAftApplication_buyerusername(String aftApplication_buyerusername) { + this.aftApplication_buyerusername = aftApplication_buyerusername; + } + + public String getAftApplication_sellerusername() { + return aftApplication_sellerusername; + } + + public void setAftApplication_sellerusername(String aftApplication_sellerusername) { + this.aftApplication_sellerusername = aftApplication_sellerusername; + } + + public PackageState getPackage_state() { + return package_state; + } + + public void setPackage_state(PackageState package_state) { + this.package_state = package_state; + } + + public AftApplicationType getAftApplication_type() { + return aftApplication_type; + } + + public void setAftApplication_type(AftApplicationType aftApplication_type) { + this.aftApplication_type = aftApplication_type; + } + + public String getAftApplication_reason() { + return aftApplication_reason; + } + + public void setAftApplication_reason(String aftApplication_reason) { + this.aftApplication_reason = aftApplication_reason; + } + + public String getAftApplication_images() { + return aftApplication_images; + } + + public void setAftApplication_images(String aftApplication_images) { + this.aftApplication_images = aftApplication_images; + } + + public AftApplicationState getAftApplication_state() { + return aftApplication_state; + } + + public void setAftApplication_state(AftApplicationState aftApplication_state) { + this.aftApplication_state = aftApplication_state; + } + + public String getCreate_time() { + return create_time; + } + + public void setCreate_time(String create_time) { + this.create_time = create_time; + } + + public String getFinish_time() { + return finish_time; + } + + public void setFinish_time(String finish_time) { + this.finish_time = finish_time; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/GO.java b/back-end_code/src/main/java/com/shop/entity/GO.java index 144a1a9f460c9f550e251f5ec09c40721944a38f..0548db5e9ff71f3deac63633ffe7298e7cfa6986 100644 --- a/back-end_code/src/main/java/com/shop/entity/GO.java +++ b/back-end_code/src/main/java/com/shop/entity/GO.java @@ -3,7 +3,7 @@ package com.shop.entity; public class GO { private int GO_id; private int item_id; - private int order_id; + private Long order_id; public int getGO_id() { return GO_id; @@ -13,7 +13,7 @@ public class GO { this.GO_id = GO_id; } - public GO(int GO_id, int item_id, int order_id) { + public GO(int GO_id, int item_id, Long order_id) { this.GO_id = GO_id; this.item_id = item_id; this.order_id = order_id; @@ -22,7 +22,7 @@ public class GO { public GO() { } - public GO(int item_id, int order_id) { + public GO(int item_id, Long order_id) { this.item_id = item_id; this.order_id = order_id; } @@ -44,11 +44,11 @@ public class GO { this.item_id = item_id; } - public int getOrder_id() { + public Long getOrder_id() { return order_id; } - public void setOrder_id(int order_id) { + public void setOrder_id(Long order_id) { this.order_id = order_id; } } diff --git a/back-end_code/src/main/java/com/shop/entity/Goods.java b/back-end_code/src/main/java/com/shop/entity/Goods.java index a79dcc81ea7510594ea121953d102ac325afee95..ccdbde820b123cbecf5fe7a556c2a7c5b7a971dc 100644 --- a/back-end_code/src/main/java/com/shop/entity/Goods.java +++ b/back-end_code/src/main/java/com/shop/entity/Goods.java @@ -1,74 +1,76 @@ package com.shop.entity; +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.GoodState; + +import java.util.Iterator; + public class Goods { private int item_id; private String goods_name; private String seller_username; private int goods_stock; private String goods_img; - private String goods_discribe; + private String goods_describe; private int goods_category; private float goods_price; - private int goods_state;//int型 1表示在售,2表示冻结,3表示下架 + private GoodState goods_state; public Goods() { super(); } - public Goods(String goods_name, String seller_username, int goods_stock, String goods_img, String goods_discribe, float goods_price) { - this.goods_name = goods_name; - this.seller_username = seller_username; - this.goods_stock = goods_stock; - this.goods_img = goods_img; - this.goods_discribe = goods_discribe; - this.goods_price = goods_price; - } - - public int getGoods_category() { - return goods_category; - } - - public void setGoods_category(int goods_category) { - this.goods_category = goods_category; - } - - public Goods(int item_id, String goods_name, String seller_username, int goods_stock, String goods_img, String goods_discribe, int goods_category, float goods_price) { + public Goods(int item_id, String goods_name, String seller_username, int goods_stock, String goods_img, String goods_describe, int goods_category, float goods_price, GoodState goods_state) { this.item_id = item_id; this.goods_name = goods_name; this.seller_username = seller_username; this.goods_stock = goods_stock; this.goods_img = goods_img; - this.goods_discribe = goods_discribe; + this.goods_describe = goods_describe; this.goods_category = goods_category; this.goods_price = goods_price; - } - - public Goods(int item_id, String goods_name, String seller_username, int goods_stock, String goods_img, String goods_discribe, float goods_price, int goods_state) { - this.item_id = item_id; - this.goods_name = goods_name; - this.seller_username = seller_username; - this.goods_stock = goods_stock; - this.goods_img = goods_img; - this.goods_discribe = goods_discribe; - this.goods_price = goods_price; this.goods_state = goods_state; } - public Goods(int item_id, String goods_name, String seller_username, String goods_img, String goods_discribe, float goods_price) { - this.item_id = item_id; - this.goods_name = goods_name; + public Goods(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getInteger("item_id") != null) + this.item_id = jsonObject.getInteger("item_id"); + if (jsonObject.getString("goods_name") != null) + this.goods_name = jsonObject.getString("goods_name"); + if (jsonObject.getString("seller_username") != null) + this.seller_username = jsonObject.getString("seller_username"); + if (jsonObject.getInteger("goods_stock") != null) + this.goods_stock = jsonObject.getInteger("goods_stock"); + if (jsonObject.getString("goods_img") != null) + this.goods_img = jsonObject.getString("goods_img"); + if (jsonObject.getString("goods_describe") != null) + this.goods_describe = jsonObject.getString("goods_describe"); + if (jsonObject.getInteger("goods_category") != null) + this.goods_category = jsonObject.getInteger("goods_category"); + if (jsonObject.getFloat("goods_price") != null) + this.goods_price = jsonObject.getFloatValue("goods_price"); + if (jsonObject.getString("goods_state") != null) + this.goods_state = GoodState.toenum(jsonObject.getString("goods_state")); + } + + public Goods(JSONObject jsonObject, String seller_username) { + Iterator objectIterator; + if (jsonObject.getInteger("item_id") != null) + this.item_id = jsonObject.getInteger("item_id"); + if (jsonObject.getString("goods_name") != null) + this.goods_name = jsonObject.getString("goods_name"); this.seller_username = seller_username; - this.goods_img = goods_img; - this.goods_discribe = goods_discribe; - this.goods_price = goods_price; - } - - public float getGoods_price() { - return goods_price; - } - - public void setGoods_price(float goods_price) { - this.goods_price = goods_price; + if (jsonObject.getInteger("goods_stock") != null) + this.goods_stock = jsonObject.getInteger("goods_stock"); + if (jsonObject.getString("goods_img") != null) + this.goods_img = jsonObject.getString("goods_img"); + if (jsonObject.getString("goods_describe") != null) + this.goods_describe = jsonObject.getString("goods_describe"); + if (jsonObject.getInteger("goods_category") != null) + this.goods_category = jsonObject.getInteger("goods_category"); + if (jsonObject.getFloat("goods_price") != null) + this.goods_price = jsonObject.getFloatValue("goods_price"); } public int getItem_id() { @@ -79,14 +81,6 @@ public class Goods { this.item_id = item_id; } - public int getGoods_stock() { - return goods_stock; - } - - public void setGoods_stock(int goods_stock) { - this.goods_stock = goods_stock; - } - public String getGoods_name() { return goods_name; } @@ -103,6 +97,14 @@ public class Goods { this.seller_username = seller_username; } + public int getGoods_stock() { + return goods_stock; + } + + public void setGoods_stock(int goods_stock) { + this.goods_stock = goods_stock; + } + public String getGoods_img() { return goods_img; } @@ -111,45 +113,35 @@ public class Goods { this.goods_img = goods_img; } - public String getGoods_discribe() { - return goods_discribe; + public String getGoods_describe() { + return goods_describe; } - public void setGoods_discribe(String goods_discribe) { - this.goods_discribe = goods_discribe; + public void setGoods_describe(String goods_describe) { + this.goods_describe = goods_describe; } - public int getGoods_state() { - return goods_state; + public int getGoods_category() { + return goods_category; } - public void setGoods_state(int goods_state) { - this.goods_state = goods_state; + public void setGoods_category(int goods_category) { + this.goods_category = goods_category; } - public Goods(String goods_name, String seller_username, int goods_stock, String goods_img, String goods_discribe, int goods_category, float goods_price) { - this.goods_name = goods_name; - this.seller_username = seller_username; - this.goods_stock = goods_stock; - this.goods_img = goods_img; - this.goods_discribe = goods_discribe; - this.goods_category = goods_category; + public float getGoods_price() { + return goods_price; + } + + public void setGoods_price(float goods_price) { this.goods_price = goods_price; } + public GoodState getGoods_state() { + return goods_state; + } - @Override - public String toString() { - return "Goods{" + - "item_id=" + item_id + - ", goods_name='" + goods_name + '\'' + - ", seller_username='" + seller_username + '\'' + - ", goods_stock=" + goods_stock + - ", goods_img='" + goods_img + '\'' + - ", goods_discribe='" + goods_discribe + '\'' + - ", goods_category=" + goods_category + - ", goods_price=" + goods_price + - ", goods_state=" + goods_state + - '}'; + public void setGoods_state(GoodState goods_state) { + this.goods_state = goods_state; } } diff --git a/back-end_code/src/main/java/com/shop/entity/Order.java b/back-end_code/src/main/java/com/shop/entity/Order.java index 4347ab8f784a8f427f28df09748e74a746b83c93..c842f4771bd1ae35cdc21b6d003fee3112a981ff 100644 --- a/back-end_code/src/main/java/com/shop/entity/Order.java +++ b/back-end_code/src/main/java/com/shop/entity/Order.java @@ -1,167 +1,130 @@ package com.shop.entity; -public class Order { - private int order_id; - private int item_id; - private String goods_name; - private String goods_img; - private String goods_discribe; - private float goods_price; - private String seller_username; +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.OrderState; +import com.shop.Enum.PackageState; +import com.shop.Enum.RefundState; - public Order(int order_id, String buyer_username, String buyer_realname, String buyer_phonenumber, String buyer_address) { - this.order_id = order_id; - this.buyer_username = buyer_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - } +import java.util.Iterator; +import java.util.List; +public class Order { + private Long order_id; + private List orderDetailList; private String buyer_username; - private String buyer_realname; - private String buyer_phonenumber; - private String buyer_address; - private int buy_sum; - private float buy_amount;//总价 - private int state;//int,1表示进行中,2表示交易成功,3表示买家退款,4表示卖家关闭交易,5表示申请中 + private Address address; + private String remark; + private Float buy_amount;//总价 + private String seller_username; + private OrderState order_state; + private RefundState refund_state; // 申诉状态 + private PackageState package_state; + private String package_number; private String create_time; private String finish_time; + public Order() { super(); } - public Order(int item_id, String goods_name, String goods_img, String goods_discribe, float goods_price, String seller_username, String buyer_username, String buyer_realname, String buyer_phonenumber, String buyer_address, int buy_sum, float buy_amount, int state, String create_time) { - this.item_id = item_id; - this.goods_name = goods_name; - this.goods_img = goods_img; - this.goods_discribe = goods_discribe; - this.goods_price = goods_price; - this.seller_username = seller_username; + public Order(Long order_id, String buyer_username, Address address) { + this.order_id = order_id; this.buyer_username = buyer_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - this.buy_sum = buy_sum; - this.buy_amount = buy_amount; - this.state = state; - this.create_time = create_time; - } - - public String getGoods_name() { - return goods_name; - } - - public void setGoods_name(String goods_name) { - this.goods_name = goods_name; - } - - public String getGoods_img() { - return goods_img; - } - - public void setGoods_img(String goods_img) { - this.goods_img = goods_img; - } - - public String getGoods_discribe() { - return goods_discribe; - } - - public void setGoods_discribe(String goods_discribe) { - this.goods_discribe = goods_discribe; - } - - public float getGoods_price() { - return goods_price; - } - - public void setGoods_price(float goods_price) { - this.goods_price = goods_price; + this.address = address; + } + + public Order(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getLong("order_id") != null) + this.order_id = jsonObject.getLong("order_id"); + if (jsonObject.getJSONArray("orderDetailList") != null) { + objectIterator = jsonObject.getJSONArray("orderDetailList").iterator(); + OrderDetail OrderDetail; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + OrderDetail = new OrderDetail(jb); + this.orderDetailList.add(OrderDetail); + } + } + if (jsonObject.getString("buyer_username") != null) + this.buyer_username = jsonObject.getString("buyer_username"); + if (jsonObject.getJSONObject("address") != null) + this.address = new Address(jsonObject.getJSONObject("address")); + if (jsonObject.getString("remark") != null) + this.remark = jsonObject.getString("remark"); + if (jsonObject.getFloat("buy_amount") != null) + this.buy_amount = jsonObject.getFloatValue("buy_amount"); + if (jsonObject.getString("seller_username") != null) + this.seller_username = jsonObject.getString("seller_username"); + if (jsonObject.getString("order_state") != null) + this.order_state = OrderState.toenum(jsonObject.getString("order_state")); + if (jsonObject.getString("refund_state") != null) + this.refund_state = RefundState.toenum(jsonObject.getString("refund_state")); + if (jsonObject.getString("package_state") != null) + this.package_state = PackageState.toenum(jsonObject.getString("package_state")); + if (jsonObject.getString("package_number") != null) + this.package_number = jsonObject.getString("package_number"); + if (jsonObject.getString("create_time") != null) + this.create_time = jsonObject.getString("create_time"); + if (jsonObject.getString("finish_time") != null) + this.finish_time = jsonObject.getString("finish_time"); + } + + public OrderState getOrder_state() { + return order_state; + } + + public void setOrder_state(OrderState order_state) { + this.order_state = order_state; + } + + public Long getOrder_id() { + return order_id; } - public float getBuy_amount() { - return buy_amount; + public void setOrder_id(Long order_id) { + this.order_id = order_id; } - public void setBuy_amount(float buy_amount) { - this.buy_amount = buy_amount; + public List getOrderDetailList() { + return orderDetailList; } - public Order(int item_id, String seller_username, String buyer_username, String buyer_realname, String buyer_phonenumber, String buyer_address, int buy_sum, float buy_amount, int state, String create_time) { - this.item_id = item_id; - this.seller_username = seller_username; - this.buyer_username = buyer_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - this.buy_sum = buy_sum; - this.buy_amount = buy_amount; - this.state = state; - this.create_time = create_time; + public void setOrderDetailList(List orderDetailList) { + this.orderDetailList = orderDetailList; } - public Order(int order_id, int item_id, String seller_username, String buyer_username, String buyer_realname, String buyer_phonenumber, String buyer_address, int buy_sum, int state, String create_time, String finish_time) { - this.order_id = order_id; - this.item_id = item_id; - this.seller_username = seller_username; - this.buyer_username = buyer_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - this.buy_sum = buy_sum; - this.state = state; - this.create_time = create_time; - this.finish_time = finish_time; + public String getBuyer_username() { + return buyer_username; } - public Order(int item_id, String seller_username, String buyer_username, String buyer_realname, String buyer_phonenumber, String buyer_address, int buy_sum, int state, String create_time) { - this.item_id = item_id; - this.seller_username = seller_username; + public void setBuyer_username(String buyer_username) { this.buyer_username = buyer_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - this.buy_sum = buy_sum; - this.state = state; - this.create_time = create_time; } - public int getOrder_id() { - return order_id; - } - - public void setOrder_id(int order_id) { - this.order_id = order_id; + public Address getAddress() { + return address; } - public int getItem_id() { - return item_id; + public void setAddress(Address address) { + this.address = address; } - public void setItem_id(int item_id) { - this.item_id = item_id; + public String getRemark() { + return remark; } - public int getBuy_sum() { - return buy_sum; + public void setRemark(String remark) { + this.remark = remark; } - public void setBuy_sum(int buy_sum) { - this.buy_sum = buy_sum; + public Float getBuy_amount() { + return buy_amount; } - public Order(int order_id, int item_id, String seller_username, String buyer_realname, String buyer_phonenumber, String buyer_address, int buy_sum, int state, String create_time, String finish_time) { - this.order_id = order_id; - this.item_id = item_id; - this.seller_username = seller_username; - this.buyer_realname = buyer_realname; - this.buyer_phonenumber = buyer_phonenumber; - this.buyer_address = buyer_address; - this.buy_sum = buy_sum; - this.state = state; - this.create_time = create_time; - this.finish_time = finish_time; + public void setBuy_amount(Float buy_amount) { + this.buy_amount = buy_amount; } public String getSeller_username() { @@ -172,45 +135,28 @@ public class Order { this.seller_username = seller_username; } - public String getBuyer_username() { - return buyer_username; + public RefundState getRefund_state() { + return refund_state; } - public void setBuyer_username(String buyer_username) { - this.buyer_username = buyer_username; - } - - public String getBuyer_realname() { - return buyer_realname; + public void setRefund_state(RefundState refund_state) { + this.refund_state = refund_state; } - public void setBuyer_realname(String buyer_realname) { - this.buyer_realname = buyer_realname; + public PackageState getPackage_state() { + return package_state; } - public String getBuyer_phonenumber() { - return buyer_phonenumber; + public void setPackage_state(PackageState package_state) { + this.package_state = package_state; } - public void setBuyer_phonenumber(String buyer_phonenumber) { - this.buyer_phonenumber = buyer_phonenumber; + public String getPackage_number() { + return package_number; } - - public String getBuyer_address() { - return buyer_address; - } - - public void setBuyer_address(String buyer_address) { - this.buyer_address = buyer_address; - } - - public int getState() { - return state; - } - - public void setState(int state) { - this.state = state; + public void setPackage_number(String package_number) { + this.package_number = package_number; } public String getCreate_time() { @@ -228,26 +174,4 @@ public class Order { public void setFinish_time(String finish_time) { this.finish_time = finish_time; } - - @Override - public String toString() { - return "Order{" + - "order_id=" + order_id + - ", item_id=" + item_id + - ", goods_name='" + goods_name + '\'' + - ", goods_img='" + goods_img + '\'' + - ", goods_discribe='" + goods_discribe + '\'' + - ", goods_price=" + goods_price + - ", seller_username='" + seller_username + '\'' + - ", buyer_username='" + buyer_username + '\'' + - ", buyer_realname='" + buyer_realname + '\'' + - ", buyer_phonenumber='" + buyer_phonenumber + '\'' + - ", buyer_address='" + buyer_address + '\'' + - ", buy_sum=" + buy_sum + - ", buy_amount=" + buy_amount + - ", state=" + state + - ", create_time='" + create_time + '\'' + - ", finish_time='" + finish_time + '\'' + - '}'; - } } diff --git a/back-end_code/src/main/java/com/shop/entity/OrderDetail.java b/back-end_code/src/main/java/com/shop/entity/OrderDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..229b37cb0d6456640af943f62dd1c8060ff690d6 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/OrderDetail.java @@ -0,0 +1,76 @@ +package com.shop.entity; + +import com.alibaba.fastjson.JSONObject; + +import java.util.Iterator; + +public class OrderDetail { + private Integer detail_id; + private Long order_id; + private Snapshot snapshot; + private Integer buy_stock; + private Float buy_sum; + + public OrderDetail() {} + + public OrderDetail(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getInteger("detail_id") != null) + this.detail_id = jsonObject.getInteger("detail_id"); + if (jsonObject.getLong("order_id") != null) + this.order_id = jsonObject.getLong("order_id"); + if (jsonObject.getJSONObject("snapshot") != null) + this.snapshot = new Snapshot(jsonObject.getJSONObject("snapshot")); + if (jsonObject.getInteger("buy_stock") != null) + this.buy_stock = jsonObject.getInteger("buy_stock"); + if (jsonObject.getFloat("buy_sum") != null) + this.buy_sum = jsonObject.getFloatValue("buy_sum"); + } + + public OrderDetail(Long order_id, Snapshot snapshot, Integer buy_stock, Float buy_sum) { + this.order_id = order_id; + this.snapshot = snapshot; + this.buy_stock = buy_stock; + this.buy_sum = buy_sum; + } + + public Integer getDetail_id() { + return detail_id; + } + + public void setDetail_id(Integer detail_id) { + this.detail_id = detail_id; + } + + public Long getOrder_id() { + return order_id; + } + + public void setOrder_id(Long order_id) { + this.order_id = order_id; + } + + public Snapshot getSnapshot() { + return snapshot; + } + + public void setSnapshot(Snapshot snapshot) { + this.snapshot = snapshot; + } + + public Integer getBuy_stock() { + return buy_stock; + } + + public void setBuy_stock(Integer buy_stock) { + this.buy_stock = buy_stock; + } + + public Float getBuy_sum() { + return buy_sum; + } + + public void setBuy_sum(Float buy_sum) { + this.buy_sum = buy_sum; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/Order_Goods.java b/back-end_code/src/main/java/com/shop/entity/Order_Goods.java index 5ce508ee427ae981732e14d028d26d9138cde550..72b8a0613107798c93d825f56f1de318fb2b517b 100644 --- a/back-end_code/src/main/java/com/shop/entity/Order_Goods.java +++ b/back-end_code/src/main/java/com/shop/entity/Order_Goods.java @@ -1,7 +1,7 @@ package com.shop.entity; public class Order_Goods { - private int order_id; + private Long order_id; private String buyer_realname; private String buyer_phonenumber; private String buyer_address; @@ -15,7 +15,7 @@ public class Order_Goods { public Order_Goods() { } - public Order_Goods(int order_id, String buyer_realname, String buyer_phonenumber, String buyer_address, int item_id, String goods_name, float goods_price, String goods_img, String goods_discribe) { + public Order_Goods(Long order_id, String buyer_realname, String buyer_phonenumber, String buyer_address, int item_id, String goods_name, float goods_price, String goods_img, String goods_discribe) { this.order_id = order_id; this.buyer_realname = buyer_realname; this.buyer_phonenumber = buyer_phonenumber; @@ -43,11 +43,11 @@ public class Order_Goods { '}'; } - public int getOrder_id() { + public Long getOrder_id() { return order_id; } - public void setOrder_id(int order_id) { + public void setOrder_id(Long order_id) { this.order_id = order_id; } @@ -123,7 +123,7 @@ public class Order_Goods { this.goods_discribe = goods_discribe; } - public Order_Goods(int order_id, String buyer_realname, String buyer_phonenumber, String buyer_address, String finish_time, int item_id, String goods_name, float goods_price, String goods_img, String goods_discribe) { + public Order_Goods(Long order_id, String buyer_realname, String buyer_phonenumber, String buyer_address, String finish_time, int item_id, String goods_name, float goods_price, String goods_img, String goods_discribe) { this.order_id = order_id; this.buyer_realname = buyer_realname; this.buyer_phonenumber = buyer_phonenumber; diff --git a/back-end_code/src/main/java/com/shop/entity/Snapshot.java b/back-end_code/src/main/java/com/shop/entity/Snapshot.java new file mode 100644 index 0000000000000000000000000000000000000000..9c8070707d1892322cd09893bbb4ff30c8f8714c --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/Snapshot.java @@ -0,0 +1,110 @@ +package com.shop.entity; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.GoodState; + +import java.util.Iterator; + + +public class Snapshot { + private Integer snapshot_id; + private Integer item_id; + private String goods_name; + private String goods_img; + private String goods_describe; + private Integer goods_category; + private Float goods_price; + private String snapshot_time; + + public Snapshot() { + } + + public Snapshot(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getInteger("snapshot_id") != null) + this.snapshot_id = jsonObject.getInteger("snapshot_id"); + if (jsonObject.getInteger("item_id") != null) + this.item_id = jsonObject.getInteger("item_id"); + if (jsonObject.getString("goods_name") != null) + this.goods_name = jsonObject.getString("goods_name"); + if (jsonObject.getString("goods_img") != null) + this.goods_img = jsonObject.getString("goods_img"); + if (jsonObject.getString("goods_describe") != null) + this.goods_describe = jsonObject.getString("goods_describe"); + if (jsonObject.getInteger("goods_category") != null) + this.goods_category = jsonObject.getInteger("goods_category"); + if (jsonObject.getFloat("goods_price") != null) + this.goods_price = jsonObject.getFloatValue("goods_price"); + if (jsonObject.getString("snapshot_time") != null) + this.snapshot_time = jsonObject.getString("snapshot_time"); + } + + public Snapshot(Goods goods) { + this.item_id = goods.getItem_id(); + this.goods_name = goods.getGoods_name(); + this.goods_img = goods.getGoods_img(); + this.goods_describe = goods.getGoods_describe(); + this.goods_category = goods.getGoods_category(); + this.goods_price = goods.getGoods_price(); + } + + public Integer getSnapshot_id() { return snapshot_id; } + + public void setSnapshot_id(Integer snapshot_id) { this.snapshot_id = snapshot_id; } + + public Integer getItem_id() { + return item_id; + } + + public void setItem_id(Integer item_id) { + this.item_id = item_id; + } + + public String getGoods_name() { + return goods_name; + } + + public void setGoods_name(String goods_name) { + this.goods_name = goods_name; + } + + public String getGoods_img() { + return goods_img; + } + + public void setGoods_img(String goods_img) { + this.goods_img = goods_img; + } + + public String getGoods_describe() { + return goods_describe; + } + + public void setGoods_describe(String goods_describe) { + this.goods_describe = goods_describe; + } + + public Integer getGoods_category() { + return goods_category; + } + + public void setGoods_category(Integer goods_category) { + this.goods_category = goods_category; + } + + public Float getGoods_price() { + return goods_price; + } + + public void setGoods_price(Float goods_price) { + this.goods_price = goods_price; + } + + public String getSnapshot_time() { + return snapshot_time; + } + + public void setSnapshot_time(String snapshot_time) { + this.snapshot_time = snapshot_time; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/User.java b/back-end_code/src/main/java/com/shop/entity/User.java index 9d95cb86030ac92839771881bc1e74bee6074828..da74505610657b016c5da7dc410c3233b1a868a8 100644 --- a/back-end_code/src/main/java/com/shop/entity/User.java +++ b/back-end_code/src/main/java/com/shop/entity/User.java @@ -1,51 +1,43 @@ package com.shop.entity; +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.Permission; + +import java.util.Iterator; + public class User { private String username; private String password; private String nickname; - private int permission; - private String phonenumber; - private String address; - private String realname; + private Permission permission; private String user_head; + private String shop_name; public User() { super(); } - public User(String username, String realname, String phonenumber, String address) { - this.username = username; - this.phonenumber = phonenumber; - this.address = address; - this.realname = realname; - } - - public User(String username, String nickname, String phonenumber, String address, String realname, String user_head) { - this.username = username; - this.nickname = nickname; - this.phonenumber = phonenumber; - this.address = address; - this.realname = realname; - this.user_head = user_head; - } - - public User(String username, String password, String nickname, int permission, String phonenumber, String address, String realname, String user_head) { - this.username = username; - this.password = password; - this.nickname = nickname; - this.permission = permission; - this.phonenumber = phonenumber; - this.address = address; - this.realname = realname; - this.user_head = user_head; + public User(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("username") != null) + this.username = jsonObject.getString("username"); + if (jsonObject.getString("password") != null) + this.password = jsonObject.getString("password"); + if (jsonObject.getString("nickname") != null) + this.nickname = jsonObject.getString("nickname"); + if (jsonObject.getString("permission") != null) + this.permission = Permission.toenum(jsonObject.getString("permission")); + if (jsonObject.getString("user_head") != null) + this.user_head = jsonObject.getString("user_head"); + if (jsonObject.getString("shop_name") != null) + this.shop_name = jsonObject.getString("shop_name"); } - public String getUserName() { + public String getUsername() { return username; } - public void setUserName(String username) { + public void setUsername(String username) { this.username = username; } @@ -57,66 +49,35 @@ public class User { this.password = password; } - public String getNickName() { + public String getNickname() { return nickname; } - public void setNickName(String nick_name) { - this.nickname = nick_name; + public void setNickname(String nickname) { + this.nickname = nickname; } - public int getPermission() { + public Permission getPermission() { return permission; } - public void setPermission(int permission) { + public void setPermission(Permission permission) { this.permission = permission; } - public String getPhonenumber() { - return phonenumber; - } - - public void setPhonenumber(String phonenumber) { - this.phonenumber = phonenumber; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getRealname() { - return realname; - } - - public void setRealname(String realname) { - this.realname = realname; - } - - public String getUserHead() { + public String getUser_head() { return user_head; } - public void setUserHead(String user_head) { + public void setUser_head(String user_head) { this.user_head = user_head; } + public String getShop_name() { + return shop_name; + } - @Override - public String toString() { - return "User{" + - "username='" + username + '\'' + - ", password='" + password + '\'' + - ", nickname='" + nickname + '\'' + - ", permission=" + permission + - ", phonenumber='" + phonenumber + '\'' + - ", address='" + address + '\'' + - ", realname='" + realname + '\'' + - ", user_head='" + user_head + '\'' + - '}'; + public void setShop_name(String shop_name) { + this.shop_name = shop_name; } } diff --git a/back-end_code/src/main/java/com/shop/entity/sf/ApiResultData.java b/back-end_code/src/main/java/com/shop/entity/sf/ApiResultData.java new file mode 100644 index 0000000000000000000000000000000000000000..d48059879c717ccb00ef0a20bedaa78941a9dcfc --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/ApiResultData.java @@ -0,0 +1,56 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.util.Iterator; + +public class ApiResultData { + private Boolean success; + private String errorCode; + private String errorMsg; + private msgDate msgData; + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public msgDate getMsgData() { + return msgData; + } + + public void setMsgData(msgDate msgData) { + this.msgData = msgData; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public ApiResultData(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getBoolean("success") != null) + this.success = jsonObject.getBoolean("success"); + if (jsonObject.getString("errorCode") != null) + this.errorCode = jsonObject.getString("errorCode"); + if (jsonObject.getString("errorMsg") != null) + this.errorMsg = jsonObject.getString("errorMsg"); + if (jsonObject.getJSONObject("msgData") != null) + this.msgData = new msgDate(jsonObject.getJSONObject("msgData")); + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/CargoDetail.java b/back-end_code/src/main/java/com/shop/entity/sf/CargoDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..c482673aa3c971c844d0d7861a149bae55911392 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/CargoDetail.java @@ -0,0 +1,246 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; +import com.shop.entity.OrderDetail; + +import java.util.Iterator; + +public class CargoDetail { + private String name; //货物名称,如果需要生成电子运单,则为必填. T-128 +// private String count; //货物数量 跨境件报关需要填写 C-5 +// private String unit; //货物单位,如:个、台、本,跨境件报关需要填写. C-30 +// private String weight; //订单货物单位重量,包含子母件,单位千克,精确到小数点后3位跨境件报关需要填写 C-16,3 +// private String amount; //货物单价,精确到小数点后3位,跨境件报关需要填写 C-17,3 +// private String taxNo; //商品行邮税号 F +// private String length; //托寄物长 F-16,3 +// private String width; //托寄物宽 F-16,3 +// private String height; //托寄物高 F-16,3 +// private String volume; //托寄物体积 F-16,2 +// private String cargoDeclaredValue; //托寄物声明价值 F-16,5 +// private String declaredValueDeclaredCurrency; // 托寄物声明价值币别 F-5 + + + public CargoDetail(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("name") != null) + this.name = jsonObject.getString("name"); + } + + public CargoDetail(OrderDetail orderDetail) { + this.name = orderDetail.getSnapshot().getGoods_name(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.name != null) { + if (num == 0) { + sb.append("\t\t\"name\": \"").append(name).append("\""); + } else { + sb.append(",\n").append("\t\"name\": \"").append(name).append("\""); + } + num = num + 1; + } + sb.append("\n\t}"); + return sb.toString(); + } + /*public String getCount() { + return count; + } + + public void setCount(String count) { + this.count = count; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public String getWeight() { + return weight; + } + + public void setWeight(String weight) { + this.weight = weight; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getTaxNo() { + return taxNo; + } + + public void setTaxNo(String taxNo) { + this.taxNo = taxNo; + } + + public String getLength() { + return length; + } + + public void setLength(String length) { + this.length = length; + } + + public String getWidth() { + return width; + } + + public void setWidth(String width) { + this.width = width; + } + + public String getHeight() { + return height; + } + + public void setHeight(String height) { + this.height = height; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public String getCargoDeclaredValue() { + return cargoDeclaredValue; + } + + public void setCargoDeclaredValue(String cargoDeclaredValue) { + this.cargoDeclaredValue = cargoDeclaredValue; + } + + public String getDeclaredValueDeclaredCurrency() { + return declaredValueDeclaredCurrency; + } + + public void setDeclaredValueDeclaredCurrency(String declaredValueDeclaredCurrency) { + this.declaredValueDeclaredCurrency = declaredValueDeclaredCurrency; + }*/ + + /*@Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.name != null) { + if (num == 0) { + sb.append("\t\t\"name\": \"").append(name).append("\""); + } else { + sb.append(",\n").append("\t\"name\": \"").append(name).append("\""); + } + num = num + 1; + } + if (this.count != null) { + if (num == 0) { + sb.append("\t\t\"count\": \"").append(count).append("\""); + } else { + sb.append(",\n").append("\t\"count\": \"").append(count).append("\""); + } + num = num + 1; + } + if (this.unit != null) { + if (num == 0) { + sb.append("\t\t\"unit\": \"").append(unit).append("\""); + } else { + sb.append(",\n").append("\t\"unit\": \"").append(unit).append("\""); + } + num = num + 1; + } + if (this.weight != null) { + if (num == 0) { + sb.append("\t\t\"weight\": \"").append(weight).append("\""); + } else { + sb.append(",\n").append("\t\"weight\": \"").append(weight).append("\""); + } + num = num + 1; + } + if (this.amount != null) { + if (num == 0) { + sb.append("\t\t\"amount\": \"").append(amount).append("\""); + } else { + sb.append(",\n").append("\t\"amount\": \"").append(amount).append("\""); + } + num = num + 1; + } + if (this.taxNo != null) { + if (num == 0) { + sb.append("\t\t\"taxNo\": \"").append(taxNo).append("\""); + } else { + sb.append(",\n").append("\t\"taxNo\": \"").append(taxNo).append("\""); + } + num = num + 1; + } + if (this.length != null) { + if (num == 0) { + sb.append("\t\t\"length\": \"").append(length).append("\""); + } else { + sb.append(",\n").append("\t\"length\": \"").append(length).append("\""); + } + num = num + 1; + } + if (this.width != null) { + if (num == 0) { + sb.append("\t\t\"width\": \"").append(width).append("\""); + } else { + sb.append(",\n").append("\t\"width\": \"").append(width).append("\""); + } + num = num + 1; + } + if (this.height != null) { + if (num == 0) { + sb.append("\t\t\"height\": \"").append(height).append("\""); + } else { + sb.append(",\n").append("\t\"height\": \"").append(height).append("\""); + } + num = num + 1; + } + if (this.volume != null) { + if (num == 0) { + sb.append("\t\t\"volume\": \"").append(volume).append("\""); + } else { + sb.append(",\n").append("\t\"volume\": \"").append(volume).append("\""); + } + num = num + 1; + } + if (this.cargoDeclaredValue != null) { + if (num == 0) { + sb.append("\t\t\"cargoDeclaredValue\": \"").append(cargoDeclaredValue).append("\""); + } else { + sb.append(",\n").append("\t\"cargoDeclaredValue\": \"").append(cargoDeclaredValue).append("\""); + } + num = num + 1; + } + if (this.declaredValueDeclaredCurrency != null) { + if (num == 0) { + sb.append("\t\t\"declaredValueDeclaredCurrency\": \"").append(declaredValueDeclaredCurrency).append("\""); + } else { + sb.append(",\n").append("\t\"declaredValueDeclaredCurrency\": \"").append(declaredValueDeclaredCurrency).append("\""); + } + num = num + 1; + } + sb.append("\n\t}"); + return sb.toString(); + }*/ +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/ConfirmOrder.java b/back-end_code/src/main/java/com/shop/entity/sf/ConfirmOrder.java new file mode 100644 index 0000000000000000000000000000000000000000..c68ce2b7311ff6e9a64776eef5f58278f130e2b1 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/ConfirmOrder.java @@ -0,0 +1,73 @@ +package com.shop.entity.sf; + +import com.shop.entity.Order; + +public class ConfirmOrder { + private String searchType; + private String orderId; + private String language = "zh-cn"; + + public ConfirmOrder() { + } + + public ConfirmOrder(Order order) { + this.orderId = order.getOrder_id().toString(); + this.searchType = "1"; + } + + public String getSearchType() { + return searchType; + } + + public void setSearchType(String searchType) { + this.searchType = searchType; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.searchType != null) { + if (num == 0) { + sb.append("\t\"searchType\": \"").append(searchType).append("\""); + } else { + sb.append(",\n").append("\t\"searchType\": \"").append(searchType).append("\""); + } + num = num + 1; + } + if (this.orderId != null) { + if (num == 0) { + sb.append("\t\"orderId\": \"").append(orderId).append("\""); + } else { + sb.append(",\n").append("\t\"orderId\": \"").append(orderId).append("\""); + } + num = num + 1; + } + if (this.language != null) { + if (num == 0) { + sb.append("\t\"language\": \"").append(language).append("\""); + } else { + sb.append(",\n").append("\t\"language\": \"").append(language).append("\""); + } + num = num + 1; + } + sb.append("\n}"); + return sb.toString(); + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/ContactInfo.java b/back-end_code/src/main/java/com/shop/entity/sf/ContactInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..160aab3bb65c650eb97eda69244155b5b764dd73 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/ContactInfo.java @@ -0,0 +1,308 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.ContactType; +import com.shop.entity.Address; + +import java.util.Iterator; + +public class ContactInfo { + private String contactType ; //地址类型:1,寄件方信息; 2,到件方信息 T-1 + private String company; //公司名称 C-100 + private String contact; //联系人 C-100 + private String tel; // 联系电话 C-20 + private String mobile; // 手机号码 N-20 + private String zoneCode; // 城市代码或国家代码,跨境件必填 C-30 + private String country; // 国家或地区 2 位代码 T-30 + private String province; // 所在省级行政区名称 F-30 + private String city; // 所在地级行政区名称 F-100 + private String county; // 所在县/区级行政区名称 F-30 + private String address; // 详细地址 T-200 + private String postCode; // 邮编,跨境件必填 C-25 + private String email; // 邮箱地址 F-200 + private String taxNo; // 税号 F-100 + + public ContactInfo() { + } + + public ContactInfo(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("contactType") != null) + this.contactType = jsonObject.getString("contactType"); + if (jsonObject.getString("company") != null) + this.company = jsonObject.getString("company"); + if (jsonObject.getString("contact") != null) + this.contact = jsonObject.getString("contact"); + if (jsonObject.getString("tel") != null) + this.tel = jsonObject.getString("tel"); + if (jsonObject.getString("mobile") != null) + this.mobile = jsonObject.getString("mobile"); + if (jsonObject.getString("zoneCode") != null) + this.zoneCode = jsonObject.getString("zoneCode"); + if (jsonObject.getString("country") != null) + this.country = jsonObject.getString("country"); + if (jsonObject.getString("province") != null) + this.province = jsonObject.getString("province"); + if (jsonObject.getString("city") != null) + this.city = jsonObject.getString("city"); + if (jsonObject.getString("county") != null) + this.county = jsonObject.getString("county"); + if (jsonObject.getString("address") != null) + this.address = jsonObject.getString("address"); + if (jsonObject.getString("postCode") != null) + this.postCode = jsonObject.getString("postCode"); + if (jsonObject.getString("email") != null) + this.email = jsonObject.getString("email"); + if (jsonObject.getString("taxNo") != null) + this.taxNo = jsonObject.getString("taxNo"); + } + + public ContactInfo(Address address, ContactType contactType){ + this.address = address.getRegion()+address.getDetail(); + this.mobile = address.getPhonenumber(); + this.contact = address.getRealname(); + this.contactType = ContactType.toInteger(contactType).toString(); + } + + public ContactInfo(ContactType contactType){ + if (contactType == ContactType.Seller){ + this.address = "浙江省杭州市钱塘区下沙高教园区学正街18号"; + this.mobile = "18888888888"; + this.contact = "阿格力"; + this.contactType = "1"; + } + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public String getTel() { + return tel; + } + + public void setTel(String tel) { + this.tel = tel; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getZoneCode() { + return zoneCode; + } + + public void setZoneCode(String zoneCode) { + this.zoneCode = zoneCode; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getCounty() { + return county; + } + + public void setCounty(String county) { + this.county = county; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getTaxNo() { + return taxNo; + } + + public void setTaxNo(String taxNo) { + this.taxNo = taxNo; + } + + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.contactType != null) { + if (num == 0) { + sb.append("\t\t\"contactType\": \"").append(contactType).append("\""); + } else { + sb.append(",\n").append("\t\t\"contactType\": \"").append(contactType).append("\""); + } + num = num + 1; + } + if (this.company != null) { + if (num == 0) { + sb.append("\t\t\"company\": \"").append(company).append("\""); + } else { + sb.append(",\n").append("\t\t\"company\": \"").append(company).append("\""); + } + num = num + 1; + } + if (this.contact != null) { + if (num == 0) { + sb.append("\t\t\"contact\": \"").append(contact).append("\""); + } else { + sb.append(",\n").append("\t\t\"contact\": \"").append(contact).append("\""); + } + num = num + 1; + } + if (this.tel != null) { + if (num == 0) { + sb.append("\t\t\"tel\": \"").append(tel).append("\""); + } else { + sb.append(",\n").append("\t\t\"tel\": \"").append(tel).append("\""); + } + num = num + 1; + } + if (this.mobile != null) { + if (num == 0) { + sb.append("\t\t\"mobile\": \"").append(mobile).append("\""); + } else { + sb.append(",\n").append("\t\t\"mobile\": \"").append(mobile).append("\""); + } + num = num + 1; + } + if (this.zoneCode != null) { + if (num == 0) { + sb.append("\t\t\"zoneCode\": \"").append(zoneCode).append("\""); + } else { + sb.append(",\n").append("\t\t\"zoneCode\": \"").append(zoneCode).append("\""); + } + num = num + 1; + } + if (this.country != null) { + if (num == 0) { + sb.append("\t\t\"country\": \"").append(country).append("\""); + } else { + sb.append(",\n").append("\t\t\"country\": \"").append(country).append("\""); + } + num = num + 1; + } + if (this.province != null) { + if (num == 0) { + sb.append("\t\t\"province\": \"").append(province).append("\""); + } else { + sb.append(",\n").append("\t\t\"province\": \"").append(province).append("\""); + } + num = num + 1; + } + if (this.city != null) { + if (num == 0) { + sb.append("\t\t\"city\": \"").append(city).append("\""); + } else { + sb.append(",\n").append("\t\t\"city\": \"").append(city).append("\""); + } + num = num + 1; + } + if (this.county != null) { + if (num == 0) { + sb.append("\t\t\"county\": \"").append(county).append("\""); + } else { + sb.append(",\n").append("\t\t\"county\": \"").append(county).append("\""); + } + num = num + 1; + } + if (this.address != null) { + if (num == 0) { + sb.append("\t\t\"address\": \"").append(address).append("\""); + } else { + sb.append(",\n").append("\t\t\"address\": \"").append(address).append("\""); + } + num = num + 1; + } + if (this.postCode != null) { + if (num == 0) { + sb.append("\t\t\"postCode\": \"").append(postCode).append("\""); + } else { + sb.append(",\n").append("\t\t\"postCode\": \"").append(postCode).append("\""); + } + num = num + 1; + } + if (this.email != null) { + if (num == 0) { + sb.append("\t\t\"email\": \"").append(email).append("\""); + } else { + sb.append(",\n").append("\t\t\"email\": \"").append(email).append("\""); + } + num = num + 1; + } + if (this.taxNo != null) { + if (num == 0) { + sb.append("\t\t\"taxNo\": \"").append(taxNo).append("\""); + } else { + sb.append(",\n").append("\t\t\"taxNo\": \"").append(taxNo).append("\""); + } + num = num + 1; + } + sb.append("\n\t}"); + return sb.toString(); + } + + +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/CreateOrder.java b/back-end_code/src/main/java/com/shop/entity/sf/CreateOrder.java new file mode 100644 index 0000000000000000000000000000000000000000..310f41c27417d4e99acad7ed9f3413d04300d352 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/CreateOrder.java @@ -0,0 +1,171 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; +import com.shop.Enum.ContactType; +import com.shop.entity.Order; +import com.shop.entity.OrderDetail; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CreateOrder { + private String language = "zh-CN"; + private String orderId; + private String parcelQty; + private String payMethod; + private List cargoDetails; + private List contactInfoList; + + public CreateOrder(Order order) { + this.orderId = order.getOrder_id().toString(); + this.parcelQty = "1"; + this.payMethod = "1"; + List cargoDetails = new ArrayList(); + List contactInfoList = new ArrayList(); + for (OrderDetail orderdetail:order.getOrderDetailList()) { + CargoDetail cargoDetail = new CargoDetail(orderdetail); + cargoDetails.add(cargoDetail); + } + this.cargoDetails = cargoDetails; + ContactInfo contactInfo = new ContactInfo(order.getAddress(), ContactType.Buyer); + contactInfoList.add(contactInfo); + contactInfo = new ContactInfo(ContactType.Seller); + contactInfoList.add(contactInfo); + this.contactInfoList = contactInfoList; + } + + public CreateOrder(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("language") != null) + this.language = jsonObject.getString("language"); + if (jsonObject.getString("orderId") != null) + this.orderId = jsonObject.getString("orderId"); + if (jsonObject.getString("parcelQty") != null) + this.parcelQty = jsonObject.getString("parcelQty"); + if (jsonObject.getString("payMethod") != null) + this.payMethod = jsonObject.getString("payMethod"); + if (jsonObject.getJSONArray("cargoDetails") != null) { + objectIterator = jsonObject.getJSONArray("cargoDetails").iterator(); + CargoDetail CargoDetail; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + CargoDetail = new CargoDetail(jb); + this.cargoDetails.add(CargoDetail); + } + } + if (jsonObject.getJSONArray("contactInfoList") != null) { + objectIterator = jsonObject.getJSONArray("contactInfoList").iterator(); + ContactInfo ContactInfo; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + ContactInfo = new ContactInfo(jb); + this.contactInfoList.add(ContactInfo); + } + } + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getParcelQty() { + return parcelQty; + } + + public void setParcelQty(String parcelQty) { + this.parcelQty = parcelQty; + } + + public String getPayMethod() { + return payMethod; + } + + public void setPayMethod(String payMethod) { + this.payMethod = payMethod; + } + + public List getCargoDetails() { + return cargoDetails; + } + + public void setCargoDetails(List cargoDetails) { + this.cargoDetails = cargoDetails; + } + + public List getContactInfoList() { + return contactInfoList; + } + + public void setContactInfoList(List contactInfoList) { + this.contactInfoList = contactInfoList; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.language != null) { + if (num == 0) { + sb.append("\t\"language\": \"").append(language).append("\""); + } else { + sb.append(",\n").append("\t\"language\": \"").append(language).append("\""); + } + num = num + 1; + } + if (this.orderId != null) { + if (num == 0) { + sb.append("\t\"orderId\": \"").append(orderId).append("\""); + } else { + sb.append(",\n").append("\t\"orderId\": \"").append(orderId).append("\""); + } + num = num + 1; + } + if (this.parcelQty != null) { + if (num == 0) { + sb.append("\t\"parcelQty\": \"").append(parcelQty).append("\""); + } else { + sb.append(",\n").append("\t\"parcelQty\": \"").append(parcelQty).append("\""); + } + num = num + 1; + } + if (this.payMethod != null) { + if (num == 0) { + sb.append("\t\"payMethod\": \"").append(payMethod).append("\""); + } else { + sb.append(",\n").append("\t\"payMethod\": \"").append(payMethod).append("\""); + } + num = num + 1; + } + if (this.cargoDetails != null) { + if (num == 0) { + sb.append("\t\"cargoDetails\": ").append(cargoDetails); + } else { + sb.append(",\n").append("\t\"cargoDetails\": ").append(cargoDetails); + } + num = num + 1; + } + if (this.contactInfoList != null) { + if (num == 0) { + sb.append("\t\"contactInfoList\": ").append(contactInfoList); + } else { + sb.append(",\n").append("\t\"contactInfoList\": ").append(contactInfoList); + } + num = num + 1; + } + sb.append("\n}"); + return sb.toString(); + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/ResultData.java b/back-end_code/src/main/java/com/shop/entity/sf/ResultData.java new file mode 100644 index 0000000000000000000000000000000000000000..d31ae7552935658248ed4d10b1f2f5c356cf595d --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/ResultData.java @@ -0,0 +1,56 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.util.Iterator; + +public class ResultData { + private String apiErrorMsg; + private String apiResponseID ; + private String apiResultCode ; + private ApiResultData apiResultData; + + public ResultData(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("apiErrorMsg") != null) + this.apiErrorMsg = jsonObject.getString("apiErrorMsg"); + if (jsonObject.getString("apiResponseID") != null) + this.apiResponseID = jsonObject.getString("apiResponseID"); + if (jsonObject.getString("apiResultCode") != null) + this.apiResultCode = jsonObject.getString("apiResultCode"); + if (jsonObject.getJSONObject("apiResultData") != null) + this.apiResultData = new ApiResultData(jsonObject.getJSONObject("apiResultData")); + } + + public String getApiErrorMsg() { + return apiErrorMsg; + } + + public void setApiErrorMsg(String apiErrorMsg) { + this.apiErrorMsg = apiErrorMsg; + } + + public String getApiResponseID() { + return apiResponseID; + } + + public void setApiResponseID(String apiResponseID) { + this.apiResponseID = apiResponseID; + } + + public String getApiResultCode() { + return apiResultCode; + } + + public void setApiResultCode(String apiResultCode) { + this.apiResultCode = apiResultCode; + } + + public ApiResultData getApiResultData() { + return apiResultData; + } + + public void setApiResultData(ApiResultData apiResultData) { + this.apiResultData = apiResultData; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/Route.java b/back-end_code/src/main/java/com/shop/entity/sf/Route.java new file mode 100644 index 0000000000000000000000000000000000000000..e694a473a3caa9a17208c30150aad39fadc86f11 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/Route.java @@ -0,0 +1,64 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.text.ParseException; +import java.util.Iterator; + +public class Route { + private String acceptTime; //路由节点发生的时间,格式:YYYY- MM-DD HH24:MM:SS,示例:2012-7-30 09:30:00 T + private String acceptAddress; // 路由节点发生的地点 F-100 + private String remark; // 路由节点具体描述 T-150 + private String opCode; // 路由节点操作码 T-50 + + public Route(JSONObject jsonObject) throws ParseException { + Iterator objectIterator; + if (jsonObject.getDate("acceptTime") != null) + this.acceptTime = jsonObject.getString("acceptTime"); + if (jsonObject.getString("acceptAddress") != null) + this.acceptAddress = jsonObject.getString("acceptAddress"); + if (jsonObject.getString("remark") != null) + this.remark = jsonObject.getString("remark"); + if (jsonObject.getString("opCode") != null) + this.opCode = jsonObject.getString("opCode"); + } + + public Route(String acceptTime, String acceptAddress, String remark, String opCode) { + this.acceptTime = acceptTime; + this.acceptAddress = acceptAddress; + this.remark = remark; + this.opCode = opCode; + } + + public String getAcceptTime() { + return acceptTime; + } + + public void setAcceptTime(String acceptTime) { + this.acceptTime = acceptTime; + } + + public String getAcceptAddress() { + return acceptAddress; + } + + public void setAcceptAddress(String acceptAddress) { + this.acceptAddress = acceptAddress; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getOpCode() { + return opCode; + } + + public void setOpCode(String opCode) { + this.opCode = opCode; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/RouteResp.java b/back-end_code/src/main/java/com/shop/entity/sf/RouteResp.java new file mode 100644 index 0000000000000000000000000000000000000000..8aea88fec09cb1440b4e167b919ceb9ea1df57e4 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/RouteResp.java @@ -0,0 +1,61 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class RouteResp { + private String mailNo; // 顺丰运单号 T-10 + private List routes = new ArrayList(); // 路由信息(列表) + private String orderId; // 客户订单号 T-10 + + public RouteResp(JSONObject jsonObject) throws ParseException { + Iterator objectIterator; + if (jsonObject.getString("mailNo") != null) + this.mailNo = jsonObject.getString("mailNo"); + if (jsonObject.getJSONArray("routes") != null) { + objectIterator = jsonObject.getJSONArray("routes").iterator(); + Route Route; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + Route = new Route(jb); + this.routes.add(Route); + } + } + if (jsonObject.getString("orderId") != null) + this.orderId = jsonObject.getString("orderId"); + } + + public RouteResp(String mailNo, List routes, String orderId) { + this.mailNo = mailNo; + this.routes = routes; + this.orderId = orderId; + } + + public String getMailNo() { + return mailNo; + } + + public void setMailNo(String mailNo) { + this.mailNo = mailNo; + } + + public List getRoutes() { + return routes; + } + + public void setRoutes(List routes) { + this.routes = routes; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/RoutesApiResultData.java b/back-end_code/src/main/java/com/shop/entity/sf/RoutesApiResultData.java new file mode 100644 index 0000000000000000000000000000000000000000..a9516fbeae7cb5939fa8003a6c22dbc95cdddc62 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/RoutesApiResultData.java @@ -0,0 +1,57 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.text.ParseException; +import java.util.Iterator; + +public class RoutesApiResultData { + private Boolean success; + private String errorCode; + private String errorMsg; + private RoutesmsgDate msgData; + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public RoutesmsgDate getMsgData() { + return msgData; + } + + public void setMsgData(RoutesmsgDate msgData) { + this.msgData = msgData; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public RoutesApiResultData(JSONObject jsonObject) throws ParseException { + Iterator objectIterator; + if (jsonObject.getBoolean("success") != null) + this.success = jsonObject.getBoolean("success"); + if (jsonObject.getString("errorCode") != null) + this.errorCode = jsonObject.getString("errorCode"); + if (jsonObject.getString("errorMsg") != null) + this.errorMsg = jsonObject.getString("errorMsg"); + if (jsonObject.getJSONObject("msgData") != null) + this.msgData = new RoutesmsgDate(jsonObject.getJSONObject("msgData")); + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/RoutesResultData.java b/back-end_code/src/main/java/com/shop/entity/sf/RoutesResultData.java new file mode 100644 index 0000000000000000000000000000000000000000..6200243eb184ccd3c7c91ee9c7af93d1aa7bb2e6 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/RoutesResultData.java @@ -0,0 +1,57 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.text.ParseException; +import java.util.Iterator; + +public class RoutesResultData { + private String apiErrorMsg; + private String apiResponseID ; + private String apiResultCode ; + private RoutesApiResultData apiResultData; + + public RoutesResultData(JSONObject jsonObject) throws ParseException { + Iterator objectIterator; + if (jsonObject.getString("apiErrorMsg") != null) + this.apiErrorMsg = jsonObject.getString("apiErrorMsg"); + if (jsonObject.getString("apiResponseID") != null) + this.apiResponseID = jsonObject.getString("apiResponseID"); + if (jsonObject.getString("apiResultCode") != null) + this.apiResultCode = jsonObject.getString("apiResultCode"); + if (jsonObject.getJSONObject("apiResultData") != null) + this.apiResultData = new RoutesApiResultData(jsonObject.getJSONObject("apiResultData")); + } + + public String getApiErrorMsg() { + return apiErrorMsg; + } + + public void setApiErrorMsg(String apiErrorMsg) { + this.apiErrorMsg = apiErrorMsg; + } + + public String getApiResponseID() { + return apiResponseID; + } + + public void setApiResponseID(String apiResponseID) { + this.apiResponseID = apiResponseID; + } + + public String getApiResultCode() { + return apiResultCode; + } + + public void setApiResultCode(String apiResultCode) { + this.apiResultCode = apiResultCode; + } + + public RoutesApiResultData getApiResultData() { + return apiResultData; + } + + public void setApiResultData(RoutesApiResultData apiResultData) { + this.apiResultData = apiResultData; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/RoutesmsgDate.java b/back-end_code/src/main/java/com/shop/entity/sf/RoutesmsgDate.java new file mode 100644 index 0000000000000000000000000000000000000000..25e03831e096acded9f0945405b60be5c082b8d7 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/RoutesmsgDate.java @@ -0,0 +1,40 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class RoutesmsgDate { + private List routeResps; + + public List getRouteResps() { + return routeResps; + } + + public void setRouteResps(List routeResps) { + this.routeResps = routeResps; + } + + public RoutesmsgDate(List routeResps) { + this.routeResps = routeResps; + } + + public RoutesmsgDate(JSONObject jsonObject) throws ParseException { + Iterator objectIterator; + List routeResps = new ArrayList(); + if (jsonObject.getJSONArray("routeResps") != null) { + objectIterator = jsonObject.getJSONArray("routeResps").iterator(); + RouteResp RouteResp; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + RouteResp = new RouteResp(jb); + routeResps.add(RouteResp); + } + } + this.routeResps = routeResps; + } + +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/SearchOrder.java b/back-end_code/src/main/java/com/shop/entity/sf/SearchOrder.java new file mode 100644 index 0000000000000000000000000000000000000000..da369bbbebb6749f2c6b68a25801153947c8a30d --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/SearchOrder.java @@ -0,0 +1,104 @@ +package com.shop.entity.sf; + +import java.util.ArrayList; +import java.util.List; + +public class SearchOrder { + private String language = "0"; + private String trackingType; + private List trackingNumber; + private String methodType = "1"; + + public SearchOrder(Long order_id) { + this.trackingType = "2"; + String track_number = "\"" + String.valueOf(order_id) + "\""; + List trackingNumber = new ArrayList(); + trackingNumber.add(track_number); + this.trackingNumber = trackingNumber; + } + public SearchOrder(String package_number) { + this.trackingType = "1"; + String track_number = "\"" + package_number + "\""; + List trackingNumber = new ArrayList(); + trackingNumber.add(track_number); + this.trackingNumber = trackingNumber; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getTrackingType() { + return trackingType; + } + + public void setTrackingType(String trackingType) { + this.trackingType = trackingType; + } + + public List getTrackingNumber() { + return trackingNumber; + } + + public void setTrackingNumber(List trackingNumber) { + this.trackingNumber = trackingNumber; + } + + public String getMethodType() { + return methodType; + } + + public void setMethodType(String methodType) { + this.methodType = methodType; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\n"); + int num = 0; + if (this.language != null) { + if (num == 0) { + sb.append("\t\"language\": \"").append(language).append("\""); + } else { + sb.append(",\n").append("\t\"language\": \"").append(language).append("\""); + } + num = num + 1; + } + if (this.trackingType != null) { + if (num == 0) { + sb.append("\t\"trackingType\": \"").append(trackingType).append("\""); + } else { + sb.append(",\n").append("\t\"trackingType\": \"").append(trackingType).append("\""); + } + num = num + 1; + } + if (this.trackingNumber != null) { + if (num == 0) { + sb.append("\t\"trackingNumber\": ").append(trackingNumber.toString()); + } else { + sb.append(",\n").append("\t\"trackingNumber\": ").append(trackingNumber.toString()); + } + num = num + 1; + } + if (this.methodType != null) { + if (num == 0) { + sb.append("\t\"methodType\": \"").append(methodType).append("\""); + } else { + sb.append(",\n").append("\t\"methodType\": \"").append(methodType).append("\""); + } + num = num + 1; + } + sb.append("\n}"); + return sb.toString(); + } +} +/*{ + "language": "0", + "trackingType": "1", + "trackingNumber": ["0SF7444434587815"], + "methodType": "1", + }*/ diff --git a/back-end_code/src/main/java/com/shop/entity/sf/WaybillNoInfo.java b/back-end_code/src/main/java/com/shop/entity/sf/WaybillNoInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..21f17c7077c0ddc21807d49c673ee9832ea378ff --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/WaybillNoInfo.java @@ -0,0 +1,38 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.util.Iterator; + +public class WaybillNoInfo { + private Integer waybillType; // 运单号类型1:母单;2:子单;3:签回单 T-1 + private String waybillNo; // 运单号 T-15 + + public WaybillNoInfo(JSONObject jsonObject) { + Iterator objectIterator; + this.waybillType = jsonObject.getInteger("waybillType"); + this.waybillNo = jsonObject.getString("waybillNo"); + } + + public WaybillNoInfo(Integer waybillType, String waybillNo) { + this.waybillType = waybillType; + this.waybillNo = waybillNo; + } + + + public Integer getWaybillType() { + return waybillType; + } + + public void setWaybillType(Integer waybillType) { + this.waybillType = waybillType; + } + + public String getWaybillNo() { + return waybillNo; + } + + public void setWaybillNo(String waybillNo) { + this.waybillNo = waybillNo; + } +} diff --git a/back-end_code/src/main/java/com/shop/entity/sf/msgDate.java b/back-end_code/src/main/java/com/shop/entity/sf/msgDate.java new file mode 100644 index 0000000000000000000000000000000000000000..ec7367208638fdfba348418f97ef7b2cafd9d318 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/entity/sf/msgDate.java @@ -0,0 +1,43 @@ +package com.shop.entity.sf; + +import com.alibaba.fastjson.JSONObject; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class msgDate { + private String orderId; // 客户订单号 T-10 + private List waybillNoInfoList = new ArrayList(); + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public List getWaybillNoInfoList() { + return waybillNoInfoList; + } + + public void setWaybillNoInfoList(List waybillNoInfoList) { + this.waybillNoInfoList = waybillNoInfoList; + } + + public msgDate(JSONObject jsonObject) { + Iterator objectIterator; + if (jsonObject.getString("orderId") != null) + this.orderId = jsonObject.getString("orderId"); + if (jsonObject.getJSONArray("waybillNoInfoList") != null) { + objectIterator = jsonObject.getJSONArray("waybillNoInfoList").iterator(); + WaybillNoInfo WaybillNoInfo; + while (objectIterator.hasNext()) { + JSONObject jb = (JSONObject) objectIterator.next(); + WaybillNoInfo = new WaybillNoInfo(jb); + this.waybillNoInfoList.add(WaybillNoInfo); + } + } + } +} diff --git a/back-end_code/src/main/java/com/shop/mapper/AddressMapper.java b/back-end_code/src/main/java/com/shop/mapper/AddressMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..5980b82c9ba15015dedfe3255785818f0177de81 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/mapper/AddressMapper.java @@ -0,0 +1,67 @@ +package com.shop.mapper; + +import com.shop.entity.Address; +import org.springframework.stereotype.Repository; + +import java.util.List; +@Repository +public interface AddressMapper { + + + /** + * 添加地址 + * @return + */ + int addAddress(Address address); + + /** + * 根据买家username查找地址 + * @param username + * @return + */ + List
searchUserAddress(String username); + + /** + * 查找买家默认地址 + * @param username + * @return + */ + Address searchUserSelectedAddress(String username); + + /** + *更新地址 + * @param address + * @return + */ + int updateAddress(Address address); + + /** + *删除地址 + * @param username + * @param address_id + * @return + */ + int deleteAddressByAddressId(String username,int address_id); + + /** + *根据AddressId修改Address为默认地址 + * @param address_id + * @param username + * @return + */ + int setSelected(int address_id,String username); + + /** + *根据username修改Address不为默认地址 + * @param username + * @return + */ + int setUnselected(String username); + + /** + *根据AddressId查询Address + * @param address_id + * @return + */ + Address searchAddressById(int address_id); +} diff --git a/back-end_code/src/main/java/com/shop/mapper/AftApplicationMapper.java b/back-end_code/src/main/java/com/shop/mapper/AftApplicationMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..ecb0fe24da626ba72fd41425f543386dd0aa1053 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/mapper/AftApplicationMapper.java @@ -0,0 +1,95 @@ +package com.shop.mapper; + +import com.shop.Enum.AftApplicationState; +import com.shop.Enum.AftApplicationType; +import com.shop.entity.AftApplication; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface AftApplicationMapper { + + + /** + * 提交申诉 + * @return + */ + int addAftApplication(AftApplication aftApplication); + + /** + * 根据买家aftApplication_buyerusername,aftApplication_type,aftApplication_state查找申诉 + * @param aftApplication_buyerusername + * @param aftApplication_type + * @param aftApplication_state + * @return + */ + List searchBuyerAftApplication(String aftApplication_buyerusername, AftApplicationType aftApplication_type, AftApplicationState aftApplication_state); + + /** + * 根据卖家aftApplication_sellerusername,aftApplication_type,aftApplication_state查找申诉 + * @param aftApplication_sellerusername + * @param aftApplication_type + * @param aftApplication_state + * @return + */ + List searchSellerAftApplication(String aftApplication_sellerusername, AftApplicationType aftApplication_type, AftApplicationState aftApplication_state); + + /** + * 根据AftApplicationId查询AftApplication + * @param aftApplication_id + * @return + */ + AftApplication searchAftApplicationById(Integer aftApplication_id); + + /** + * 根据order_id查询AftApplication是否存在 + * @param order_id + * @return + */ + AftApplication isAftApplicationById(Long order_id); + + /** + * 买家修改申诉 + * @param aftApplication + * @return + */ + int updateAftApplication(AftApplication aftApplication); + + /** + * 买家取消申诉 + * @param aftApplication + * @return + */ + int cancelAftApplication(AftApplication aftApplication); + + /** + * 卖家同意申诉 + * @param aftApplication + * @return + */ + int acceptAftApplication(AftApplication aftApplication); + + /** + * 卖家同意申诉回退 + * @param aftApplication + * @return + */ + int acceptAftApplicationBack(AftApplication aftApplication); + + /** + * 卖家拒绝申诉 + * @param aftApplication + * @return + */ + int refuseAftApplication(AftApplication aftApplication); + + /** + * 卖家拒绝申诉回退 + * @param aftApplication + * @return + */ + int refuseAftApplicationBack(AftApplication aftApplication); + + +} diff --git a/back-end_code/src/main/java/com/shop/mapper/GOMapper.java b/back-end_code/src/main/java/com/shop/mapper/GOMapper.java index 4805708f26500d3271ec6c4d552d81a444d827e2..3ca4602c05cf5e441a9fe774b7b4d49a4138b389 100644 --- a/back-end_code/src/main/java/com/shop/mapper/GOMapper.java +++ b/back-end_code/src/main/java/com/shop/mapper/GOMapper.java @@ -13,7 +13,7 @@ public interface GOMapper { * @param order_id * @return */ - int addGO(int item_id,int order_id); + int addGO(int item_id,Long order_id); /** * 根据item_id向GO表中查询信息 @@ -27,7 +27,7 @@ public interface GOMapper { * @param order_id * @return */ - GO searchGOByOrderId(int order_id); + GO searchGOByOrderId(Long order_id); /** * 根据item_id删除GO表中信息 @@ -41,5 +41,5 @@ public interface GOMapper { * @param order_id * @return */ - int deleteGOByOrderId(int order_id); + int deleteGOByOrderId(Long order_id); } diff --git a/back-end_code/src/main/java/com/shop/mapper/GoodsMapper.java b/back-end_code/src/main/java/com/shop/mapper/GoodsMapper.java index f6601725a2630668102c31a566c2399ee33c6be4..9c715a8f5b25d0c124a7dd07219c6454b48a036e 100644 --- a/back-end_code/src/main/java/com/shop/mapper/GoodsMapper.java +++ b/back-end_code/src/main/java/com/shop/mapper/GoodsMapper.java @@ -14,6 +14,15 @@ public interface GoodsMapper { */ int addGoods(Goods Goods); + /** + * 获取item_id(商品ID) + * @param goods_name + * @param goods_img + * @param goods_describe + * @return + */ + Goods getNewItem(String goods_name, String goods_img,String goods_describe); + /** * 根据item_id(商品ID)向Godds表中查询详细信息 * @param item_id diff --git a/back-end_code/src/main/java/com/shop/mapper/OrderDetailMapper.java b/back-end_code/src/main/java/com/shop/mapper/OrderDetailMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..2832751f93381f4bc384ce6c4b5380733ce8fc37 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/mapper/OrderDetailMapper.java @@ -0,0 +1,53 @@ +package com.shop.mapper; + +import com.shop.entity.OrderDetail; +import com.shop.entity.Snapshot; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface OrderDetailMapper { + + /** + * 添加订单明细 + * @return + */ + int addOrderDetail(OrderDetail orderDetail); + + /** + *删除订单明细 + * @param orderDetail_id + * @return + */ + Integer deleteOrderDetailByOrderDetailId(Integer orderDetail_id); + + /** + *更新订单明细 + * @param orderDetail + * @return + */ + Integer updateOrderDetail(OrderDetail orderDetail); + + /** + * 根据订单Id查找商品的全部订单明细 + * @param order_id + * @return + */ + List searchOrderDetailByOrderId(Long order_id); + + /** + * 根据订单Id查找商品的最新订单明细 + * @param order_id + * @return + */ + OrderDetail searchNewOrderDetailByOrderId(Long order_id); + + /** + *根据OrderDetailId查询OrderDetail + * @param detail_id + * @return + */ + OrderDetail searchOrderDetailByOrderDetailId(Integer detail_id); + +} diff --git a/back-end_code/src/main/java/com/shop/mapper/OrderMapper.java b/back-end_code/src/main/java/com/shop/mapper/OrderMapper.java index 7c76d8af2ac21b42f1988bb43b89a5b03bb98f9f..44ba6dcc51661e1948de4d8d0a45d00c0a56382c 100644 --- a/back-end_code/src/main/java/com/shop/mapper/OrderMapper.java +++ b/back-end_code/src/main/java/com/shop/mapper/OrderMapper.java @@ -11,232 +11,285 @@ import java.util.List; @Repository public interface OrderMapper { + /** - * 查看order表中商品号为item_number的买家列表 - * @param item_id + * 用户下单 + * @param order * @return */ - List searchBuyerlist(String seller_username,int item_id); + Integer addOrder(Order order); /** - * 查看order表中商品号为item_number且正在交易中的的订单信息 - * @param item_id + * 通过订单id查询订单 + * @param order_id * @return */ - Order searchFreezeGoodsBuyer(String seller_username,int item_id); + Order searchOrderByOrderId(Long order_id); /** - * 查看order表中商品意向买家名 + * 根据买家用户名查找所有订单 + * @param buyer_username * @param * @return */ - List searchSellingGoodsBuyerRealname(); + List buyerSearchHistoryOrders(String buyer_username); /** - * 同意意向买家 - * @param order_id + * 根据卖家用户名查找所有订单 + * @param seller_username * @return */ - int agreeOrderwanted(String seller_username,int order_id); + List sellerSearchHistoryOrders(String seller_username); /** - * 取消交易(恢复) - * @param order_id + * 买家查询待支付的订单 + * @param buyer_username * @return */ - int cancelOrder(String seller_username,int order_id); + List buyerSearchUnpaidOrder(String buyer_username); /** - * 通过订单id查询订单 + * 卖家查询待支付的订单 * @param seller_username + * @return + */ + List sellerSearchUnpaidOrder(String seller_username); + + /** + * 买家支付待支付的订单 * @param order_id * @return */ - Order searchOrderByOrderId(String seller_username,int order_id); + Integer buyerPayOrder(Long order_id); /** - * 查询完成订单 - * @param seller_username + * 买家查询待确认的订单 + * @param buyer_username * @return */ - List searchFinishOrder(String seller_username); + List buyerSearchUnconfirmedOrder(String buyer_username); + /** - * 按卖家查询所有订单 + * 卖家查询待确认的订单 * @param seller_username * @return */ - List searchOrdersBySellerUserName(String seller_username); + List sellerSearchUnconfirmedOrder(String seller_username); + /** - * 在Order表中查找已完成交易商品的历史意向买家 + * 卖家确认待确认的订单 * @param seller_username - * @param item_id + * @param order_id * @return */ - List searchHistoryGoodsUnFinishedOrder(String seller_username, int item_id); + Integer sellerConfirmOrder(String seller_username,Long order_id); /** - * 查询交易中订单 - * @param seller_username - * @param page + * 买家查询待备货的订单 + * @param buyer_username * @return */ - List searchDealingOrder(String seller_username,int page); + List buyerSearchUnpickedOrder(String buyer_username); /** - * 修改其余订单状态为关闭交易 + * 卖家查询待备货的订单 * @param seller_username - * @param item_id * @return */ - int updateOtherOrders(String seller_username,int item_id); - + List sellerSearchUnpickedOrder(String seller_username); /** - * 根据item_id(商品ID)有意向的购买者下单 - * @param order + * 卖家完成备货订单 + * @param order_id * @return */ - int addToOrderWanted(Order order); + Integer sellerPickOrder(String seller_username,Long order_id); /** - * 根据用户名查看历史购买记录 + * 买家查询待发货的订单 * @param buyer_username - * @param * @return */ - List searchFinishOrderByBuyerName(String buyer_username); + List buyerSearchUndeliveredOrder(String buyer_username); /** - * 买家下单 + * 卖家查询待发货的订单 + * @param seller_username + * @return + */ + List sellerSearchUndeliveredOrder(String seller_username); + + /** + * 买家修改待发货的订单收货人信息 * @param order * @return */ - int addOrder(Order order); + Integer buyerUpdateUndeliveredOrder(Order order); /** - * 买家查询待确认的订单 + * 卖家发货订单 + * @param order_id + * @return + */ + Integer sellerDeliverOrder(String seller_username,Long order_id); + + /** + * 买家查询待收货的订单 * @param buyer_username * @return */ - List buyerSearchUnconfirmedOrder(String buyer_username); + List buyerSearchUnarrivedOrder(String buyer_username); /** - * 卖家查询待确认的订单 + * 卖家查询待收货的订单 * @param seller_username * @return */ - List sellerSearchUnconfirmedOrder(String seller_username); + List sellerSearchUnarrivedOrder(String seller_username); /** - * 卖家确认待确认的订单 + * 买家根据order_id(订单ID)完成交易 * @param order_id + * @param buyer_username * @return */ - int confirmOrder(String seller_username,int order_id); + Integer buyerFinishOrder(String buyer_username,Long order_id,String finish_time); /** - * 买家查询待备货的订单 + * 买家查询已签收的订单 * @param buyer_username * @return */ - List buyerSearchUnpickOrder(String buyer_username); + List buyerSearchFinishOrder(String buyer_username); /** - * 卖家查询待备货的订单 + * 卖家查询已签收的订单 * @param seller_username * @return */ - List sellerSearchUnpickOrder(String seller_username); + List sellerSearchFinishOrder(String seller_username); /** - * 卖家完成备货订单 + * 买家根据order_id(订单ID)取消订单 + * @param buyer_username * @param order_id + * @param finish_time * @return */ - int pickOrder(String seller_username,int order_id); + Integer buyerCancelOrder(String buyer_username, Long order_id,String finish_time); /** - * 买家查询待发货的订单 - * @param buyer_username + * 卖家根据order_id(订单ID)取消订单 + * @param seller_username + * @param order_id + * @param finish_time * @return */ - List buyerSearchUndeliverOrder(String buyer_username); + Integer sellerCancelOrder(String seller_username, Long order_id,String finish_time); /** - * 买家修改待发货的订单收货人信息 - * @param order + * 买家查询已取消的订单 + * @param buyer_username * @return */ - int buyerUpdateUndeliverOrder(Order order); + List buyerSearchCancelOrder(String buyer_username); /** - * 卖家查询待发货的订单 + * 卖家查询已取消的订单 * @param seller_username * @return */ - List sellerSearchUndeliverOrder(String seller_username); + List sellerSearchCancelOrder(String seller_username); /** - * 卖家发货订单 + * 买家根据order_id(订单ID)申请订单售后 + * @param buyer_username * @param order_id * @return */ - int deliverOrder(String seller_username,int order_id); + Integer buyerSubmitAftApplication(String buyer_username, Long order_id); /** - * 卖家查询待收货的订单 - * @param seller_username + * 买家查询售后处理中的订单 + * @param buyer_username * @return */ - List sellerSearchUnfinishOrder(String seller_username); + List buyerSearchDealingOrder(String buyer_username); /** - * 买家根据order_id(订单ID)完成交易 - * @param order_id - * @param buyer_username + * 卖家查询售后处理中的订单 + * @param seller_username * @return */ - int finishOrder(String buyer_username,int order_id,String finish_time); + List sellerSearchDealingOrder(String seller_username); /** - * 卖家根据order_id(订单ID)取消订单 - * @param order_id + * 卖家根据order_id(订单ID)同意订单退款 * @param seller_username + * @param order_id * @return */ - int sellerCancelOrder(int order_id,String seller_username); + Integer sellerAcceptAftApplication(String seller_username, Long order_id,String finish_time); /** - * 买家根据order_id(订单ID)取消订单 + * 卖家根据order_id(订单ID)拒绝订单退款 + * @param seller_username * @param order_id - * @param buyer_username * @return */ - int buyerCancelOrder(int order_id,String buyer_username); + Integer sellerRefuseAftApplication(String seller_username, Long order_id,String finish_time); /** - * 买家查询未完成的订单 + * 买家查询售后处理的订单 * @param buyer_username * @return */ - List buyerSearchUnfinishOrder(String buyer_username); + List buyerSearchAfterOrder(String buyer_username); /** - * 买家查询已完成的订单 - * @param buyer_username + * 卖家查询售后处理的订单 + * @param seller_username * @return */ - List buyerSearchFinishOrder(String buyer_username); + List sellerSearchAfterOrder(String seller_username); /** - * 卖家查询已完成的订单 + * 卖家查询同意退款的订单 * @param seller_username * @return */ - List sellerSearchFinishOrder(String seller_username); + List sellerSearchAfterOkrOrder(String seller_username); + /** + * 卖家查询拒绝退款的订单 + * @param seller_username + * @return + */ + List sellerSearchAfterFailOrder(String seller_username); + /** + * 根据查找最新订单 + * @param order + * @return + */ + Order searchNewOrder(Order order); + /** + *根据OrderId设置Amount + * @param order_id + * @param seller_username + * @param buy_amount + * @return + */ + Integer setAmountByOrderId(Long order_id,String seller_username,Float buy_amount); + /** + *根据OrderId设置PackageNumber + * @param order_id + * @param seller_username + * @param package_number + * @return + */ + Integer setPackageNumberByOrderId(Long order_id,String seller_username,String package_number); } diff --git a/back-end_code/src/main/java/com/shop/mapper/SnapshotMapper.java b/back-end_code/src/main/java/com/shop/mapper/SnapshotMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..5ff56c29d7f3ec929d7c884e7359097522333c4e --- /dev/null +++ b/back-end_code/src/main/java/com/shop/mapper/SnapshotMapper.java @@ -0,0 +1,51 @@ +package com.shop.mapper; + +import com.shop.entity.Snapshot; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SnapshotMapper { + + /** + * 添加交易快照 + * @return + */ + int addSnapshot(Snapshot snapshot); + + /** + * 删除交易快照 + * @param snapshot_id + * @return + */ + Integer deleteSnapshotBySnapshotId(Integer snapshot_id); + + /** + * 更新交易快照 + * @param snapshot + * @return + */ + Integer updateSnapshot(Snapshot snapshot); + + /** + * 根据商品Id查找商品的全部交易快照 + * @param item_id + * @return + */ + List searchSnapshotByGoodId(Integer item_id); + + /** + * 根据商品Id查找商品的最新交易快照 + * @param item_id + * @return + */ + Snapshot searchNewSnapshotByGoodId(Integer item_id); + + /** + *根据SnapshotId查询Snapshot + * @param snapshot_id + * @return + */ + Snapshot searchSnapshotBySnapshotId(Integer snapshot_id); +} diff --git a/back-end_code/src/main/java/com/shop/service/AddressService.java b/back-end_code/src/main/java/com/shop/service/AddressService.java new file mode 100644 index 0000000000000000000000000000000000000000..035573ed6d7dfd261f02d745b0688d0527402096 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/AddressService.java @@ -0,0 +1,23 @@ +package com.shop.service; + +import com.shop.entity.Address; +import com.shop.mapper.AddressMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class AddressService { + @Autowired + private AddressMapper addressMapper; + + public int addAddress(Address address){return addressMapper.addAddress(address); } + public List
searchUserAddress(String username){ return addressMapper.searchUserAddress(username); } + public Address searchUserSelectedAddress(String username){ return addressMapper.searchUserSelectedAddress(username); } + public int updateAddress(Address address){return addressMapper.updateAddress(address);} + public int setSelected(int address_id,String username){return addressMapper.setSelected(address_id,username);} + public Address searchAddressById(int address_id){return addressMapper.searchAddressById(address_id);} + public int setUnselected(String username){return addressMapper.setUnselected(username);} + public int deleteAddressByAddressId(String username,int address_id){return addressMapper.deleteAddressByAddressId(username,address_id);} +} diff --git a/back-end_code/src/main/java/com/shop/service/AftApplicationService.java b/back-end_code/src/main/java/com/shop/service/AftApplicationService.java new file mode 100644 index 0000000000000000000000000000000000000000..9d05db4d66758d9a4928d4d2818c6a88c13829ca --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/AftApplicationService.java @@ -0,0 +1,31 @@ +package com.shop.service; + +import com.shop.Enum.AftApplicationState; +import com.shop.Enum.AftApplicationType; +import com.shop.entity.AftApplication; +import com.shop.mapper.AftApplicationMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class AftApplicationService { + @Autowired + private AftApplicationMapper aftApplicationMapper; + + public int addAftApplication(AftApplication aftApplication){return aftApplicationMapper.addAftApplication(aftApplication); } + public List searchBuyerAftApplication(String aftApplication_buyerusername, AftApplicationType aftApplication_type, AftApplicationState aftApplication_state){ + return aftApplicationMapper.searchBuyerAftApplication(aftApplication_buyerusername,aftApplication_type,aftApplication_state); } + public List searchSellerAftApplication(String aftApplication_sellerusername, AftApplicationType aftApplication_type, AftApplicationState aftApplication_state){ + return aftApplicationMapper.searchSellerAftApplication(aftApplication_sellerusername,aftApplication_type,aftApplication_state); } + public AftApplication searchAftApplicationById(Integer aftApplication_id){return aftApplicationMapper.searchAftApplicationById(aftApplication_id);} + public AftApplication isAftApplicationById(Long order_id){return aftApplicationMapper.isAftApplicationById(order_id);} + public int updateAftApplication(AftApplication aftApplication){return aftApplicationMapper.updateAftApplication(aftApplication);} + public int cancelAftApplication(AftApplication aftApplication){return aftApplicationMapper.cancelAftApplication(aftApplication);} + public int acceptAftApplication(AftApplication aftApplication){return aftApplicationMapper.acceptAftApplication(aftApplication);} + public int acceptAftApplicationBack(AftApplication aftApplication){return aftApplicationMapper.acceptAftApplication(aftApplication);} + public int refuseAftApplication(AftApplication aftApplication){return aftApplicationMapper.refuseAftApplication(aftApplication);} + public int refuseAftApplicationBack(AftApplication aftApplication){return aftApplicationMapper.refuseAftApplicationBack(aftApplication);} + +} diff --git a/back-end_code/src/main/java/com/shop/service/AlipayService.java b/back-end_code/src/main/java/com/shop/service/AlipayService.java new file mode 100644 index 0000000000000000000000000000000000000000..8f139ba1f7cc59a309132d1f69cf337ff361ef28 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/AlipayService.java @@ -0,0 +1,56 @@ +package com.shop.service; + +import com.alipay.api.AlipayApiException; + +/** + * 支付接口 + * @author lcc + * @data :2018年6月4日 上午10:18:39 + */ +public interface AlipayService { + + /** + * web端订单支付 + * @param outTradeNo 订单编号(唯一) + * @param totalAmount 订单价格 + * @param subject 商品名称 + */ + String webPagePay(String outTradeNo,Float totalAmount,String subject) throws Exception; + + /** + * app端订单支付 + * @param outTradeNo 订单编号 + * @param totalAmount 订单价格 + * @param subject 商品名称 + */ + String appPagePay(String outTradeNo,Integer totalAmount,String subject) throws Exception; + + /** + * 退款 + * @param outTradeNo 订单编号 + * @param refundReason 退款原因 + * @param refundAmount 退款金额 + * @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传 + */ + String refund(String outTradeNo,String refundReason,Integer refundAmount,String outRequestNo) throws AlipayApiException; + + /** + * 交易查询 + * @param outTradeNo 订单编号(唯一) + */ + String query(String outTradeNo) throws AlipayApiException; + + /** + * 交易关闭 + * @param outTradeNo 订单编号(唯一) + */ + String close(String outTradeNo) throws AlipayApiException; + + /** + * 退款查询 + * @param outTradeNo 订单编号(唯一) + * @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传 + */ + String refundQuery(String outTradeNo,String outRequestNo) throws AlipayApiException; +} + diff --git a/back-end_code/src/main/java/com/shop/service/AlipayServiceImpl.java b/back-end_code/src/main/java/com/shop/service/AlipayServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f00ff5d9543fc35c06bd27f67975fd08c88c8b65 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/AlipayServiceImpl.java @@ -0,0 +1,125 @@ +package com.shop.service; + +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.domain.AlipayTradeWapPayModel; +import com.alipay.api.request.*; +import com.shop.utils.AlipayConfig; +import org.springframework.stereotype.Service; + +/** + * 支付实现类 + * @author lcc + * @data :2018年6月4日 上午10:18:07 + */ +@Service("alipayService") +public class AlipayServiceImpl implements AlipayService { + + /** 调取支付宝接口 web端支付*/ + DefaultAlipayClient alipayClient = new DefaultAlipayClient( + AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type); + + /** 调取支付宝接口app端支付*/ + AlipayClient alipayClients = new DefaultAlipayClient( + AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type); + + + @Override + public String webPagePay(String outTradeNo, Float totalAmount, String subject) throws Exception { + + AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); + /** 同步通知,支付完成后,支付成功页面*/ + alipayRequest.setReturnUrl(AlipayConfig.return_url); + /** 异步通知,支付完成后,需要进行的异步处理*/ + alipayRequest.setNotifyUrl(AlipayConfig.notify_url); + + alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\"," + + "\"total_amount\":\""+ totalAmount +"\"," + + "\"subject\":\""+ subject +"\"," + + "\"body\":\"商品名称\"," + + "\"timeout_express\":\"90m\"," + + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); + + /**转换格式*/ + String result = alipayClient.pageExecute(alipayRequest).getBody().replace('\"','\'').replace('\n',' '); + return result; + } + + @Override + public String refund(String outTradeNo,String refundReason,Integer refundAmount,String outRequestNo) throws AlipayApiException { + AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest(); + + /** 调取接口*/ + alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\"," + + "\"refund_amount\":\""+ refundAmount +"\"," + + "\"refund_reason\":\""+ refundReason +"\"," + + "\"out_request_no\":\""+ outRequestNo +"\"}"); + String result = alipayClient.execute(alipayRequest).getBody(); + return result; + } + + @Override + public String query(String outTradeNo) throws AlipayApiException { + AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest(); + /**请求接口*/ + alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","+"\"trade_no\":\""+ "" +"\"}"); + /**转换格式*/ + String result = alipayClient.execute(alipayRequest).getBody(); + return result; + } + + @Override + public String close(String outTradeNo) throws AlipayApiException { + AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest(); + + alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\"," +"\"trade_no\":\""+ "" +"\"}"); + + String result = alipayClient.execute(alipayRequest).getBody(); + + return result; + } + + @Override + public String refundQuery(String outTradeNo , String outRequestNo) throws AlipayApiException { + AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest(); + + /** 请求接口*/ + alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\"," + +"\"out_request_no\":\""+ outRequestNo +"\"}"); + + /** 格式转换*/ + String result = alipayClient.execute(alipayRequest).getBody(); + + return result; + } + + @Override + public String appPagePay(String outTradeNo, Integer totalAmount, String subject) throws Exception { + AlipayTradeWapPayRequest alipayRequest=new AlipayTradeWapPayRequest(); + + /** 同步通知,支付完成后,支付成功页面*/ + alipayRequest.setReturnUrl(AlipayConfig.return_url); + /** 异步通知,支付完成后,需要进行的异步处理*/ + alipayRequest.setNotifyUrl(AlipayConfig.notify_url); + + /**销售产品码(固定)*/ + String productCode="QUICK_WAP_WAY"; + + /** 进行赋值 */ + AlipayTradeWapPayModel wapPayModel=new AlipayTradeWapPayModel(); + wapPayModel.setOutTradeNo(outTradeNo); + wapPayModel.setSubject(subject); + wapPayModel.setTotalAmount(totalAmount.toString()); + wapPayModel.setBody("商品名称"); + wapPayModel.setTimeoutExpress("2m"); + wapPayModel.setProductCode(productCode); + alipayRequest.setBizModel(wapPayModel); + + /** 格式转换*/ + String result = alipayClients.pageExecute(alipayRequest).getBody().replace('\"','\'').replace('\n',' '); + return result; + } + +} + diff --git a/back-end_code/src/main/java/com/shop/service/GOService.java b/back-end_code/src/main/java/com/shop/service/GOService.java index 2597dd755e80bb238dc4beac80b85a2af16c8dab..28e5c14c47e0d3cedda67d14ce09a2253dcdcb04 100644 --- a/back-end_code/src/main/java/com/shop/service/GOService.java +++ b/back-end_code/src/main/java/com/shop/service/GOService.java @@ -11,10 +11,10 @@ public class GOService { @Autowired private GOMapper GOMapper; - public int addGO(int item_id,int order_id){return GOMapper.addGO(item_id,order_id);} + public int addGO(int item_id,Long order_id){return GOMapper.addGO(item_id,order_id);} public GO searchGOByItemId(int item_id){return GOMapper.searchGOByItemId(item_id);} - public GO searchGOByOrderId(int order_id){return GOMapper.searchGOByOrderId(order_id);} + public GO searchGOByOrderId(Long order_id){return GOMapper.searchGOByOrderId(order_id);} public int deleteGOByItemId(int item_id){return GOMapper.deleteGOByItemId(item_id);} - public int deleteGOByOrderId(int order_id){return GOMapper.deleteGOByOrderId(order_id);} + public int deleteGOByOrderId(Long order_id){return GOMapper.deleteGOByOrderId(order_id);} } diff --git a/back-end_code/src/main/java/com/shop/service/GoodsService.java b/back-end_code/src/main/java/com/shop/service/GoodsService.java index ab792469d575357f5ce048d40bcfaa931f9d9d65..134dcdba3e6008ec1b3531b6b06241a0e551bf07 100644 --- a/back-end_code/src/main/java/com/shop/service/GoodsService.java +++ b/back-end_code/src/main/java/com/shop/service/GoodsService.java @@ -5,6 +5,7 @@ import com.shop.entity.Goods; import com.shop.mapper.CategoryMapper; import com.shop.mapper.GoodsMapper; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -20,6 +21,7 @@ public class GoodsService { public int addGoods(Goods Goods){ return goodsMapper.addGoods(Goods); } + public Goods getNewItem(String goods_name, String goods_img,String goods_describe){ return goodsMapper.getNewItem(goods_name,goods_img,goods_describe);} public Goods searchGoods(int item_id){ return goodsMapper.searchGoods(item_id); } public int updateGoodsState(String seller_username,int item_id,int new_state){return goodsMapper.updateGoodsState(seller_username,item_id, new_state);} public List searchSellingGoods(){return goodsMapper.searchSellingGoods();}//一页8条 diff --git a/back-end_code/src/main/java/com/shop/service/OrderDetailService.java b/back-end_code/src/main/java/com/shop/service/OrderDetailService.java new file mode 100644 index 0000000000000000000000000000000000000000..a508953b1f20fea16f0560735a18f2a6fec48a7e --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/OrderDetailService.java @@ -0,0 +1,31 @@ +package com.shop.service; + +import com.shop.entity.Goods; +import com.shop.entity.OrderDetail; +import com.shop.entity.Snapshot; +import com.shop.mapper.OrderDetailMapper; +import com.shop.mapper.SnapshotMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +@Service +public class OrderDetailService { + @Autowired + private OrderDetailMapper orderDetailMapper; + @Autowired + private SnapshotMapper snapshotMapper; + + public Integer addOrderDetail(Long order_id,Snapshot snapshot, Integer buy_stock){ + Float buy_sum = snapshot.getGoods_price() * buy_stock; + OrderDetail orderDetail = new OrderDetail(order_id,snapshot,buy_stock,buy_sum); + return orderDetailMapper.addOrderDetail(orderDetail); } + public Integer deleteOrderDetailByOrderDetailId(Integer orderDetail_id){return orderDetailMapper.deleteOrderDetailByOrderDetailId(orderDetail_id);} + public Integer updateOrderDetail(OrderDetail orderDetail){return orderDetailMapper.updateOrderDetail(orderDetail);} + public List searchOrderDetailByOrderId(Long order_id){ return orderDetailMapper.searchOrderDetailByOrderId(order_id); } + public OrderDetail searchNewOrderDetailByOrderId(Long order_id){ return orderDetailMapper.searchNewOrderDetailByOrderId(order_id); } + public OrderDetail searchOrderDetailByOrderDetailId(Integer orderDetail_id){return orderDetailMapper.searchOrderDetailByOrderDetailId(orderDetail_id);} +} diff --git a/back-end_code/src/main/java/com/shop/service/OrderService.java b/back-end_code/src/main/java/com/shop/service/OrderService.java index 15559993a36569ca03e69c9ee427509c352d49e1..089be4b606385bdf9aa03cea6a2e81e65c837dd9 100644 --- a/back-end_code/src/main/java/com/shop/service/OrderService.java +++ b/back-end_code/src/main/java/com/shop/service/OrderService.java @@ -1,15 +1,12 @@ package com.shop.service; -import com.shop.entity.Goods; import com.shop.entity.Order; -import com.shop.entity.User; -import com.shop.mapper.GoodsMapper; import com.shop.mapper.OrderMapper; +import com.sun.org.apache.xpath.internal.operations.Or; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Service; -import java.util.ArrayList; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @@ -18,19 +15,15 @@ public class OrderService { @Autowired private OrderMapper orderMapper; - @Autowired - private GoodsMapper goodsMapper; - @Autowired - private GoodsService goodsService; public static String hideCardNo(String str) { - int length = str.length(); - int beforeLength = 1; - int afterLength = 0; + Integer length = str.length(); + Integer beforeLength = 1; + Integer afterLength = 0; //替换字符串,当前使用“*” String replaceSymbol = "*"; StringBuffer sb = new StringBuffer(); - for(int i=0; i<4; i++) { + for(Integer i=0; i<4; i++) { if(i == 0) { sb.append(str.charAt(i)); } else { @@ -40,65 +33,42 @@ public class OrderService { return sb.toString(); } - public List searchBuyerlist(String seller_username,int item_id){ return orderMapper.searchBuyerlist(seller_username,item_id);} - public Order searchFreezeGoodsBuyer(String seller_username,int item_id){ return orderMapper.searchFreezeGoodsBuyer(seller_username,item_id);} - public Order agreeOrderwanted(String seller_username,int order_id){ - int result = orderMapper.agreeOrderwanted(seller_username,order_id); - Order order = orderMapper.searchOrderByOrderId(seller_username,order_id); - Goods good = goodsMapper.searchGoods(order.getItem_id()); - int new_stock = good.getGoods_stock()-order.getBuy_sum(); - goodsMapper.updateGoodStock(order.getItem_id(),new_stock); - if (new_stock == 0){ - goodsMapper.updateGoodsState(order.getSeller_username(),order.getItem_id(),3); - } - return order; - } - public List searchSellingGoodsBuyerRealname(){ - List Strings = new ArrayList<>(); - List orderList = orderMapper.searchSellingGoodsBuyerRealname(); - String str; - for (int i=0;i searchHistoryGoodsUnFinishedOrder(String seller_username,int item_id){ - return orderMapper.searchHistoryGoodsUnFinishedOrder(seller_username,item_id); - } - public Order searchOrderByOrderId(String seller_username,int order_id){return orderMapper.searchOrderByOrderId(seller_username,order_id);} - public List searchFinishOrder(String seller_username){return orderMapper.searchFinishOrder(seller_username);} - public List searchDealingOrder(String seller_username,int page){return orderMapper.searchDealingOrder(seller_username,page);} - public int cancelOrder(String seller_username,int order_id){ - int result = orderMapper.cancelOrder(seller_username,order_id); - Order order = orderMapper.searchOrderByOrderId(seller_username,order_id); - Goods good = goodsMapper.searchGoods(order.getItem_id()); - int new_stock = good.getGoods_stock()+order.getBuy_sum(); - goodsMapper.updateGoodStock(good.getItem_id(),new_stock); - if (good.getGoods_stock() == 0){ - goodsMapper.updateGoodsState(seller_username,order_id,1); - } - return result; - } - public int addToOrderWanted(Order order){return orderMapper.addToOrderWanted(order); } - public List searchFinishOrderByBuyerName(String buyer_username){return orderMapper.searchFinishOrderByBuyerName(buyer_username);} - public List searchOrdersBySellerName(String seller_username){return orderMapper.searchOrdersBySellerUserName(seller_username);} - public int addOrder(Order order){return orderMapper.addOrder(order);} + public Integer addOrder(Order order){return orderMapper.addOrder(order);} + public Order searchOrderByOrderId(Long order_id){return orderMapper.searchOrderByOrderId(order_id);} + public List buyerSearchHistoryOrders(String buyer_username){return orderMapper.buyerSearchHistoryOrders(buyer_username);} + public List sellerSearchHistoryOrders(String seller_username){return orderMapper.sellerSearchHistoryOrders(seller_username);} + public List sellerSearchUnpaidOrder(String seller_username){return orderMapper.sellerSearchUnpaidOrder(seller_username);} + public List buyerSearchUnpaidOrder(String buyer_username){return orderMapper.buyerSearchUnpaidOrder(buyer_username);} + public int buyerPayOrder(Long order_id){ return orderMapper.buyerPayOrder(order_id);} + public Integer sellerConfirmOrder(String seller_username,Long order_id){return orderMapper.sellerConfirmOrder(seller_username,order_id);} public List buyerSearchUnconfirmedOrder(String buyer_username){return orderMapper.buyerSearchUnconfirmedOrder(buyer_username);} public List sellerSearchUnconfirmedOrder(String seller_username){return orderMapper.sellerSearchUnconfirmedOrder(seller_username);} - public int confirmOrder(String seller_username,int order_id){return orderMapper.confirmOrder(seller_username,order_id);} - public List buyerSearchUnpickOrder(String buyer_username){return orderMapper.buyerSearchUnpickOrder(buyer_username);} - public List sellerSearchUnpickOrder(String seller_username){return orderMapper.sellerSearchUnpickOrder(seller_username);} - public int pickOrder(String seller_username,int order_id){return orderMapper.pickOrder(seller_username,order_id);} - public List buyerSearchUndeliverOrder(String buyer_username){return orderMapper.buyerSearchUndeliverOrder(buyer_username);} - public int buyerUpdateUndeliverOrder(Order order){return orderMapper.buyerUpdateUndeliverOrder(order);} - public List sellerSearchUndeliverOrder(String seller_username){return orderMapper.sellerSearchUndeliverOrder(seller_username);} - public int deliverOrder(String seller_username,int order_id){return orderMapper.deliverOrder(seller_username,order_id);} - public List sellerSearchUnfinishOrder(String seller_username){return orderMapper.sellerSearchUnfinishOrder(seller_username);} - public int finishOrder(String buyer_username,int order_id,String finish_time){ return orderMapper.finishOrder(buyer_username,order_id,finish_time); } - public int sellerCancelOrder(int order_id,String seller_username){return orderMapper.sellerCancelOrder(order_id,seller_username);} - public int buyerCancelOrder(int order_id,String buyer_username){return orderMapper.buyerCancelOrder(order_id,buyer_username);} - public List buyerSearchUnfinishOrder(String buyer_username){return orderMapper.buyerSearchUnfinishOrder(buyer_username);} + public List buyerSearchUnpickedOrder(String buyer_username){return orderMapper.buyerSearchUnpickedOrder(buyer_username);} + public List sellerSearchUnpickedOrder(String seller_username){return orderMapper.sellerSearchUnpickedOrder(seller_username);} + public Integer sellerPickOrder(String seller_username,Long order_id){return orderMapper.sellerPickOrder(seller_username,order_id);} + public List buyerSearchUndeliveredOrder(String buyer_username){return orderMapper.buyerSearchUndeliveredOrder(buyer_username);} + public List sellerSearchUndeliveredOrder(String seller_username){return orderMapper.sellerSearchUndeliveredOrder(seller_username);} + public Integer buyerUpdateUndeliveredOrder(Order order){return orderMapper.buyerUpdateUndeliveredOrder(order);} + public Integer sellerDeliverOrder(String seller_username,Long order_id){return orderMapper.sellerDeliverOrder(seller_username,order_id);} + public List buyerSearchUnarrivedOrder(String buyer_username){return orderMapper.buyerSearchUnarrivedOrder(buyer_username);} + public List sellerSearchUnarrivedOrder(String seller_username){return orderMapper.sellerSearchUnarrivedOrder(seller_username);} + public Integer buyerFinishOrder(String buyer_username,Long order_id,String finish_time){ return orderMapper.buyerFinishOrder(buyer_username,order_id,finish_time); } public List buyerSearchFinishOrder(String buyer_username){return orderMapper.buyerSearchFinishOrder(buyer_username);} public List sellerSearchFinishOrder(String seller_username){return orderMapper.sellerSearchFinishOrder(seller_username);} - + public Integer buyerCancelOrder(String buyer_username,Long order_id,String finish_time){return orderMapper.buyerCancelOrder(buyer_username,order_id,finish_time);} + public Integer sellerCancelOrder(String seller_username,Long order_id,String finish_time){return orderMapper.sellerCancelOrder(seller_username,order_id,finish_time);} + public List buyerSearchCancelOrder(String buyer_username){return orderMapper.buyerSearchCancelOrder(buyer_username);} + public List sellerSearchCancelOrder(String seller_username){return orderMapper.sellerSearchCancelOrder(seller_username);} + public Integer buyerSubmitAftApplication(String buyer_username, Long order_id){ return orderMapper.buyerSubmitAftApplication(buyer_username, order_id);}; + public List buyerSearchDealingOrder(String buyer_username){return orderMapper.buyerSearchDealingOrder(buyer_username);} + public List sellerSearchDealingOrder(String seller_username){ return orderMapper.sellerSearchDealingOrder(seller_username);} + public Integer sellerAcceptAftApplication(String seller_username, Long order_id){ return orderMapper.sellerAcceptAftApplication(seller_username, order_id,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));}; + public Integer sellerRefuseAftApplication(String seller_username, Long order_id){ return orderMapper.sellerRefuseAftApplication(seller_username, order_id,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));}; + public List buyerSearchAfterOrder(String buyer_username){return orderMapper.buyerSearchAfterOrder(buyer_username);} + public List sellerSearchAfterOrder(String seller_username){ return orderMapper.sellerSearchAfterOrder(seller_username);} + public List sellerSearchAfterOkrOrder(String seller_username){ return orderMapper.sellerSearchAfterOkrOrder(seller_username);} + public List sellerSearchAfterFailOrder(String seller_username){ return orderMapper.sellerSearchAfterFailOrder(seller_username);} + public Order searchNewOrder(Order order){ return orderMapper.searchNewOrder(order); } + public Integer setAmountByOrderId(Long order_id,String seller_username,Float buy_amount){ return orderMapper.setAmountByOrderId(order_id,seller_username,buy_amount);} + public Integer setPackageNumberByOrderId(Long order_id,String seller_username,String package_number){ return orderMapper.setPackageNumberByOrderId(order_id,seller_username,package_number);} } diff --git a/back-end_code/src/main/java/com/shop/service/RedisService.java b/back-end_code/src/main/java/com/shop/service/RedisService.java new file mode 100644 index 0000000000000000000000000000000000000000..fe02dc5e6b45362cd0a45d1988146f553be0f2da --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/RedisService.java @@ -0,0 +1,36 @@ +package com.shop.service; + +/** + * redis操作Service, + * 对象和数组都以json形式进行存储 + * Created by macro on 2018/8/7. + */ +public interface RedisService { + /** + * 存储数据 + */ + void set(String key, String value); + + /** + * 获取数据 + */ + String get(String key); + + /** + * 设置超期时间 + */ + boolean expire(String key, long expire); + + /** + * 删除数据 + */ + void remove(String key); + + /** + * 自增操作 + * @param delta 自增步长 + */ + Long increment(String key, long delta); + +} + diff --git a/back-end_code/src/main/java/com/shop/service/SFService.java b/back-end_code/src/main/java/com/shop/service/SFService.java new file mode 100644 index 0000000000000000000000000000000000000000..f41aa5c7fe4b9aeb4f4113ea964db1e39aef37d4 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/SFService.java @@ -0,0 +1,68 @@ +package com.shop.service; + +import com.alibaba.fastjson.JSONObject; +import com.sf.csim.express.service.CallExpressServiceTools; +import com.sf.csim.express.service.HttpClientUtil; +import com.shop.entity.Order; +import com.shop.entity.sf.*; +import org.springframework.stereotype.Service; + +import java.io.UnsupportedEncodingException; +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@Service +public class SFService { + private static final String CLIENT_CODE = "WXY66kyI8b"; //丰桥平台顾客编码 + private static final String CHECK_WORD = "KGTNUaXkdvedc4UkYGAk6ZEnwgD4JD98";//丰桥平台校验码 + private static final String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service"; //沙箱环境的地址 -PRO + private static final String CALL_URL_PROD = "https://sfapi.sf-express.com/std/service"; //生产环境的地址 -PRO + private CallExpressServiceTools tools=CallExpressServiceTools.getInstance(); + private String timeStamp ; + private Map params = new HashMap(); + public SFService() { + params.put("partnerID", CLIENT_CODE); // 顾客编码 ,对应丰桥上获取的clientCode + params.put("requestID", UUID.randomUUID().toString().replace("-", "")); + } + public JSONObject tool(String classname, String msgData) throws UnsupportedEncodingException { + timeStamp = String.valueOf(System.currentTimeMillis()); + params.put("serviceCode",classname); + params.put("timestamp", timeStamp); + params.put("msgData", msgData); + params.put("msgDigest", tools.getMsgDigest(msgData,timeStamp,CHECK_WORD)); + System.out.println("===调用实际请求=" + params); + String result = HttpClientUtil.post(CALL_URL_BOX, params); + System.out.println("===调用地址 ==="+CALL_URL_BOX); + System.out.println("===顾客编码 ==="+CLIENT_CODE); + System.out.println("===返回结果:" +result); + JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result); + return jsonObject; + } + public Object EXP_RECE_CREATE_ORDER(Order order) throws UnsupportedEncodingException { + String request = new CreateOrder(order).toString(); + JSONObject temp = SFService.this.tool(Thread.currentThread().getStackTrace()[1].getMethodName(),request); + return new ResultData(temp); + } + public Object EXP_RECE_SEARCH_ORDER_RESP(Order order) throws UnsupportedEncodingException { + String request = new ConfirmOrder(order).toString(); + JSONObject temp = SFService.this.tool(Thread.currentThread().getStackTrace()[1].getMethodName(),request); + return new ResultData(temp); + } + public Object EXP_RECE_SEARCH_ROUTES(String package_number) throws UnsupportedEncodingException, ParseException { + String request = new SearchOrder(package_number).toString(); + JSONObject temp = SFService.this.tool(Thread.currentThread().getStackTrace()[1].getMethodName(),request); + return new RoutesResultData(temp); + } + public Object EXP_RECE_SEARCH_ROUTES(Long order_id) throws UnsupportedEncodingException, ParseException { + String request = new SearchOrder(order_id).toString(); + JSONObject temp = SFService.this.tool(Thread.currentThread().getStackTrace()[1].getMethodName(),request); + return new RoutesResultData(temp); + } + public Object EXP_RECE_UPDATE_ORDER(String msgData) throws UnsupportedEncodingException { + return SFService.this.tool(Thread.currentThread().getStackTrace()[1].getMethodName(),msgData); + } + + +} diff --git a/back-end_code/src/main/java/com/shop/service/SnapshotService.java b/back-end_code/src/main/java/com/shop/service/SnapshotService.java new file mode 100644 index 0000000000000000000000000000000000000000..bcc318811df3166047e37f3b8400e893b1bdbd2a --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/SnapshotService.java @@ -0,0 +1,27 @@ +package com.shop.service; + +import com.shop.entity.Goods; +import com.shop.entity.Snapshot; +import com.shop.mapper.SnapshotMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +@Service +public class SnapshotService { + @Autowired + private SnapshotMapper snapshotMapper; + + public Integer addSnapshot(Goods goods){ + Snapshot snapshot = new Snapshot(goods); + snapshot.setSnapshot_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + return snapshotMapper.addSnapshot(snapshot); } + public Integer deleteSnapshotBySnapshotId(Integer snapshot_id){return snapshotMapper.deleteSnapshotBySnapshotId(snapshot_id);} + public Integer updateSnapshot(Snapshot snapshot){return snapshotMapper.updateSnapshot(snapshot);} + public List searchSnapshotByGoodId(Integer item_id){ return snapshotMapper.searchSnapshotByGoodId(item_id); } + public Snapshot searchNewSnapshotByGoodId(Integer item_id){ return snapshotMapper.searchNewSnapshotByGoodId(item_id); } + public Snapshot searchSnapshotBySnapshotId(Integer snapshot_id){return snapshotMapper.searchSnapshotBySnapshotId(snapshot_id);} +} diff --git a/back-end_code/src/main/java/com/shop/service/UnionPaymentService.java b/back-end_code/src/main/java/com/shop/service/UnionPaymentService.java new file mode 100644 index 0000000000000000000000000000000000000000..f2a4b34acbfb04b68ad97dbb3f4fdec79134d43b --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/UnionPaymentService.java @@ -0,0 +1,53 @@ +package com.shop.service; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public interface UnionPaymentService { + + + /** + * 支付 + * @param request + * @param response + */ + void pay(HttpServletRequest request, HttpServletResponse response) throws IOException; + + /** + * 后台回调 + * @param request + * @param response + */ + void backRcvResponse(HttpServletRequest request, HttpServletResponse response) throws IOException; + + /** + * 前台回调 + * @param request + * @param response + * @throws IOException + */ + void frontRcvResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; + + /** + * 交易状态查询 + * @param request + * @param response + */ + void query(HttpServletRequest request, HttpServletResponse response) throws IOException; + + /** + * 支付成功后的跳转 + * @param request + * @param response + */ + void successRedict(HttpServletRequest request, HttpServletResponse response) throws IOException; + + /** + * 检查支付结果 + * @param shopOrderId + * @throws IOException + */ + void check(Long shopOrderId); +} \ No newline at end of file diff --git a/back-end_code/src/main/java/com/shop/service/UnionPaymentServiceImpl.java b/back-end_code/src/main/java/com/shop/service/UnionPaymentServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..81e0faf5dcc503243ef712c3051aa43244e3f1d7 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/UnionPaymentServiceImpl.java @@ -0,0 +1,490 @@ +package com.shop.service; + +import com.shop.union.DemoBase; +import com.shop.union.config.SDKConfig; +import com.shop.union.constants.SDKConstants; +import com.shop.union.service.AcpService; +import com.shop.union.util.CertUtil; +import com.shop.union.util.LogUtil; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * Created by gangsun on 2017/4/12. + */ +@Service +public class UnionPaymentServiceImpl implements com.shop.service.UnionPaymentService { + + @Autowired + OrderService orderService; + @PostConstruct + public void init(){ + System.out.println("银联支付初始化"); + SDKConfig.getConfig().loadPropertiesFromSrc(); //从classpath加载acp_sdk.properties文件 + CertUtil.init(); + } + + //先取商户号 + //private String merId = "777290058110048"; + private String merId = "777290058197286"; + + private String redictUrl = "http://www.baidu.com"; + + + /** + * 支付 + * @param request + * @param response + */ + @Override + public void pay(HttpServletRequest request, HttpServletResponse response) throws IOException { + + request.setCharacterEncoding(DemoBase.encoding); + response.setContentType("text/html; charset="+ DemoBase.encoding); + + //String orderId = String.valueOf(System.currentTimeMillis()); //实际上是orderSn + String orderId = request.getParameter("id"); + String txnAmt = null; //订单金额 + String txnTime = null; //订单发送时间 + //交易金额,单位分,不要带小数点 + String price =request.getParameter("price"); + BigDecimal amount = new BigDecimal(price); + amount = amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP); + txnAmt = amount.toString(); + + //订单发送时间用于查询用 + Date sendPaymentDate = new Date(); + txnTime = formatTime(sendPaymentDate); + + Map requestData = new HashMap<>(); + + /***银联全渠道系统,产品参数,除了encoding自行选择外其他不需修改***/ + requestData.put("version", DemoBase.version); //版本号,全渠道默认值 + requestData.put("encoding", DemoBase.encoding); //字符集编码,可以使用UTF-8,GBK两种方式 + requestData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法 + requestData.put("txnType", "01"); //交易类型 ,01:消费 + requestData.put("txnSubType", "01"); //交易子类型, 01:自助消费 + requestData.put("bizType", "000201"); //业务类型,B2C网关支付,手机wap支付 + requestData.put("channelType", "08"); //渠道类型,这个字段区分B2C网关支付和手机wap支付;07:PC,平板 08:手机 + + /***商户接入参数***/ + requestData.put("merId", merId); //商户号码,请改成自己申请的正式商户号或者open上注册得来的777测试商户号 + requestData.put("accessType", "0"); //接入类型,0:直连商户 + requestData.put("orderId", orderId); //商户订单号,8-40位数字字母,不能含“-”或“_”,可以自行定制规则 + requestData.put("txnTime", txnTime); //订单发送时间,取系统时间,格式为YYYYMMDDhhmmss,必须取当前时间,否则会报txnTime无效 + requestData.put("currencyCode", "156"); //交易币种(境内商户一般是156 人民币) + requestData.put("txnAmt", txnAmt); //交易金额,单位分,不要带小数点 + //requestData.put("reqReserved", "透传字段"); //请求方保留域,如需使用请启用即可;透传字段(可以实现商户自定义参数的追踪)本交易的后台通知,对本交易的交易状态查询交易、对账文件中均会原样返回,商户可以按需上传,长度为1-1024个字节。出现&={}[]符号时可能导致查询接口应答报文解析失败,建议尽量只传字母数字并使用|分割,或者可以最外层做一次base64编码(base64编码之后出现的等号不会导致解析失败可以不用管)。 + + //前台通知地址 (需设置为外网能访问 http https均可),支付成功后的页面 点击“返回商户”按钮的时候将异步通知报文post到该地址 + //如果想要实现过几秒中自动跳转回商户页面权限,需联系银联业务申请开通自动返回商户权限 + //异步通知参数详见open.unionpay.com帮助中心 下载 产品接口规范 网关支付产品接口规范 消费交易 商户通知 + requestData.put("frontUrl", DemoBase.frontUrl); + + //后台通知地址(需设置为【外网】能访问 http https均可),支付成功后银联会自动将异步通知报文post到商户上送的该地址,失败的交易银联不会发送后台通知 + //后台通知参数详见open.unionpay.com帮助中心 下载 产品接口规范 网关支付产品接口规范 消费交易 商户通知 + //注意:1.需设置为外网能访问,否则收不到通知 2.http https均可 3.收单后台通知后需要10秒内返回http200或302状态码 + // 4.如果银联通知服务器发送通知后10秒内未收到返回状态码或者应答码非http200,那么银联会间隔一段时间再次发送。总共发送5次,每次的间隔时间为0,1,2,4分钟。 + // 5.后台通知地址如果上送了带有?的参数,例如:http://abc/web?a=b&c=d 在后台通知处理程序验证签名之前需要编写逻辑将这些字段去掉再验签,否则将会验签失败 + requestData.put("backUrl", DemoBase.backUrl); + + // 订单超时时间。 + // 超过此时间后,除网银交易外,其他交易银联系统会拒绝受理,提示超时。 跳转银行网银交易如果超时后交易成功,会自动退款,大约5个工作日金额返还到持卡人账户。 + // 此时间建议取支付时的北京时间加15分钟。 + // 超过超时时间调查询接口应答origRespCode不是A6或者00的就可以判断为失败。 + requestData.put("payTimeout", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime() + 15 * 60 * 1000)); + + ////////////////////////////////////////////////// + // + // 报文中特殊用法请查看 PCwap网关跳转支付特殊用法.txt + // + ////////////////////////////////////////////////// + + /**请求参数设置完毕,以下对请求参数进行签名并生成html表单,将表单写入浏览器跳转打开银联页面**/ + Map submitFromData = AcpService.sign(requestData,DemoBase.encoding); //报文中certId,signature的值是在signData方法中获取并自动赋值的,只要证书配置正确即可。 + + String requestFrontUrl = SDKConfig.getConfig().getFrontRequestUrl(); //获取请求银联的前台地址:对应属性文件acp_sdk.properties文件中的acpsdk.frontTransUrl + String html = AcpService.createAutoFormHtml(requestFrontUrl, submitFromData,DemoBase.encoding); //生成自动跳转的Html表单 + + LogUtil.writeLog("打印请求HTML,此为请求报文,为联调排查问题的依据:"+html); + //将生成的html写到浏览器中完成自动跳转打开银联支付页面;这里调用signData之后,将html写到浏览器跳转到银联页面之前均不能对html中的表单项的名称和值进行修改,如果修改会导致验签不通过 + response.getWriter().write(html); + + + } + + /** + * 后台回调 + * @param request + * @param response + */ + @Override + public void backRcvResponse(HttpServletRequest request, HttpServletResponse response) throws IOException { + LogUtil.writeLog("BackRcvResponse接收后台通知开始"); + + String encoding = request.getParameter(SDKConstants.param_encoding); + // 获取银联通知服务器发送的后台通知参数 + Map reqParam = getAllRequestParam(request); + + LogUtil.printRequestLog(reqParam); + + Map valideData = null; + if (null != reqParam && !reqParam.isEmpty()) { + Iterator> it = reqParam.entrySet().iterator(); + valideData = new HashMap(reqParam.size()); + while (it.hasNext()) { + Map.Entry e = it.next(); + String key = (String) e.getKey(); + String value = (String) e.getValue(); + value = new String(value.getBytes(encoding), encoding); + valideData.put(key, value); + } + } + + //重要!验证签名前不要修改reqParam中的键值对的内容,否则会验签不过 + if (!AcpService.validate(valideData, encoding)) { + LogUtil.writeLog("验证签名结果[失败]."); + //验签失败,需解决验签问题 + + } else { + LogUtil.writeLog("验证签名结果[成功]."); + //【注:为了安全验签成功才应该写商户的成功处理逻辑】交易成功,更新商户订单状态 + + String orderId =valideData.get("orderId"); //获取后台通知的数据,其他字段也可用类似方式获取 + String orderSn =orderId; //orderId其实存的是Sn + + String respCode = valideData.get("respCode"); + String txnAmt = valideData.get("txnAmt"); + BigDecimal txnAmount = (new BigDecimal(txnAmt)).multiply(new BigDecimal(0.01)); + + String queryId = valideData.get("queryId"); + String traceTime = valideData.get("traceTime"); + String payCardNo = valideData.get("payCardNo"); + String payCardType = valideData.get("payCardType"); //支付卡类型 + String paymentMethodMethod; //PayPaymentMethod里面的method字段 + if(StringUtils.isEmpty(payCardType)){ + paymentMethodMethod = "UNION"; //对之前代码做兼容,如果没有支付卡类型的情况走默认 + }else{ + paymentMethodMethod = "UNION-" + payCardType; + } + + //判断respCode=00、A6后,对涉及资金类的交易,请再发起查询接口查询,确定交易成功后更新数据库。 + if("00".equals(respCode)){ // 00 交易成功 + orderService.buyerPayOrder(Long.valueOf(orderId)); + //todo 若交易成功 + }else if("A6".equals(respCode)){ // A6 部分成功 + + } + + } + LogUtil.writeLog("BackRcvResponse接收后台通知结束"); + //返回给银联服务器http 200 状态码 + response.getWriter().print("ok"); + } + + @Override + public void frontRcvResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + LogUtil.writeLog("FrontRcvResponse前台接收报文返回开始"); + System.out.println("走到frontRcvResponse了"); + + String encoding = request.getParameter(SDKConstants.param_encoding); + LogUtil.writeLog("返回报文中encoding=[" + encoding + "]"); + String pageResult = ""; + if (DemoBase.encoding.equalsIgnoreCase(encoding)) { + pageResult = "/utf8_result.jsp"; + } else { + pageResult = "/gbk_result.jsp"; + } + Map respParam = getAllRequestParam(request); + + // 打印请求报文 + LogUtil.printRequestLog(respParam); + + Map valideData = null; + StringBuffer page = new StringBuffer(); + if (null != respParam && !respParam.isEmpty()) { + Iterator> it = respParam.entrySet() + .iterator(); + valideData = new HashMap(respParam.size()); + while (it.hasNext()) { + Map.Entry e = it.next(); + String key = (String) e.getKey(); + String value = (String) e.getValue(); + value = new String(value.getBytes(encoding), encoding); + page.append("" + key + + "(" + key + ")" + value + ""); + valideData.put(key, value); + } + } + if (!AcpService.validate(valideData, encoding)) { + page.append("验证签名结果失败"); + LogUtil.writeLog("验证签名结果[失败]."); + } else { + page.append("验证签名结果成功"); + LogUtil.writeLog("验证签名结果[成功]."); + System.out.println(valideData.get("orderId")); //其他字段也可用类似方式获取 + + String respCode = valideData.get("respCode"); + //判断respCode=00、A6后,对涉及资金类的交易,请再发起查询接口查询,确定交易成功后更新数据库。 + } + request.setAttribute("result", page.toString()); + request.getRequestDispatcher(pageResult).forward(request, response); + + LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束"); + + } + + @Override + public void query(HttpServletRequest request, HttpServletResponse response) throws IOException { + + String orderId = String.valueOf(System.currentTimeMillis()); //实际上是orderSn + String txnTime = null; //订单发送时间 + + //订单发送时间 + Map data = new HashMap(); + + /***银联全渠道系统,产品参数,除了encoding自行选择外其他不需修改***/ + data.put("version", DemoBase.version); //版本号 + data.put("encoding", DemoBase.encoding); //字符集编码 可以使用UTF-8,GBK两种方式 + data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法 + data.put("txnType", "00"); //交易类型 00-默认 + data.put("txnSubType", "00"); //交易子类型 默认00 + data.put("bizType", "000201"); //业务类型 B2C网关支付,手机wap支付 + + /***商户接入参数***/ + data.put("merId", merId); //商户号码,请改成自己申请的商户号或者open上注册得来的777商户号测试 + data.put("accessType", "0"); //接入类型,商户接入固定填0,不需修改 + + /***要调通交易以下字段必须修改***/ + data.put("orderId", orderId); //****商户订单号,每次发交易测试需修改为被查询的交易的订单号 + data.put("txnTime", txnTime); //****订单发送时间,每次发交易测试需修改为被查询的交易的订单发送时间 + + /**请求参数设置完毕,以下对请求参数进行签名并发送http post请求,接收同步应答报文------------->**/ + + Map reqData = AcpService.sign(data,DemoBase.encoding);//报文中certId,signature的值是在signData方法中获取并自动赋值的,只要证书配置正确即可。 + + String url = SDKConfig.getConfig().getSingleQueryUrl();// 交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.singleQueryUrl + //这里调用signData之后,调用submitUrl之前不能对submitFromData中的键值对做任何修改,如果修改会导致验签不通过 + Map rspData = AcpService.post(reqData,url,DemoBase.encoding); + + /**对应答码的处理,请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/ + //应答码规范参考open.unionpay.com帮助中心 下载 产品接口规范 《平台接入接口规范-第5部分-附录》 + if(!rspData.isEmpty()){ + if(AcpService.validate(rspData, DemoBase.encoding)){ + LogUtil.writeLog("验证签名成功"); + if("00".equals(rspData.get("respCode"))){//如果查询交易成功 + //处理被查询交易的应答码逻辑 + String origRespCode = rspData.get("origRespCode"); + if("00".equals(origRespCode)){ + //交易成功,更新商户订单状态 + //TODO + }else if("03".equals(origRespCode) || + "04".equals(origRespCode) || + "05".equals(origRespCode)){ + //需再次发起交易状态查询交易 + //TODO + }else{ + //其他应答码为失败请排查原因 + //TODO + } + }else{//查询交易本身失败,或者未查到原交易,检查查询交易报文要素 + //TODO + } + }else{ + LogUtil.writeErrorLog("验证签名失败"); + //TODO 检查验证签名失败的原因 + } + }else{ + //未返回正确的http状态 + LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200"); + } + String reqMessage = DemoBase.genHtmlResult(reqData); + String rspMessage = DemoBase.genHtmlResult(rspData); + response.getWriter().write("
请求报文:
"+reqMessage+"
" + "应答报文:
"+rspMessage+""); + + } + + @Override + public void check(Long shopOrderId){ + + String orderId = String.valueOf(System.currentTimeMillis()); //实际上是orderSn + String txnTime = null; //订单发送时间 + + Map data = new HashMap(); + + /***银联全渠道系统,产品参数,除了encoding自行选择外其他不需修改***/ + data.put("version", DemoBase.version); //版本号 + data.put("encoding", DemoBase.encoding); //字符集编码 可以使用UTF-8,GBK两种方式 + data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法 + data.put("txnType", "00"); //交易类型 00-默认 + data.put("txnSubType", "00"); //交易子类型 默认00 + data.put("bizType", "000201"); //业务类型 B2C网关支付,手机wap支付 + + /***商户接入参数***/ + data.put("merId", merId); //商户号码,请改成自己申请的商户号或者open上注册得来的777商户号测试 + data.put("accessType", "0"); //接入类型,商户接入固定填0,不需修改 + + /***要调通交易以下字段必须修改***/ + data.put("orderId", orderId); //****商户订单号,每次发交易测试需修改为被查询的交易的订单号 + data.put("txnTime", txnTime); //****订单发送时间,每次发交易测试需修改为被查询的交易的订单发送时间 + + /**请求参数设置完毕,以下对请求参数进行签名并发送http post请求,接收同步应答报文------------->**/ + + Map reqData = AcpService.sign(data,DemoBase.encoding);//报文中certId,signature的值是在signData方法中获取并自动赋值的,只要证书配置正确即可。 + LogUtil.writeLog("查询请求数据: " + reqData.toString()); + + String url = SDKConfig.getConfig().getSingleQueryUrl();// 交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.singleQueryUrl + //这里调用signData之后,调用submitUrl之前不能对submitFromData中的键值对做任何修改,如果修改会导致验签不通过 + Map rspData = AcpService.post(reqData,url,DemoBase.encoding); + LogUtil.writeLog("查询响应数据: " + rspData.toString()); + + /**对应答码的处理,请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/ + //应答码规范参考open.unionpay.com帮助中心 下载 产品接口规范 《平台接入接口规范-第5部分-附录》 + if(!rspData.isEmpty()){ + if(AcpService.validate(rspData, DemoBase.encoding)){ + LogUtil.writeLog("验证签名成功"); + if("00".equals(rspData.get("respCode"))){//如果查询交易成功 + //处理被查询交易的应答码逻辑 + String origRespCode = rspData.get("origRespCode"); + if("00".equals(origRespCode)){ + //交易成功,更新商户订单状态 + String txnAmt = rspData.get("txnAmt"); + BigDecimal txnAmount = null; + if(!StringUtils.isEmpty(txnAmt)){ + txnAmount = (new BigDecimal(txnAmt)).multiply(new BigDecimal(0.01)); //分转换为元; + } + String queryId = rspData.get("queryId"); + String traceTime = rspData.get("traceTime"); + String payCardNo = rspData.get("payCardNo"); + String payCardType = rspData.get("payCardType"); //支付卡类型 + String paymentMethodMethod; //PayPaymentMethod里面的method字段 + if(StringUtils.isEmpty(payCardType)){ + paymentMethodMethod = "UNION"; //对之前代码做兼容,如果没有支付卡类型的情况走默认 + }else{ + paymentMethodMethod = "UNION-" + payCardType; + } + + //更改支付状态 + + //改变工单状态 + }else if("03".equals(origRespCode) || + "04".equals(origRespCode) || + "05".equals(origRespCode)){ + //需再次发起交易状态查询交易 + throw new RuntimeException("查询结果:订单号" + orderId + "交易失败,应答码为“" + origRespCode + "”"); + }else{ + //其他应答码为失败请排查原因 + throw new RuntimeException("查询结果:订单号" + orderId + "交易失败,应答码为“" + origRespCode + "”"); + } + }else{//查询交易本身失败,或者未查到原交易,检查查询交易报文要素 + throw new RuntimeException("查询失败"); + } + }else{ + LogUtil.writeErrorLog("验证签名失败"); + throw new RuntimeException("验证签名失败"); + //TODO 检查验证签名失败的原因 + } + }else{ + //未返回正确的http状态 + LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200"); + throw new RuntimeException("未获取到返回报文或返回http状态码非200"); + } + + } + + @Override + public void successRedict(HttpServletRequest request, HttpServletResponse response) throws IOException { + //response.sendRedirect(redictUrl); + try { + System.out.println("走到successRedict了"); + request.getRequestDispatcher(redictUrl).forward(request,response); + } catch (ServletException e) { + e.printStackTrace(); + } + } + + + //---------------------------------------------------- private ----------------------------------------------------- + + /** + * 获取请求参数中所有的信息 + * + * @param request + * @return + */ + private static Map getAllRequestParam(final HttpServletRequest request) { + Map res = new HashMap(); + Enumeration temp = request.getParameterNames(); + if (null != temp) { + while (temp.hasMoreElements()) { + String en = (String) temp.nextElement(); + String value = request.getParameter(en); + res.put(en, value); + //在报文上送时,如果字段的值为空,则不上送<下面的处理为在获取所有参数数据时,判断若值为空,则删除这个字段> + //System.out.println("ServletUtil类247行 temp数据的键=="+en+" 值==="+value); + if (null == res.get(en) || "".equals(res.get(en))) { + res.remove(en); + } + } + } + return res; + } + + + + //收费比率 精确到分保留两位小数四舍五入 + private BigDecimal getFeeAmount(BigDecimal amount, BigDecimal feeRatio, BigDecimal feeMax) { + BigDecimal fee = new BigDecimal(0); + if(null == amount || null == feeRatio) return fee; + //金额乘以费率 = 手续费 + fee = amount.multiply(feeRatio); + //最大值为feeMax + if(null != feeMax && feeMax.compareTo(new BigDecimal("0")) >= 0) fee = fee.max(feeMax); + //设置精确到分并四舍五入 + fee = fee.setScale(4, BigDecimal.ROUND_HALF_UP); + return fee; + } + + /** + * 时间格式化 + * @param date + * @return + */ + private static String formatTime(Date date){ + return new SimpleDateFormat("yyyyMMddHHmmss").format(date); + } + private static Date formatTime(String dateStr){ + if(null == dateStr) return null; + if(dateStr.length() == 14){ + try { + return new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + }else{ + try { + return new SimpleDateFormat("MMddHHmmss").parse(dateStr); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + + } + + } + + +} diff --git a/back-end_code/src/main/java/com/shop/service/UserService.java b/back-end_code/src/main/java/com/shop/service/UserService.java index 4909617fef31430d68ed2982b78f3c0825fe0eb6..31afb33f3508d6a8d0f87de1d287b882c9e98c34 100644 --- a/back-end_code/src/main/java/com/shop/service/UserService.java +++ b/back-end_code/src/main/java/com/shop/service/UserService.java @@ -23,11 +23,8 @@ public class UserService { public User getUserInfo(String username){ return userMapper.getUserInfo(username); } public int updatePassword(String username,String newPassword){ return userMapper.updatePassword(username,newPassword); } public int registerUser(User user){ - String username=user.getUserName(); + String username=user.getUsername(); String password=user.getPassword(); - String realName=user.getRealname(); - String phoneNumber=user.getPhonenumber(); - String address=user.getAddress(); final String STR_ENG_PATTERN="^[a-z0-9A-Z]+$"; if(username.length()>11||username.length()<3){ return -1;//用户名长度错误 @@ -37,12 +34,6 @@ public class UserService { return -3;//用户名包含非数字或字母 }else if(password.length()<7||password.length()>15){ return -4;//密码长度错误 - }else if(realName.length()>10){ - return -5;//真实姓名长度过长 - }else if(phoneNumber.length()!=11||!phoneNumber.matches("^[0-9]+$")){ - return -6;//电话号码格式错误 - }else if(address.length()>50){ - return -7;//地址过长 } user.setPassword(JasyptUtil.encryptPwd("xiebo",user.getPassword())); return userMapper.registerUser(user); diff --git a/back-end_code/src/main/java/com/shop/service/impl/RedisServiceImpl.java b/back-end_code/src/main/java/com/shop/service/impl/RedisServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..483481971941ee9826c36c233f09b2108437bffe --- /dev/null +++ b/back-end_code/src/main/java/com/shop/service/impl/RedisServiceImpl.java @@ -0,0 +1,43 @@ +package com.shop.service.impl; + +import com.shop.service.RedisService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.TimeUnit; + +/** + * redis操作Service的实现类 + * Created by macro on 2018/8/7. + */ +@Service +public class RedisServiceImpl implements RedisService { + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Override + public void set(String key, String value) { + stringRedisTemplate.opsForValue().set(key, value); + } + + @Override + public String get(String key) { + return stringRedisTemplate.opsForValue().get(key); + } + + @Override + public boolean expire(String key, long expire) { + return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + + @Override + public void remove(String key) { + stringRedisTemplate.delete(key); + } + + @Override + public Long increment(String key, long delta) { + return stringRedisTemplate.opsForValue().increment(key,delta); + } +} diff --git a/back-end_code/src/main/java/com/shop/sflib/SF-CSIM.jar b/back-end_code/src/main/java/com/shop/sflib/SF-CSIM.jar new file mode 100644 index 0000000000000000000000000000000000000000..f7028c964988e89d7e569f6507933c38548b5ada Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/SF-CSIM.jar differ diff --git a/back-end_code/src/main/java/com/shop/sflib/commons-codec-1.9.jar b/back-end_code/src/main/java/com/shop/sflib/commons-codec-1.9.jar new file mode 100644 index 0000000000000000000000000000000000000000..ef35f1c50d7c41278bc31f4b9fcfc8fbd708d55d Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/commons-codec-1.9.jar differ diff --git a/back-end_code/src/main/java/com/shop/sflib/commons-logging-1.2.jar b/back-end_code/src/main/java/com/shop/sflib/commons-logging-1.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..93a3b9f6db406c84e270e19b9a5e70f2e27ca513 Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/commons-logging-1.2.jar differ diff --git a/back-end_code/src/main/java/com/shop/sflib/httpclient-4.3.4.jar b/back-end_code/src/main/java/com/shop/sflib/httpclient-4.3.4.jar new file mode 100644 index 0000000000000000000000000000000000000000..f8a7afebb93ee28eb3bc09176175225884e3b5c8 Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/httpclient-4.3.4.jar differ diff --git a/back-end_code/src/main/java/com/shop/sflib/httpcore-4.3.2.jar b/back-end_code/src/main/java/com/shop/sflib/httpcore-4.3.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..813ec234859e5c97798519c7a0fd221c1a79150e Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/httpcore-4.3.2.jar differ diff --git a/back-end_code/src/main/java/com/shop/sflib/slf4j-api-1.7.7.jar b/back-end_code/src/main/java/com/shop/sflib/slf4j-api-1.7.7.jar new file mode 100644 index 0000000000000000000000000000000000000000..bebabd961960a011786715026cb86f85df00fe3e Binary files /dev/null and b/back-end_code/src/main/java/com/shop/sflib/slf4j-api-1.7.7.jar differ diff --git a/back-end_code/src/main/java/com/shop/token/TokenService.java b/back-end_code/src/main/java/com/shop/token/TokenService.java index be249d6074a9c660f57102d5e87a08ce4177c4de..0ba20e6b3b79d1398e8c2de322510549d0182850 100644 --- a/back-end_code/src/main/java/com/shop/token/TokenService.java +++ b/back-end_code/src/main/java/com/shop/token/TokenService.java @@ -24,8 +24,8 @@ public class TokenService { token = JWT.create() // .withHeader(header) //存储自己想要留存给客户端浏览器的内容 - .withAudience(user.getUserName()) - .withClaim("username",user.getUserName()) + .withAudience(user.getUsername()) + .withClaim("username",user.getUsername()) .withIssuedAt(start) .withExpiresAt(expiresAt) .sign(Algorithm.HMAC256(user.getPassword())); diff --git a/back-end_code/src/main/java/com/shop/union/DemoBase.java b/back-end_code/src/main/java/com/shop/union/DemoBase.java new file mode 100644 index 0000000000000000000000000000000000000000..7b6775da144e1057d2f0424075e93e07e88bf169 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/DemoBase.java @@ -0,0 +1,211 @@ +package com.shop.union; + + +import com.shop.union.config.SDKConfig; +import com.shop.union.constants.SDKConstants; + +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + + +/** + * 名称: demo中用到的方法
+ * 日期: 2015-09
+ * 版本: 1.0.0 + * 版权: 中国银联
+ * 说明:以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己需要,按照技术文档编写。该代码仅供参考。
+ */ +public class DemoBase { + + //默认配置的是UTF-8 + public static String encoding = "UTF-8"; + + //全渠道固定值 + public static String version = SDKConfig.getConfig().getVersion(); + + //后台服务对应的写法参照 FrontRcvResponse.java + public static String frontUrl = SDKConfig.getConfig().getFrontUrl(); + + //后台服务对应的写法参照 BackRcvResponse.java + public static String backUrl = SDKConfig.getConfig().getBackUrl();//受理方和发卡方自选填写的域[O]--后台通知地址 + + // 商户发送交易时间 格式:YYYYMMDDhhmmss + public static String getCurrentTime() { + return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); + } + + // AN8..40 商户订单号,不能含"-"或"_" + public static String getOrderId() { + return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); + } + + /** + * 组装请求,返回报文字符串用于显示 + * @param data + * @return + */ + public static String genHtmlResult(Map data){ + + TreeMap tree = new TreeMap(); + Iterator> it = data.entrySet().iterator(); + while (it.hasNext()) { + Entry en = it.next(); + tree.put(en.getKey(), en.getValue()); + } + it = tree.entrySet().iterator(); + StringBuffer sf = new StringBuffer(); + while (it.hasNext()) { + Entry en = it.next(); + String key = en.getKey(); + String value = en.getValue(); + if("respCode".equals(key)){ + sf.append(""+key + SDKConstants.EQUAL + value+"
"); + }else + sf.append(key + SDKConstants.EQUAL + value+"
"); + } + return sf.toString(); + } + /** + * 功能:解析全渠道商户对账文件中的ZM文件并以List方式返回 + * 适用交易:对账文件下载后对文件的查看 + * @param filePath ZM文件全路径 + * @return 包含每一笔交易中 序列号 和 值 的map序列 + */ + public static List parseZMFile(String filePath){ + int lengthArray[] = {3,11,11,6,10,19,12,4,2,21,2,32,2,6,10,13,13,4,15,2,2,6,2,4,32,1,21,15,1,15,32,13,13,8,32,13,13,12,2,1,32,98}; + return parseFile(filePath,lengthArray); + } + + /** + * 功能:解析全渠道商户对账文件中的ZME文件并以List方式返回 + * 适用交易:对账文件下载后对文件的查看 + * @param filePath ZME文件全路径 + * @return 包含每一笔交易中 序列号 和 值 的map序列 + */ + public static List parseZMEFile(String filePath){ + int lengthArray[] = {3,11,11,6,10,19,12,4,2,2,6,10,4,12,13,13,15,15,1,12,2,135}; + return parseFile(filePath,lengthArray); + } + + /** + * 功能:解析全渠道商户 ZM,ZME对账文件 + * @param filePath + * @param lengthArray 参照《全渠道平台接入接口规范 第3部分 文件接口》 全渠道商户对账文件 6.1 ZM文件和6.2 ZME 文件 格式的类型长度组成int型数组 + * @return + */ + private static List parseFile(String filePath,int lengthArray[]){ + List ZmDataList = new ArrayList(); + try { + String encoding="UTF-8"; + File file=new File(filePath); + if(file.isFile() && file.exists()){ //判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file),encoding);//考虑到编码格式 + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + while((lineTxt = bufferedReader.readLine()) != null){ + //解析的结果MAP,key为对账文件列序号,value为解析的值 + Map ZmDataMap = new LinkedHashMap(); + //左侧游标 + int leftIndex = 0; + //右侧游标 + int rightIndex = 0; + for(int i=0;i dataList,String file){ + StringBuffer tableSb = new StringBuffer("对账文件的规范参考 https://open.unionpay.com/ajweb/help/file/ 产品接口规范->平台接口规范:文件接口
文件【"+file + "】解析后内容如下:"); + tableSb.append(""); + if(dataList.size() > 0){ + Map dataMapTmp = dataList.get(0); + tableSb.append(""); + for(Iterator it = dataMapTmp.keySet().iterator();it.hasNext();){ + Integer key = it.next(); + String value = dataMapTmp.get(key); + System.out.println("序号:"+ (key+1) + " 值: '"+ value +"'"); + tableSb.append(""); + } + tableSb.append(""); + } + + for(int i=0;i dataMapTmp = dataList.get(i); + tableSb.append(""); + for(Iterator it = dataMapTmp.keySet().iterator();it.hasNext();){ + Integer key = it.next(); + String value = dataMapTmp.get(key); + System.out.println("序号:"+ (key+1) + " 值: '"+ value +"'"); + tableSb.append(""); + } + tableSb.append(""); + } + tableSb.append("
序号"+(key+1)+"
"+value+"
"); + return tableSb.toString(); + } + + + public static List unzip(String zipFilePath,String outPutDirectory){ + List fileList = new ArrayList(); + try { + ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFilePath));//输入源zip路径 + BufferedInputStream bin = new BufferedInputStream(zin); + BufferedOutputStream bout = null; + File file=null; + ZipEntry entry; + try { + while((entry = zin.getNextEntry())!=null && !entry.isDirectory()){ + file = new File(outPutDirectory,entry.getName()); + if(!file.exists()){ + (new File(file.getParent())).mkdirs(); + } + bout = new BufferedOutputStream(new FileOutputStream(file)); + int b; + while((b=bin.read())!=-1){ + bout.write(b); + } + bout.flush(); + fileList.add(file.getAbsolutePath()); + System.out.println(file+"解压成功"); + } + } catch (IOException e) { + e.printStackTrace(); + }finally{ + try { + bin.close(); + zin.close(); + if(bout!=null){ + bout.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + return fileList; + } + +} \ No newline at end of file diff --git a/back-end_code/src/main/java/com/shop/union/config/SDKConfig.java b/back-end_code/src/main/java/com/shop/union/config/SDKConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..9ae9da770aa9f1b3c90bf7376cd8ea0524b92d20 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/config/SDKConfig.java @@ -0,0 +1,728 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 MPI基本参数工具类 + * ============================================================================= + */ +package com.shop.union.config; + +import com.shop.union.constants.SDKConstants; +import com.shop.union.util.LogUtil; +import com.shop.union.util.SDKUtil; +import org.apache.commons.lang.StringUtils; + +import java.io.*; +import java.util.Properties; + +/** + * + * @ClassName SDKConfig + * @Description acpsdk配置文件acp_sdk.properties配置信息类 + * @date 2016-7-22 下午4:04:55 + * + */ +public class SDKConfig { + public static final String FILE_NAME = "properties/acp_sdk.properties"; + /** 前台请求URL. */ + private String frontRequestUrl; + /** 后台请求URL. */ + private String backRequestUrl; + /** 单笔查询 */ + private String singleQueryUrl; + /** 批量查询 */ + private String batchQueryUrl; + /** 批量交易 */ + private String batchTransUrl; + /** 文件传输 */ + private String fileTransUrl; + /** 签名证书路径. */ + private String signCertPath; + /** 签名证书密码. */ + private String signCertPwd; + /** 签名证书类型. */ + private String signCertType; + /** 加密公钥证书路径. */ + private String encryptCertPath; + /** 验证签名公钥证书目录. */ + private String validateCertDir; + /** 按照商户代码读取指定签名证书目录. */ + private String signCertDir; + /** 磁道加密证书路径. */ + private String encryptTrackCertPath; + /** 磁道加密公钥模数. */ + private String encryptTrackKeyModulus; + /** 磁道加密公钥指数. */ + private String encryptTrackKeyExponent; + /** 有卡交易. */ + private String cardRequestUrl; + /** app交易 */ + private String appRequestUrl; + /** 证书使用模式(单证书/多证书) */ + private String singleMode; + /** 安全密钥(SHA256和SM3计算时使用) */ + private String secureKey; + /** 中级证书路径 */ + private String middleCertPath; + /** 根证书路径 */ + private String rootCertPath; + /** 是否验证验签证书CN,除了false都验 */ + private boolean ifValidateCNName = true; + /** 是否验证https证书,默认都不验 */ + private boolean ifValidateRemoteCert = false; + /** signMethod,没配按01吧 */ + private String signMethod = "01"; + /** version,没配按5.0.0 */ + private String version = "5.0.0"; + /** frontUrl */ + private String frontUrl; + /** backUrl */ + private String backUrl; + + /*缴费相关地址*/ + private String jfFrontRequestUrl; + private String jfBackRequestUrl; + private String jfSingleQueryUrl; + private String jfCardRequestUrl; + private String jfAppRequestUrl; + + private String qrcBackTransUrl; + private String qrcB2cIssBackTransUrl; + private String qrcB2cMerBackTransUrl; + + /** 配置文件中的前台URL常量. */ + public static final String SDK_FRONT_URL = "acpsdk.frontTransUrl"; + /** 配置文件中的后台URL常量. */ + public static final String SDK_BACK_URL = "acpsdk.backTransUrl"; + /** 配置文件中的单笔交易查询URL常量. */ + public static final String SDK_SIGNQ_URL = "acpsdk.singleQueryUrl"; + /** 配置文件中的批量交易查询URL常量. */ + public static final String SDK_BATQ_URL = "acpsdk.batchQueryUrl"; + /** 配置文件中的批量交易URL常量. */ + public static final String SDK_BATTRANS_URL = "acpsdk.batchTransUrl"; + /** 配置文件中的文件类交易URL常量. */ + public static final String SDK_FILETRANS_URL = "acpsdk.fileTransUrl"; + /** 配置文件中的有卡交易URL常量. */ + public static final String SDK_CARD_URL = "acpsdk.cardTransUrl"; + /** 配置文件中的app交易URL常量. */ + public static final String SDK_APP_URL = "acpsdk.appTransUrl"; + + /** 以下缴费产品使用,其余产品用不到,无视即可 */ + // 前台请求地址 + public static final String JF_SDK_FRONT_TRANS_URL= "acpsdk.jfFrontTransUrl"; + // 后台请求地址 + public static final String JF_SDK_BACK_TRANS_URL="acpsdk.jfBackTransUrl"; + // 单笔查询请求地址 + public static final String JF_SDK_SINGLE_QUERY_URL="acpsdk.jfSingleQueryUrl"; + // 有卡交易地址 + public static final String JF_SDK_CARD_TRANS_URL="acpsdk.jfCardTransUrl"; + // App交易地址 + public static final String JF_SDK_APP_TRANS_URL="acpsdk.jfAppTransUrl"; + // 人到人 + public static final String QRC_BACK_TRANS_URL="acpsdk.qrcBackTransUrl"; + // 人到人 + public static final String QRC_B2C_ISS_BACK_TRANS_URL="acpsdk.qrcB2cIssBackTransUrl"; + // 人到人 + public static final String QRC_B2C_MER_BACK_TRANS_URL="acpsdk.qrcB2cMerBackTransUrl"; + + + /** 配置文件中签名证书路径常量. */ + public static final String SDK_SIGNCERT_PATH = "acpsdk.signCert.path"; + /** 配置文件中签名证书密码常量. */ + public static final String SDK_SIGNCERT_PWD = "acpsdk.signCert.pwd"; + /** 配置文件中签名证书类型常量. */ + public static final String SDK_SIGNCERT_TYPE = "acpsdk.signCert.type"; + /** 配置文件中密码加密证书路径常量. */ + public static final String SDK_ENCRYPTCERT_PATH = "acpsdk.encryptCert.path"; + /** 配置文件中磁道加密证书路径常量. */ + public static final String SDK_ENCRYPTTRACKCERT_PATH = "acpsdk.encryptTrackCert.path"; + /** 配置文件中磁道加密公钥模数常量. */ + public static final String SDK_ENCRYPTTRACKKEY_MODULUS = "acpsdk.encryptTrackKey.modulus"; + /** 配置文件中磁道加密公钥指数常量. */ + public static final String SDK_ENCRYPTTRACKKEY_EXPONENT = "acpsdk.encryptTrackKey.exponent"; + /** 配置文件中验证签名证书目录常量. */ + public static final String SDK_VALIDATECERT_DIR = "acpsdk.validateCert.dir"; + + /** 配置文件中是否加密cvn2常量. */ + public static final String SDK_CVN_ENC = "acpsdk.cvn2.enc"; + /** 配置文件中是否加密cvn2有效期常量. */ + public static final String SDK_DATE_ENC = "acpsdk.date.enc"; + /** 配置文件中是否加密卡号常量. */ + public static final String SDK_PAN_ENC = "acpsdk.pan.enc"; + /** 配置文件中证书使用模式 */ + public static final String SDK_SINGLEMODE = "acpsdk.singleMode"; + /** 配置文件中安全密钥 */ + public static final String SDK_SECURITYKEY = "acpsdk.secureKey"; + /** 配置文件中根证书路径常量 */ + public static final String SDK_ROOTCERT_PATH = "acpsdk.rootCert.path"; + /** 配置文件中根证书路径常量 */ + public static final String SDK_MIDDLECERT_PATH = "acpsdk.middleCert.path"; + /** 配置是否需要验证验签证书CN,除了false之外的值都当true处理 */ + public static final String SDK_IF_VALIDATE_CN_NAME = "acpsdk.ifValidateCNName"; + /** 配置是否需要验证https证书,除了true之外的值都当false处理 */ + public static final String SDK_IF_VALIDATE_REMOTE_CERT = "acpsdk.ifValidateRemoteCert"; + /** signmethod */ + public static final String SDK_SIGN_METHOD ="acpsdk.signMethod"; + /** version */ + public static final String SDK_VERSION = "acpsdk.version"; + /** 后台通知地址 */ + public static final String SDK_BACKURL = "acpsdk.backUrl"; + /** 前台通知地址 */ + public static final String SDK_FRONTURL = "acpsdk.frontUrl"; + /** 操作对象. */ + private static SDKConfig config = new SDKConfig(); + /** 属性文件对象. */ + private Properties properties; + + private SDKConfig() { + super(); + } + + /** + * 获取config对象. + * @return + */ + public static SDKConfig getConfig() { + return config; + } + + /** + * 从properties文件加载 + * + * @param rootPath + * 不包含文件名的目录. + */ + public void loadPropertiesFromPath(String rootPath) { + if (StringUtils.isNotBlank(rootPath)) { + LogUtil.writeLog("从路径读取配置文件: " + rootPath+File.separator+FILE_NAME); + File file = new File(rootPath + File.separator + FILE_NAME); + InputStream in = null; + if (file.exists()) { + try { + in = new FileInputStream(file); + properties = new Properties(); + properties.load(in); + loadProperties(properties); + } catch (FileNotFoundException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + } + } else { + // 由于此时可能还没有完成LOG的加载,因此采用标准输出来打印日志信息 + LogUtil.writeErrorLog(rootPath + FILE_NAME + "不存在,加载参数失败"); + } + } else { + loadPropertiesFromSrc(); + } + + } + + /** + * 从classpath路径下加载配置参数 + */ + public void loadPropertiesFromSrc() { + InputStream in = null; + try { + LogUtil.writeLog("从classpath: " +SDKConfig.class.getClassLoader().getResource("").getPath()+" 获取属性文件"+FILE_NAME); + in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME); + if (null != in) { + properties = new Properties(); + try { + properties.load(in); + } catch (IOException e) { + throw e; + } + } else { + LogUtil.writeErrorLog(FILE_NAME + "属性文件未能在classpath指定的目录下 "+SDKConfig.class.getClassLoader().getResource("").getPath()+" 找到!"); + return; + } + loadProperties(properties); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + } + } + + /** + * 根据传入的 {@link #(Properties)}对象设置配置参数 + * + * @param pro + */ + public void loadProperties(Properties pro) { + LogUtil.writeLog("开始从属性文件中加载配置项"); + String value = null; + + value = pro.getProperty(SDK_SIGNCERT_PATH); + if (!SDKUtil.isEmpty(value)) { + this.signCertPath = value.trim(); + LogUtil.writeLog("配置项:私钥签名证书路径==>"+SDK_SIGNCERT_PATH +"==>"+ value+" 已加载"); + } + value = pro.getProperty(SDK_SIGNCERT_PWD); + if (!SDKUtil.isEmpty(value)) { + this.signCertPwd = value.trim(); + LogUtil.writeLog("配置项:私钥签名证书密码==>"+SDK_SIGNCERT_PWD +" 已加载"); + } + value = pro.getProperty(SDK_SIGNCERT_TYPE); + if (!SDKUtil.isEmpty(value)) { + this.signCertType = value.trim(); + LogUtil.writeLog("配置项:私钥签名证书类型==>"+SDK_SIGNCERT_TYPE +"==>"+ value+" 已加载"); + } + value = pro.getProperty(SDK_ENCRYPTCERT_PATH); + if (!SDKUtil.isEmpty(value)) { + this.encryptCertPath = value.trim(); + LogUtil.writeLog("配置项:敏感信息加密证书==>"+SDK_ENCRYPTCERT_PATH +"==>"+ value+" 已加载"); + } + value = pro.getProperty(SDK_VALIDATECERT_DIR); + if (!SDKUtil.isEmpty(value)) { + this.validateCertDir = value.trim(); + LogUtil.writeLog("配置项:验证签名证书路径(这里配置的是目录,不要指定到公钥文件)==>"+SDK_VALIDATECERT_DIR +"==>"+ value+" 已加载"); + } + value = pro.getProperty(SDK_FRONT_URL); + if (!SDKUtil.isEmpty(value)) { + this.frontRequestUrl = value.trim(); + } + value = pro.getProperty(SDK_BACK_URL); + if (!SDKUtil.isEmpty(value)) { + this.backRequestUrl = value.trim(); + } + value = pro.getProperty(SDK_BATQ_URL); + if (!SDKUtil.isEmpty(value)) { + this.batchQueryUrl = value.trim(); + } + value = pro.getProperty(SDK_BATTRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.batchTransUrl = value.trim(); + } + value = pro.getProperty(SDK_FILETRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.fileTransUrl = value.trim(); + } + value = pro.getProperty(SDK_SIGNQ_URL); + if (!SDKUtil.isEmpty(value)) { + this.singleQueryUrl = value.trim(); + } + value = pro.getProperty(SDK_CARD_URL); + if (!SDKUtil.isEmpty(value)) { + this.cardRequestUrl = value.trim(); + } + value = pro.getProperty(SDK_APP_URL); + if (!SDKUtil.isEmpty(value)) { + this.appRequestUrl = value.trim(); + } + value = pro.getProperty(SDK_ENCRYPTTRACKCERT_PATH); + if (!SDKUtil.isEmpty(value)) { + this.encryptTrackCertPath = value.trim(); + } + + value = pro.getProperty(SDK_SECURITYKEY); + if (!SDKUtil.isEmpty(value)) { + this.secureKey = value.trim(); + } + value = pro.getProperty(SDK_ROOTCERT_PATH); + if (!SDKUtil.isEmpty(value)) { + this.rootCertPath = value.trim(); + } + value = pro.getProperty(SDK_MIDDLECERT_PATH); + if (!SDKUtil.isEmpty(value)) { + this.middleCertPath = value.trim(); + } + + /**缴费部分**/ + value = pro.getProperty(JF_SDK_FRONT_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.jfFrontRequestUrl = value.trim(); + } + + value = pro.getProperty(JF_SDK_BACK_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.jfBackRequestUrl = value.trim(); + } + + value = pro.getProperty(JF_SDK_SINGLE_QUERY_URL); + if (!SDKUtil.isEmpty(value)) { + this.jfSingleQueryUrl = value.trim(); + } + + value = pro.getProperty(JF_SDK_CARD_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.jfCardRequestUrl = value.trim(); + } + + value = pro.getProperty(JF_SDK_APP_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.jfAppRequestUrl = value.trim(); + } + + value = pro.getProperty(QRC_BACK_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.qrcBackTransUrl = value.trim(); + } + + value = pro.getProperty(QRC_B2C_ISS_BACK_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.qrcB2cIssBackTransUrl = value.trim(); + } + + value = pro.getProperty(QRC_B2C_MER_BACK_TRANS_URL); + if (!SDKUtil.isEmpty(value)) { + this.qrcB2cMerBackTransUrl = value.trim(); + } + + value = pro.getProperty(SDK_ENCRYPTTRACKKEY_EXPONENT); + if (!SDKUtil.isEmpty(value)) { + this.encryptTrackKeyExponent = value.trim(); + } + + value = pro.getProperty(SDK_ENCRYPTTRACKKEY_MODULUS); + if (!SDKUtil.isEmpty(value)) { + this.encryptTrackKeyModulus = value.trim(); + } + + value = pro.getProperty(SDK_IF_VALIDATE_CN_NAME); + if (!SDKUtil.isEmpty(value)) { + if( SDKConstants.FALSE_STRING.equals(value.trim())) + this.ifValidateCNName = false; + } + + value = pro.getProperty(SDK_IF_VALIDATE_REMOTE_CERT); + if (!SDKUtil.isEmpty(value)) { + if( SDKConstants.TRUE_STRING.equals(value.trim())) + this.ifValidateRemoteCert = true; + } + + value = pro.getProperty(SDK_SIGN_METHOD); + if (!SDKUtil.isEmpty(value)) { + this.signMethod = value.trim(); + } + + value = pro.getProperty(SDK_SIGN_METHOD); + if (!SDKUtil.isEmpty(value)) { + this.signMethod = value.trim(); + } + value = pro.getProperty(SDK_VERSION); + if (!SDKUtil.isEmpty(value)) { + this.version = value.trim(); + } + value = pro.getProperty(SDK_FRONTURL); + if (!SDKUtil.isEmpty(value)) { + this.frontUrl = value.trim(); + } + value = pro.getProperty(SDK_BACKURL); + if (!SDKUtil.isEmpty(value)) { + this.backUrl = value.trim(); + } + } + + + public String getFrontRequestUrl() { + return frontRequestUrl; + } + + public void setFrontRequestUrl(String frontRequestUrl) { + this.frontRequestUrl = frontRequestUrl; + } + + public String getBackRequestUrl() { + return backRequestUrl; + } + + public void setBackRequestUrl(String backRequestUrl) { + this.backRequestUrl = backRequestUrl; + } + + public String getSignCertPath() { + return signCertPath; + } + + public void setSignCertPath(String signCertPath) { + this.signCertPath = signCertPath; + } + + public String getSignCertPwd() { + return signCertPwd; + } + + public void setSignCertPwd(String signCertPwd) { + this.signCertPwd = signCertPwd; + } + + public String getSignCertType() { + return signCertType; + } + + public void setSignCertType(String signCertType) { + this.signCertType = signCertType; + } + + public String getEncryptCertPath() { + return encryptCertPath; + } + + public void setEncryptCertPath(String encryptCertPath) { + this.encryptCertPath = encryptCertPath; + } + + public String getValidateCertDir() { + return validateCertDir; + } + + public void setValidateCertDir(String validateCertDir) { + this.validateCertDir = validateCertDir; + } + + public String getSingleQueryUrl() { + return singleQueryUrl; + } + + public void setSingleQueryUrl(String singleQueryUrl) { + this.singleQueryUrl = singleQueryUrl; + } + + public String getBatchQueryUrl() { + return batchQueryUrl; + } + + public void setBatchQueryUrl(String batchQueryUrl) { + this.batchQueryUrl = batchQueryUrl; + } + + public String getBatchTransUrl() { + return batchTransUrl; + } + + public void setBatchTransUrl(String batchTransUrl) { + this.batchTransUrl = batchTransUrl; + } + + public String getFileTransUrl() { + return fileTransUrl; + } + + public void setFileTransUrl(String fileTransUrl) { + this.fileTransUrl = fileTransUrl; + } + + public String getSignCertDir() { + return signCertDir; + } + + public void setSignCertDir(String signCertDir) { + this.signCertDir = signCertDir; + } + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + + public String getCardRequestUrl() { + return cardRequestUrl; + } + + public void setCardRequestUrl(String cardRequestUrl) { + this.cardRequestUrl = cardRequestUrl; + } + + public String getAppRequestUrl() { + return appRequestUrl; + } + + public void setAppRequestUrl(String appRequestUrl) { + this.appRequestUrl = appRequestUrl; + } + + public String getEncryptTrackCertPath() { + return encryptTrackCertPath; + } + + public void setEncryptTrackCertPath(String encryptTrackCertPath) { + this.encryptTrackCertPath = encryptTrackCertPath; + } + + public String getJfFrontRequestUrl() { + return jfFrontRequestUrl; + } + + public void setJfFrontRequestUrl(String jfFrontRequestUrl) { + this.jfFrontRequestUrl = jfFrontRequestUrl; + } + + public String getJfBackRequestUrl() { + return jfBackRequestUrl; + } + + public void setJfBackRequestUrl(String jfBackRequestUrl) { + this.jfBackRequestUrl = jfBackRequestUrl; + } + + public String getJfSingleQueryUrl() { + return jfSingleQueryUrl; + } + + public void setJfSingleQueryUrl(String jfSingleQueryUrl) { + this.jfSingleQueryUrl = jfSingleQueryUrl; + } + + public String getJfCardRequestUrl() { + return jfCardRequestUrl; + } + + public void setJfCardRequestUrl(String jfCardRequestUrl) { + this.jfCardRequestUrl = jfCardRequestUrl; + } + + public String getJfAppRequestUrl() { + return jfAppRequestUrl; + } + + public void setJfAppRequestUrl(String jfAppRequestUrl) { + this.jfAppRequestUrl = jfAppRequestUrl; + } + + public String getSingleMode() { + return singleMode; + } + + public void setSingleMode(String singleMode) { + this.singleMode = singleMode; + } + + public String getEncryptTrackKeyExponent() { + return encryptTrackKeyExponent; + } + + public void setEncryptTrackKeyExponent(String encryptTrackKeyExponent) { + this.encryptTrackKeyExponent = encryptTrackKeyExponent; + } + + public String getEncryptTrackKeyModulus() { + return encryptTrackKeyModulus; + } + + public void setEncryptTrackKeyModulus(String encryptTrackKeyModulus) { + this.encryptTrackKeyModulus = encryptTrackKeyModulus; + } + + public String getSecureKey() { + return secureKey; + } + + public void setSecureKey(String securityKey) { + this.secureKey = securityKey; + } + + public String getMiddleCertPath() { + return middleCertPath; + } + + public void setMiddleCertPath(String middleCertPath) { + this.middleCertPath = middleCertPath; + } + + public boolean isIfValidateCNName() { + return ifValidateCNName; + } + + public void setIfValidateCNName(boolean ifValidateCNName) { + this.ifValidateCNName = ifValidateCNName; + } + + public boolean isIfValidateRemoteCert() { + return ifValidateRemoteCert; + } + + public void setIfValidateRemoteCert(boolean ifValidateRemoteCert) { + this.ifValidateRemoteCert = ifValidateRemoteCert; + } + + public String getSignMethod() { + return signMethod; + } + + public void setSignMethod(String signMethod) { + this.signMethod = signMethod; + } + public String getQrcBackTransUrl() { + return qrcBackTransUrl; + } + + public void setQrcBackTransUrl(String qrcBackTransUrl) { + this.qrcBackTransUrl = qrcBackTransUrl; + } + + public String getQrcB2cIssBackTransUrl() { + return qrcB2cIssBackTransUrl; + } + + public void setQrcB2cIssBackTransUrl(String qrcB2cIssBackTransUrl) { + this.qrcB2cIssBackTransUrl = qrcB2cIssBackTransUrl; + } + + public String getQrcB2cMerBackTransUrl() { + return qrcB2cMerBackTransUrl; + } + + public void setQrcB2cMerBackTransUrl(String qrcB2cMerBackTransUrl) { + this.qrcB2cMerBackTransUrl = qrcB2cMerBackTransUrl; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getFrontUrl() { + return frontUrl; + } + + public void setFrontUrl(String frontUrl) { + this.frontUrl = frontUrl; + } + + public String getBackUrl() { + return backUrl; + } + + public void setBackUrl(String backUrl) { + this.backUrl = backUrl; + } + + public String getRootCertPath() { + return rootCertPath; + } + + public void setRootCertPath(String rootCertPath) { + this.rootCertPath = rootCertPath; + } + +} diff --git a/back-end_code/src/main/java/com/shop/union/constants/SDKConstants.java b/back-end_code/src/main/java/com/shop/union/constants/SDKConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..aa7c3899f073240d74c2a3bdeeac03fe406c26ff --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/constants/SDKConstants.java @@ -0,0 +1,391 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 MPI插件包常量定义 + * ============================================================================= + */ +package com.shop.union.constants; +/** + * + * @ClassName SDKConstants + * @Description acpsdk常量类 + * @date 2016-7-22 下午4:05:54 + * + */ +public class SDKConstants { + + public final static String COLUMN_DEFAULT = "-"; + + public final static String KEY_DELIMITER = "#"; + + /** memeber variable: blank. */ + public static final String BLANK = ""; + + /** member variabel: space. */ + public static final String SPACE = " "; + + /** memeber variable: unline. */ + public static final String UNLINE = "_"; + + /** memeber varibale: star. */ + public static final String STAR = "*"; + + /** memeber variable: line. */ + public static final String LINE = "-"; + + /** memeber variable: add. */ + public static final String ADD = "+"; + + /** memeber variable: colon. */ + public final static String COLON = "|"; + + /** memeber variable: point. */ + public final static String POINT = "."; + + /** memeber variable: comma. */ + public final static String COMMA = ","; + + /** memeber variable: slash. */ + public final static String SLASH = "/"; + + /** memeber variable: div. */ + public final static String DIV = "/"; + + /** memeber variable: left . */ + public final static String LB = "("; + + /** memeber variable: right. */ + public final static String RB = ")"; + + /** memeber variable: rmb. */ + public final static String CUR_RMB = "RMB"; + + /** memeber variable: .page size */ + public static final int PAGE_SIZE = 10; + + /** memeber variable: String ONE. */ + public static final String ONE = "1"; + + /** memeber variable: String ZERO. */ + public static final String ZERO = "0"; + + /** memeber variable: number six. */ + public static final int NUM_SIX = 6; + + /** memeber variable: equal mark. */ + public static final String EQUAL = "="; + + /** memeber variable: operation ne. */ + public static final String NE = "!="; + + /** memeber variable: operation le. */ + public static final String LE = "<="; + + /** memeber variable: operation ge. */ + public static final String GE = ">="; + + /** memeber variable: operation lt. */ + public static final String LT = "<"; + + /** memeber variable: operation gt. */ + public static final String GT = ">"; + + /** memeber variable: list separator. */ + public static final String SEP = "./"; + + /** memeber variable: Y. */ + public static final String Y = "Y"; + + /** memeber variable: AMPERSAND. */ + public static final String AMPERSAND = "&"; + + /** memeber variable: SQL_LIKE_TAG. */ + public static final String SQL_LIKE_TAG = "%"; + + /** memeber variable: @. */ + public static final String MAIL = "@"; + + /** memeber variable: number zero. */ + public static final int NZERO = 0; + + public static final String LEFT_BRACE = "{"; + + public static final String RIGHT_BRACE = "}"; + + /** memeber variable: string true. */ + public static final String TRUE_STRING = "true"; + /** memeber variable: string false. */ + public static final String FALSE_STRING = "false"; + + /** memeber variable: forward success. */ + public static final String SUCCESS = "success"; + /** memeber variable: forward fail. */ + public static final String FAIL = "fail"; + /** memeber variable: global forward success. */ + public static final String GLOBAL_SUCCESS = "$success"; + /** memeber variable: global forward fail. */ + public static final String GLOBAL_FAIL = "$fail"; + + public static final String UTF_8_ENCODING = "UTF-8"; + public static final String GBK_ENCODING = "GBK"; + public static final String CONTENT_TYPE = "Content-type"; + public static final String APP_XML_TYPE = "application/xml;charset=utf-8"; + public static final String APP_FORM_TYPE = "application/x-www-form-urlencoded;charset="; + + public static final String VERSION_1_0_0 = "1.0.0"; + public static final String VERSION_5_0_0 = "5.0.0"; + public static final String VERSION_5_0_1 = "5.0.1"; + public static final String VERSION_5_1_0 = "5.1.0"; + public static final String SIGNMETHOD_RSA = "01"; + public static final String SIGNMETHOD_SHA256 = "11"; + public static final String SIGNMETHOD_SM3 = "12"; + public static final String UNIONPAY_CNNAME = "中国银联股份有限公司"; + public static final String CERTTYPE_01 = "01";// 敏感信息加密公钥 + public static final String CERTTYPE_02 = "02";// 磁道加密公钥 + + /******************************************** 5.0报文接口定义 ********************************************/ + /** 版本号. */ + public static final String param_version = "version"; + /** 证书ID. */ + public static final String param_certId = "certId"; + /** 签名. */ + public static final String param_signature = "signature"; + /** 签名方法. */ + public static final String param_signMethod = "signMethod"; + /** 编码方式. */ + public static final String param_encoding = "encoding"; + /** 交易类型. */ + public static final String param_txnType = "txnType"; + /** 交易子类. */ + public static final String param_txnSubType = "txnSubType"; + /** 业务类型. */ + public static final String param_bizType = "bizType"; + /** 前台通知地址 . */ + public static final String param_frontUrl = "frontUrl"; + /** 后台通知地址. */ + public static final String param_backUrl = "backUrl"; + /** 接入类型. */ + public static final String param_accessType = "accessType"; + /** 收单机构代码. */ + public static final String param_acqInsCode = "acqInsCode"; + /** 商户类别. */ + public static final String param_merCatCode = "merCatCode"; + /** 商户类型. */ + public static final String param_merType = "merType"; + /** 商户代码. */ + public static final String param_merId = "merId"; + /** 商户名称. */ + public static final String param_merName = "merName"; + /** 商户简称. */ + public static final String param_merAbbr = "merAbbr"; + /** 二级商户代码. */ + public static final String param_subMerId = "subMerId"; + /** 二级商户名称. */ + public static final String param_subMerName = "subMerName"; + /** 二级商户简称. */ + public static final String param_subMerAbbr = "subMerAbbr"; + /** Cupsecure 商户代码. */ + public static final String param_csMerId = "csMerId"; + /** 商户订单号. */ + public static final String param_orderId = "orderId"; + /** 交易时间. */ + public static final String param_txnTime = "txnTime"; + /** 发送时间. */ + public static final String param_txnSendTime = "txnSendTime"; + /** 订单超时时间间隔. */ + public static final String param_orderTimeoutInterval = "orderTimeoutInterval"; + /** 支付超时时间. */ + public static final String param_payTimeoutTime = "payTimeoutTime"; + /** 默认支付方式. */ + public static final String param_defaultPayType = "defaultPayType"; + /** 支持支付方式. */ + public static final String param_supPayType = "supPayType"; + /** 支付方式. */ + public static final String param_payType = "payType"; + /** 自定义支付方式. */ + public static final String param_customPayType = "customPayType"; + /** 物流标识. */ + public static final String param_shippingFlag = "shippingFlag"; + /** 收货地址-国家. */ + public static final String param_shippingCountryCode = "shippingCountryCode"; + /** 收货地址-省. */ + public static final String param_shippingProvinceCode = "shippingProvinceCode"; + /** 收货地址-市. */ + public static final String param_shippingCityCode = "shippingCityCode"; + /** 收货地址-地区. */ + public static final String param_shippingDistrictCode = "shippingDistrictCode"; + /** 收货地址-详细. */ + public static final String param_shippingStreet = "shippingStreet"; + /** 商品总类. */ + public static final String param_commodityCategory = "commodityCategory"; + /** 商品名称. */ + public static final String param_commodityName = "commodityName"; + /** 商品URL. */ + public static final String param_commodityUrl = "commodityUrl"; + /** 商品单价. */ + public static final String param_commodityUnitPrice = "commodityUnitPrice"; + /** 商品数量. */ + public static final String param_commodityQty = "commodityQty"; + /** 是否预授权. */ + public static final String param_isPreAuth = "isPreAuth"; + /** 币种. */ + public static final String param_currencyCode = "currencyCode"; + /** 账户类型. */ + public static final String param_accType = "accType"; + /** 账号. */ + public static final String param_accNo = "accNo"; + /** 支付卡类型. */ + public static final String param_payCardType = "payCardType"; + /** 发卡机构代码. */ + public static final String param_issInsCode = "issInsCode"; + /** 持卡人信息. */ + public static final String param_customerInfo = "customerInfo"; + /** 交易金额. */ + public static final String param_txnAmt = "txnAmt"; + /** 余额. */ + public static final String param_balance = "balance"; + /** 地区代码. */ + public static final String param_districtCode = "districtCode"; + /** 附加地区代码. */ + public static final String param_additionalDistrictCode = "additionalDistrictCode"; + /** 账单类型. */ + public static final String param_billType = "billType"; + /** 账单号码. */ + public static final String param_billNo = "billNo"; + /** 账单月份. */ + public static final String param_billMonth = "billMonth"; + /** 账单查询要素. */ + public static final String param_billQueryInfo = "billQueryInfo"; + /** 账单详情. */ + public static final String param_billDetailInfo = "billDetailInfo"; + /** 账单金额. */ + public static final String param_billAmt = "billAmt"; + /** 账单金额符号. */ + public static final String param_billAmtSign = "billAmtSign"; + /** 绑定标识号. */ + public static final String param_bindId = "bindId"; + /** 风险级别. */ + public static final String param_riskLevel = "riskLevel"; + /** 绑定信息条数. */ + public static final String param_bindInfoQty = "bindInfoQty"; + /** 绑定信息集. */ + public static final String param_bindInfoList = "bindInfoList"; + /** 批次号. */ + public static final String param_batchNo = "batchNo"; + /** 总笔数. */ + public static final String param_totalQty = "totalQty"; + /** 总金额. */ + public static final String param_totalAmt = "totalAmt"; + /** 文件类型. */ + public static final String param_fileType = "fileType"; + /** 文件名称. */ + public static final String param_fileName = "fileName"; + /** 批量文件内容. */ + public static final String param_fileContent = "fileContent"; + /** 商户摘要. */ + public static final String param_merNote = "merNote"; + /** 商户自定义域. */ + // public static final String param_merReserved = "merReserved";//接口变更删除 + /** 请求方保留域. */ + public static final String param_reqReserved = "reqReserved";// 新增接口 + /** 保留域. */ + public static final String param_reserved = "reserved"; + /** 终端号. */ + public static final String param_termId = "termId"; + /** 终端类型. */ + public static final String param_termType = "termType"; + /** 交互模式. */ + public static final String param_interactMode = "interactMode"; + /** 发卡机构识别模式. */ + // public static final String param_recognitionMode = "recognitionMode"; + public static final String param_issuerIdentifyMode = "issuerIdentifyMode";// 接口名称变更 + /** 商户端用户号. */ + public static final String param_merUserId = "merUserId"; + /** 持卡人IP. */ + public static final String param_customerIp = "customerIp"; + /** 查询流水号. */ + public static final String param_queryId = "queryId"; + /** 原交易查询流水号. */ + public static final String param_origQryId = "origQryId"; + /** 系统跟踪号. */ + public static final String param_traceNo = "traceNo"; + /** 交易传输时间. */ + public static final String param_traceTime = "traceTime"; + /** 清算日期. */ + public static final String param_settleDate = "settleDate"; + /** 清算币种. */ + public static final String param_settleCurrencyCode = "settleCurrencyCode"; + /** 清算金额. */ + public static final String param_settleAmt = "settleAmt"; + /** 清算汇率. */ + public static final String param_exchangeRate = "exchangeRate"; + /** 兑换日期. */ + public static final String param_exchangeDate = "exchangeDate"; + /** 响应时间. */ + public static final String param_respTime = "respTime"; + /** 原交易应答码. */ + public static final String param_origRespCode = "origRespCode"; + /** 原交易应答信息. */ + public static final String param_origRespMsg = "origRespMsg"; + /** 应答码. */ + public static final String param_respCode = "respCode"; + /** 应答码信息. */ + public static final String param_respMsg = "respMsg"; + // 新增四个报文字段merUserRegDt merUserEmail checkFlag activateStatus + /** 商户端用户注册时间. */ + public static final String param_merUserRegDt = "merUserRegDt"; + /** 商户端用户注册邮箱. */ + public static final String param_merUserEmail = "merUserEmail"; + /** 验证标识. */ + public static final String param_checkFlag = "checkFlag"; + /** 开通状态. */ + public static final String param_activateStatus = "activateStatus"; + /** 加密证书ID. */ + public static final String param_encryptCertId = "encryptCertId"; + /** 用户MAC、IMEI串号、SSID. */ + public static final String param_userMac = "userMac"; + /** 关联交易. */ + // public static final String param_relationTxnType = "relationTxnType"; + /** 短信类型 */ + public static final String param_smsType = "smsType"; + + /** 风控信息域 */ + public static final String param_riskCtrlInfo = "riskCtrlInfo"; + + /** IC卡交易信息域 */ + public static final String param_ICTransData = "ICTransData"; + + /** VPC交易信息域 */ + public static final String param_VPCTransData = "VPCTransData"; + + /** 安全类型 */ + public static final String param_securityType = "securityType"; + + /** 银联订单号 */ + public static final String param_tn = "tn"; + + /** 分期付款手续费率 */ + public static final String param_instalRate = "instalRate"; + + /** 分期付款手续费率 */ + public static final String param_mchntFeeSubsidy = "mchntFeeSubsidy"; + + /** 签名公钥证书 */ + public static final String param_signPubKeyCert = "signPubKeyCert"; + + /** 加密公钥证书 */ + public static final String param_encryptPubKeyCert = "encryptPubKeyCert"; + + /** 证书类型 */ + public static final String param_certType = "certType"; + +} diff --git a/back-end_code/src/main/java/com/shop/union/service/AcpService.java b/back-end_code/src/main/java/com/shop/union/service/AcpService.java new file mode 100644 index 0000000000000000000000000000000000000000..84812eb912db67909b813c85040c0dbeb963b56b --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/service/AcpService.java @@ -0,0 +1,673 @@ +package com.shop.union.service; + + +import com.shop.union.constants.SDKConstants; +import com.shop.union.util.*; + +import java.io.*; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @ClassName AcpService + * @Description acpsdk接口服务类,接入商户集成请可以直接参考使用本类中的方法 + * @date 2016-7-22 下午2:44:37 + */ +public class AcpService { + + /** + * 请求报文签名(使用配置文件中配置的私钥证书或者对称密钥签名)
+ * 功能:对请求报文进行签名,并计算赋值certid,signature字段并返回
+ * @param reqData 请求报文map
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return 签名后的map对象
+ */ + public static Map sign(Map reqData,String encoding) { + reqData = SDKUtil.filterBlank(reqData); + SDKUtil.sign(reqData, encoding); + return reqData; + } + + /** + * 同signByCertInfo
+ * @param reqData + * @param certPath + * @param certPwd + * @param encoding + * @return + * @deprecated + */ + public static Map sign(Map reqData, String certPath, + String certPwd,String encoding) { + reqData = SDKUtil.filterBlank(reqData); + SDKUtil.signByCertInfo(reqData,certPath,certPwd,encoding); + return reqData; + } + + /** + * 多证书签名(通过传入私钥证书路径和密码签名)
+ * 功能:如果有多个商户号接入银联,每个商户号对应不同的证书可以使用此方法:传入私钥证书和密码(并且在acp_sdk.properties中 配置 acpsdk.singleMode=false)
+ * @param reqData 请求报文map
+ * @param certPath 签名私钥文件(带路径)
+ * @param certPwd 签名私钥密码
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return 签名后的map对象
+ */ + public static Map signByCertInfo(Map reqData, String certPath, + String certPwd,String encoding) { + reqData = SDKUtil.filterBlank(reqData); + SDKUtil.signByCertInfo(reqData,certPath,certPwd,encoding); + return reqData; + } + + /** + * 多密钥签名(通过传入密钥签名)
+ * 功能:如果有多个商户号接入银联,每个商户号对应不同的证书可以使用此方法:传入私钥证书和密码(并且在acp_sdk.properties中 配置 acpsdk.singleMode=false)
+ * @param reqData 请求报文map
+ * @param secureKey 签名对称密钥
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return 签名后的map对象
+ */ + public static Map signBySecureKey(Map reqData, String secureKey, String encoding) { + reqData = SDKUtil.filterBlank(reqData); + SDKUtil.signBySecureKey(reqData, secureKey, encoding); + return reqData; + } + + /** + * 验证签名(SHA-1摘要算法)
+ * @param rspData 返回报文数据
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return true 通过 false 未通过
+ */ + public static boolean validate(Map rspData, String encoding) { + return SDKUtil.validate(rspData, encoding); + } + + /** + * 多密钥验签(通过传入密钥签名)
+ * @param rspData 返回报文数据
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return true 通过 false 未通过
+ */ + public static boolean validateBySecureKey(Map rspData, String secureKey, String encoding) { + return SDKUtil.validateBySecureKey(rspData, secureKey, encoding); + } + + + /** + * @deprecated 5.1.0开发包已删除此方法,请直接参考5.1.0开发包中的VerifyAppData.java验签。 + * 对控件支付成功返回的结果信息中data域进行验签(控件端获取的应答信息)
+ * @param jsonData json格式数据,例如:{"sign" : "J6rPLClQ64szrdXCOtV1ccOMzUmpiOKllp9cseBuRqJ71pBKPPkZ1FallzW18gyP7CvKh1RxfNNJ66AyXNMFJi1OSOsteAAFjF5GZp0Xsfm3LeHaN3j/N7p86k3B1GrSPvSnSw1LqnYuIBmebBkC1OD0Qi7qaYUJosyA1E8Ld8oGRZT5RR2gLGBoiAVraDiz9sci5zwQcLtmfpT5KFk/eTy4+W9SsC0M/2sVj43R9ePENlEvF8UpmZBqakyg5FO8+JMBz3kZ4fwnutI5pWPdYIWdVrloBpOa+N4pzhVRKD4eWJ0CoiD+joMS7+C0aPIEymYFLBNYQCjM0KV7N726LA==", "data" : "pay_result=success&tn=201602141008032671528&cert_id=68759585097"} + * @return 是否成功 + */ + public static boolean validateAppResponse(String jsonData, String encoding) { + LogUtil.writeLog("控件应答信息验签处理开始:[" + jsonData + "]"); + if (SDKUtil.isEmpty(encoding)) { + encoding = "UTF-8"; + } + + Pattern p = Pattern.compile("\\s*\"sign\"\\s*:\\s*\"([^\"]*)\"\\s*"); + Matcher m = p.matcher(jsonData); + if(!m.find()) return false; + String sign = m.group(1); + + p = Pattern.compile("\\s*\"data\"\\s*:\\s*\"([^\"]*)\"\\s*"); + m = p.matcher(jsonData); + if(!m.find()) return false; + String data = m.group(1); + + p = Pattern.compile("cert_id=(\\d*)"); + m = p.matcher(jsonData); + if(!m.find()) return false; + String certId = m.group(1); + + try { + // 验证签名需要用银联发给商户的公钥证书. + return SecureUtil.validateSignBySoft(CertUtil + .getValidatePublicKey(certId), SecureUtil.base64Decode(sign + .getBytes(encoding)), SecureUtil.sha1X16(data, + encoding)); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return false; + } + + /** + * 功能:后台交易提交请求报文并接收同步应答报文
+ * @param reqData 请求报文
+ * @param reqUrl 请求地址
+ * @param encoding
+ * @return 应答http 200返回true ,其他false
+ */ + public static Map post( + Map reqData,String reqUrl,String encoding) { + Map rspData = new HashMap(); + LogUtil.writeLog("请求银联地址:" + reqUrl); + //发送后台请求数据 + HttpClient hc = new HttpClient(reqUrl, 30000, 30000); + try { + int status = hc.send(reqData, encoding); + if (200 == status) { + String resultString = hc.getResult(); + if (null != resultString && !"".equals(resultString)) { + // 将返回结果转换为map + Map tmpRspData = SDKUtil.convertResultStringToMap(resultString); + rspData.putAll(tmpRspData); + } + }else{ + LogUtil.writeLog("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确"); + } + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return rspData; + } + + /** + * 功能:http Get方法 便民缴费产品中使用
+ * @param reqUrl 请求地址
+ * @param encoding
+ * @return + */ + public static String get(String reqUrl,String encoding) { + + LogUtil.writeLog("请求银联地址:" + reqUrl); + //发送后台请求数据 + HttpClient hc = new HttpClient(reqUrl, 30000, 30000); + try { + int status = hc.sendGet(encoding); + if (200 == status) { + String resultString = hc.getResult(); + if (null != resultString && !"".equals(resultString)) { + return resultString; + } + }else{ + LogUtil.writeLog("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确"); + } + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return null; + } + + + /** + * 功能:前台交易构造HTTP POST自动提交表单
+ * @param reqUrl 表单提交地址
+ * @param hiddens 以MAP形式存储的表单键值
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return 构造好的HTTP POST交易表单
+ */ + public static String createAutoFormHtml(String reqUrl, Map hiddens,String encoding) { + StringBuffer sf = new StringBuffer(); + //sf.append(""); + sf.append("
"); + if (null != hiddens && 0 != hiddens.size()) { + Set> set = hiddens.entrySet(); + Iterator> it = set.iterator(); + while (it.hasNext()) { + Entry ey = it.next(); + String key = ey.getKey(); + String value = ey.getValue(); + sf.append(""); + } + } + sf.append(""); + //sf.append(""); + sf.append(""); + //sf.append(""); + return sf.toString(); + } + + + /** + * 功能:将批量文件内容使用DEFLATE压缩算法压缩,Base64编码生成字符串并返回
+ * 适用到的交易:批量代付,批量代收,批量退货
+ * @param filePath 批量文件-全路径文件名
+ * @return + */ + public static String enCodeFileContent(String filePath,String encoding){ + String baseFileContent = ""; + + File file = new File(filePath); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + InputStream in = null; + try { + in = new FileInputStream(file); + int fl = in.available(); + if (null != in) { + byte[] s = new byte[fl]; + in.read(s, 0, fl); + // 压缩编码. + baseFileContent = new String(SecureUtil.base64Encode(SDKUtil.deflater(s)),encoding); + } + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + } + return baseFileContent; + } + + /** + * 功能:解析交易返回的fileContent字符串并落地 ( 解base64,解DEFLATE压缩并落地)
+ * 适用到的交易:对账文件下载,批量交易状态查询
+ * @param resData 返回报文map
+ * @param fileDirectory 落地的文件目录(绝对路径) + * @param encoding 上送请求报文域encoding字段的值
+ */ + public static String deCodeFileContent(Map resData,String fileDirectory,String encoding) { + // 解析返回文件 + String filePath = null; + String fileContent = resData.get(SDKConstants.param_fileContent); + if (null != fileContent && !"".equals(fileContent)) { + FileOutputStream out = null; + try { + byte[] fileArray = SDKUtil.inflater(SecureUtil + .base64Decode(fileContent.getBytes(encoding))); + if (SDKUtil.isEmpty(resData.get("fileName"))) { + filePath = fileDirectory + File.separator + resData.get("merId") + + "_" + resData.get("batchNo") + "_" + + resData.get("txnTime") + ".txt"; + } else { + filePath = fileDirectory + File.separator + resData.get("fileName"); + } + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + file.createNewFile(); + out = new FileOutputStream(file); + out.write(fileArray, 0, fileArray.length); + out.flush(); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + }finally{ + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return filePath; + } + + /** + * 功能:将结果文件内容 转换成明文字符串:解base64,解压缩
+ * 适用到的交易:批量交易状态查询
+ * @param fileContent 批量交易状态查询返回的文件内容
+ * @return 内容明文
+ */ + public static String getFileContent(String fileContent,String encoding){ + String fc = ""; + try { + fc = new String(SDKUtil.inflater(SecureUtil.base64Decode(fileContent.getBytes())),encoding); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return fc; + } + + + /** + * 功能:持卡人信息域customerInfo构造
+ * 说明:不勾选对敏感信息加密权限使用旧的构造customerInfo域方式,不对敏感信息进行加密(对 phoneNo,cvn2, expired不加密),但如果送pin的话则加密
+ * @param customerInfoMap 信息域请求参数 key送域名value送值,必送
+ * 例如:customerInfoMap.put("certifTp", "01"); //证件类型
+ customerInfoMap.put("certifId", "341126197709218366"); //证件号码
+ customerInfoMap.put("customerNm", "互联网"); //姓名
+ customerInfoMap.put("phoneNo", "13552535506"); //手机号
+ customerInfoMap.put("smsCode", "123456"); //短信验证码
+ customerInfoMap.put("pin", "111111"); //密码(加密)
+ customerInfoMap.put("cvn2", "123"); //卡背面的cvn2三位数字(不加密)
+ customerInfoMap.put("expired", "1711"); //有效期 年在前月在后(不加密)
+ * @param accNo customerInfoMap送了密码那么卡号必送,如果customerInfoMap未送密码pin,此字段可以不送
+ * @param encoding 上送请求报文域encoding字段的值
+ * @return base64后的持卡人信息域字段
+ */ + public static String getCustomerInfo(Map customerInfoMap,String accNo,String encoding) { + + if(customerInfoMap.isEmpty()) + return "{}"; + StringBuffer sf = new StringBuffer("{"); + for(Iterator it = customerInfoMap.keySet().iterator(); it.hasNext();){ + String key = it.next(); + String value = customerInfoMap.get(key); + if(key.equals("pin")){ + if(null == accNo || "".equals(accNo.trim())){ + LogUtil.writeLog("送了密码(PIN),必须在getCustomerInfo参数中上传卡号"); + throw new RuntimeException("加密PIN没送卡号无法后续处理"); + }else{ + value = encryptPin(accNo,value,encoding); + } + } + sf.append(key).append(SDKConstants.EQUAL).append(value); + if(it.hasNext()) + sf.append(SDKConstants.AMPERSAND); + } + String customerInfo = sf.append("}").toString(); + LogUtil.writeLog("组装的customerInfo明文:"+customerInfo); + try { + return new String(SecureUtil.base64Encode(sf.toString().getBytes( + encoding)),encoding); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return customerInfo; + } + + /** + * 功能:持卡人信息域customerInfo构造,勾选对敏感信息加密权限 适用新加密规范,对pin和phoneNo,cvn2,expired加密
+ * 适用到的交易:
+ * @param customerInfoMap 信息域请求参数 key送域名value送值,必送
+ * 例如:customerInfoMap.put("certifTp", "01"); //证件类型
+ customerInfoMap.put("certifId", "341126197709218366"); //证件号码
+ customerInfoMap.put("customerNm", "互联网"); //姓名
+ customerInfoMap.put("smsCode", "123456"); //短信验证码
+ customerInfoMap.put("pin", "111111"); //密码(加密)
+ customerInfoMap.put("phoneNo", "13552535506"); //手机号(加密)
+ customerInfoMap.put("cvn2", "123"); //卡背面的cvn2三位数字(加密)
+ customerInfoMap.put("expired", "1711"); //有效期 年在前月在后(加密)
+ * @param accNo customerInfoMap送了密码那么卡号必送,如果customerInfoMap未送密码PIN,此字段可以不送
+ * @param encoding 上送请求报文域encoding字段的值 + * @return base64后的持卡人信息域字段
+ */ + public static String getCustomerInfoWithEncrypt(Map customerInfoMap,String accNo,String encoding) { + if(customerInfoMap.isEmpty()) + return "{}"; + StringBuffer sf = new StringBuffer("{"); + //敏感信息加密域 + StringBuffer encryptedInfoSb = new StringBuffer(""); + + for(Iterator it = customerInfoMap.keySet().iterator(); it.hasNext();){ + String key = it.next(); + String value = customerInfoMap.get(key); + if(key.equals("phoneNo") || key.equals("cvn2") || key.equals("expired")){ + encryptedInfoSb.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND); + }else{ + if(key.equals("pin")){ + if(null == accNo || "".equals(accNo.trim())){ + LogUtil.writeLog("送了密码(PIN),必须在getCustomerInfoWithEncrypt参数中上传卡号"); + throw new RuntimeException("加密PIN没送卡号无法后续处理"); + }else{ + value = encryptPin(accNo,value,encoding); + } + } + sf.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND); + } + } + + if(!encryptedInfoSb.toString().equals("")){ + encryptedInfoSb.setLength(encryptedInfoSb.length()-1);//去掉最后一个&符号 + LogUtil.writeLog("组装的customerInfo encryptedInfo明文:"+ encryptedInfoSb.toString()); + sf.append("encryptedInfo").append(SDKConstants.EQUAL).append(encryptData(encryptedInfoSb.toString(), encoding)); + }else{ + sf.setLength(sf.length()-1); + } + + String customerInfo = sf.append("}").toString(); + LogUtil.writeLog("组装的customerInfo明文:"+customerInfo); + try { + return new String(SecureUtil.base64Encode(sf.toString().getBytes(encoding)),encoding); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return customerInfo; + } + + /** + * 解析返回报文(后台通知)中的customerInfo域:
+ * 解base64,如果带敏感信息加密 encryptedInfo 则将其解密并将 encryptedInfo中的域放到customerInfoMap返回
+ * @param customerInfo
+ * @param encoding
+ * @return + */ + public static Map parseCustomerInfo(String customerInfo,String encoding){ + Map customerInfoMap = null; + try { + byte[] b = SecureUtil.base64Decode(customerInfo.getBytes(encoding)); + String customerInfoNoBase64 = new String(b,encoding); + LogUtil.writeLog("解base64后===>" +customerInfoNoBase64); + //去掉前后的{} + customerInfoNoBase64 = customerInfoNoBase64.substring(1, customerInfoNoBase64.length()-1); + customerInfoMap = SDKUtil.parseQString(customerInfoNoBase64); + if(customerInfoMap.containsKey("encryptedInfo")){ + String encInfoStr = customerInfoMap.get("encryptedInfo"); + customerInfoMap.remove("encryptedInfo"); + String encryptedInfoStr = decryptData(encInfoStr, encoding); + Map encryptedInfoMap = SDKUtil.parseQString(encryptedInfoStr); + customerInfoMap.putAll(encryptedInfoMap); + } + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return customerInfoMap; + } + + /** + * 解析返回报文(后台通知)中的customerInfo域:
+ * 解base64,如果带敏感信息加密 encryptedInfo 则将其解密并将 encryptedInfo中的域放到customerInfoMap返回
+ * @param customerInfo
+ * @param encoding
+ * @return + */ + public static Map parseCustomerInfo(String customerInfo, String certPath, + String certPwd, String encoding){ + Map customerInfoMap = null; + try { + byte[] b = SecureUtil.base64Decode(customerInfo.getBytes(encoding)); + String customerInfoNoBase64 = new String(b,encoding); + LogUtil.writeLog("解base64后===>" +customerInfoNoBase64); + //去掉前后的{} + customerInfoNoBase64 = customerInfoNoBase64.substring(1, customerInfoNoBase64.length()-1); + customerInfoMap = SDKUtil.parseQString(customerInfoNoBase64); + if(customerInfoMap.containsKey("encryptedInfo")){ + String encInfoStr = customerInfoMap.get("encryptedInfo"); + customerInfoMap.remove("encryptedInfo"); + String encryptedInfoStr = decryptData(encInfoStr, certPath, certPwd, encoding); + Map encryptedInfoMap = SDKUtil.parseQString(encryptedInfoStr); + customerInfoMap.putAll(encryptedInfoMap); + } + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return customerInfoMap; + } + + /** + * 密码加密并做base64
+ * @param accNo 卡号
+ * @param pin 密码
+ * @param encoding
+ * @return 加密的内容
+ */ + public static String encryptPin(String accNo, String pin, String encoding) { + return SecureUtil.encryptPin(accNo, pin, encoding, CertUtil + .getEncryptCertPublicKey()); + } + + /** + * 敏感信息加密并做base64(卡号,手机号,cvn2,有效期)
+ * @param data 送 phoneNo,cvn2,有效期
+ * @param encoding
+ * @return 加密的密文
+ */ + public static String encryptData(String data, String encoding) { + return SecureUtil.encryptData(data, encoding, CertUtil + .getEncryptCertPublicKey()); + } + + /** + * 敏感信息解密,使用配置文件acp_sdk.properties解密
+ * @param base64EncryptedInfo 加密信息
+ * @param encoding
+ * @return 解密后的明文
+ */ + public static String decryptData(String base64EncryptedInfo, String encoding) { + return SecureUtil.decryptData(base64EncryptedInfo, encoding, CertUtil + .getSignCertPrivateKey()); + } + + /** + * 敏感信息解密,通过传入的私钥解密
+ * @param base64EncryptedInfo 加密信息
+ * @param certPath 私钥文件(带全路径)
+ * @param certPwd 私钥密码
+ * @param encoding
+ * @return + */ + public static String decryptData(String base64EncryptedInfo, String certPath, + String certPwd, String encoding) { + return SecureUtil.decryptData(base64EncryptedInfo, encoding, CertUtil + .getSignCertPrivateKeyByStoreMap(certPath, certPwd)); + } + + /** + * 5.0.0加密磁道信息,5.1.0接口请勿使用
+ * @param trackData 待加密磁道数据
+ * @param encoding 编码格式
+ * @return 加密的密文
+ * @deprecated + */ + public static String encryptTrack(String trackData, String encoding) { + return SecureUtil.encryptData(trackData, encoding, + CertUtil.getEncryptTrackPublicKey()); + } + + /** + * 获取敏感信息加密证书的物理序列号
+ * @return + */ + public static String getEncryptCertId(){ + return CertUtil.getEncryptCertId(); + } + + /** + * 对字符串做base64
+ * @param rawStr
+ * @param encoding
+ * @return
+ * @throws IOException + */ + public static String base64Encode(String rawStr,String encoding) throws IOException{ + byte [] rawByte = rawStr.getBytes(encoding); + return new String(SecureUtil.base64Encode(rawByte),encoding); + } + /** + * 对base64的字符串解base64
+ * @param base64Str
+ * @param encoding
+ * @return
+ * @throws IOException + */ + public static String base64Decode(String base64Str,String encoding) throws IOException{ + byte [] rawByte = base64Str.getBytes(encoding); + return new String(SecureUtil.base64Decode(rawByte),encoding); + } + + + /** + * + * 有卡交易信息域(cardTransData)构造
+ * 所有子域需用“{}”包含,子域间以“&”符号链接。格式如下:{子域名1=值&子域名2=值&子域名3=值}
+ * 说明:本示例仅供参考,开发时请根据接口文档中的报文要素组装
+ * + * @param cardTransDataMap cardTransData的数据
+ * @param requestData 必须包含merId、orderId、txnTime、txnAmt,磁道加密时需要使用
+ * @param encoding 编码
+ * @return + */ + public static String getCardTransData(Map cardTransDataMap, + Map requestData, + String encoding) { { + + StringBuffer cardTransDataBuffer = new StringBuffer(); + + if(cardTransDataMap.containsKey("track2Data")){ + StringBuffer track2Buffer = new StringBuffer(); + track2Buffer.append(requestData.get("merId")) + .append(SDKConstants.COLON).append(requestData.get("orderId")) + .append(SDKConstants.COLON).append(requestData.get("txnTime")) + .append(SDKConstants.COLON).append(requestData.get("txnAmt")==null?0:requestData.get("txnAmt")) + .append(SDKConstants.COLON).append(cardTransDataMap.get("track2Data")); + cardTransDataMap.put("track2Data", + AcpService.encryptData(track2Buffer.toString(), encoding)); + } + + if(cardTransDataMap.containsKey("track3Data")){ + StringBuffer track3Buffer = new StringBuffer(); + track3Buffer.append(requestData.get("merId")) + .append(SDKConstants.COLON).append(requestData.get("orderId")) + .append(SDKConstants.COLON).append(requestData.get("txnTime")) + .append(SDKConstants.COLON).append(requestData.get("txnAmt")==null?0:requestData.get("txnAmt")) + .append(SDKConstants.COLON).append(cardTransDataMap.get("track3Data")); + cardTransDataMap.put("track3Data", + AcpService.encryptData(track3Buffer.toString(), encoding)); + } + + return cardTransDataBuffer.append(SDKConstants.LEFT_BRACE) + .append(SDKUtil.coverMap2String(cardTransDataMap)) + .append(SDKConstants.RIGHT_BRACE).toString(); + } + + } + + /** + * 获取应答报文中的加密公钥证书,并存储到本地,备份原始证书,并自动替换证书
+ * 更新成功则返回1,无更新返回0,失败异常返回-1
+ * @param resData 返回报文 + * @param encoding + * @return + */ + public static int updateEncryptCert(Map resData, + String encoding) { + return SDKUtil.getEncryptCert(resData, encoding); + } + + /** + * 获取 + * @param number + * @return + */ + public static int genLuhn(String number){ + return SecureUtil.genLuhn(number); + } +} diff --git a/back-end_code/src/main/java/com/shop/union/service/BaseHttpSSLSocketFactory.java b/back-end_code/src/main/java/com/shop/union/service/BaseHttpSSLSocketFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..084f5708c58cd1fe27f6810aa270ca5d7f4ff673 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/service/BaseHttpSSLSocketFactory.java @@ -0,0 +1,123 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 SSLSocket 链接工具类(用于https) + * ============================================================================= + */ +package com.shop.union.service; + + +import com.shop.union.util.LogUtil; + +import javax.net.ssl.*; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; +import java.security.cert.X509Certificate; + +/** + * + * @ClassName BaseHttpSSLSocketFactory + * @Description 忽略验证ssl证书 + * @date 2016-7-22 下午4:10:14 + * + */ +public class BaseHttpSSLSocketFactory extends SSLSocketFactory { + private SSLContext getSSLContext() { + return createEasySSLContext(); + } + + @Override + public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, + int arg3) throws IOException { + return getSSLContext().getSocketFactory().createSocket(arg0, arg1, + arg2, arg3); + } + + @Override + public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3) + throws IOException, UnknownHostException { + return getSSLContext().getSocketFactory().createSocket(arg0, arg1, + arg2, arg3); + } + + @Override + public Socket createSocket(InetAddress arg0, int arg1) throws IOException { + return getSSLContext().getSocketFactory().createSocket(arg0, arg1); + } + + @Override + public Socket createSocket(String arg0, int arg1) throws IOException, + UnknownHostException { + return getSSLContext().getSocketFactory().createSocket(arg0, arg1); + } + + @Override + public String[] getSupportedCipherSuites() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String[] getDefaultCipherSuites() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Socket createSocket(Socket arg0, String arg1, int arg2, boolean arg3) + throws IOException { + return getSSLContext().getSocketFactory().createSocket(arg0, arg1, + arg2, arg3); + } + + private SSLContext createEasySSLContext() { + try { + SSLContext context = SSLContext.getInstance("SSL"); + context.init(null, + new TrustManager[] { MyX509TrustManager.manger }, null); + return context; + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return null; + } + } + + public static class MyX509TrustManager implements X509TrustManager { + + static MyX509TrustManager manger = new MyX509TrustManager(); + + public MyX509TrustManager() { + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + } + + /** + * 解决由于服务器证书问题导致HTTPS无法访问的情况 PS:HTTPS hostname wrong: should be + */ + public static class TrustAnyHostnameVerifier implements HostnameVerifier { + public boolean verify(String hostname, SSLSession session) { + //直接返回true + return true; + } + } +} diff --git a/back-end_code/src/main/java/com/shop/union/util/CertUtil.java b/back-end_code/src/main/java/com/shop/union/util/CertUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..6fd3846b3213faf4ffc0a5c55ab0095a2117fe68 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/util/CertUtil.java @@ -0,0 +1,761 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 证书工具类. + * ============================================================================= + */ +package com.shop.union.util; + +import com.shop.union.config.SDKConfig; + +import java.io.*; +import java.math.BigInteger; +import java.security.*; +import java.security.cert.*; +import java.security.spec.RSAPublicKeySpec; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +import static com.shop.union.constants.SDKConstants.UNIONPAY_CNNAME; + +/** + * @ClassName: CertUtil + * @Description: acpsdk证书工具类,主要用于对证书的加载和使用 + * @date 2016-7-22 下午2:46:20 + * + */ +public class CertUtil { + /** 证书容器,存储对商户请求报文签名私钥证书. */ + private static KeyStore keyStore = null; + /** 敏感信息加密公钥证书 */ + private static X509Certificate encryptCert = null; + /** 磁道加密公钥 */ + private static PublicKey encryptTrackKey = null; + /** 验证银联返回报文签名证书. */ + private static X509Certificate validateCert = null; + /** 验签中级证书 */ + private static X509Certificate middleCert = null; + /** 验签根证书 */ + private static X509Certificate rootCert = null; + /** 验证银联返回报文签名的公钥证书存储Map. */ + private static Map certMap = new HashMap(); + /** 商户私钥存储Map */ + private final static Map keyStoreMap = new ConcurrentHashMap(); + + + /** + * 初始化所有证书. + */ + public static void init() { + try { + addProvider();//向系统添加BC provider + initSignCert();//初始化签名私钥证书 + initMiddleCert();//初始化验签证书的中级证书 + initRootCert();//初始化验签证书的根证书 + initEncryptCert();//初始化加密公钥 + initTrackKey();//构建磁道加密公钥 + initValidateCertFromDir();//初始化所有的验签证书 + } catch (Exception e) { + LogUtil.writeErrorLog("init失败。(如果是用对称密钥签名的可无视此异常。)", e); + } + } + + /** + * 添加签名,验签,加密算法提供者 + */ + private static void addProvider(){ + if (Security.getProvider("BC") == null) { + LogUtil.writeLog("add BC provider"); + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + } else { + Security.removeProvider("BC"); //解决eclipse调试时tomcat自动重新加载时,BC存在不明原因异常的问题。 + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + LogUtil.writeLog("re-add BC provider"); + } + printSysInfo(); + } + + /** + * 用配置文件acp_sdk.properties中配置的私钥路径和密码 加载签名证书 + */ + private static void initSignCert() { + if(!"01".equals(SDKConfig.getConfig().getSignMethod())){ + LogUtil.writeLog("非rsa签名方式,不加载签名证书。"); + return; + } + if (SDKConfig.getConfig().getSignCertPath() == null + || SDKConfig.getConfig().getSignCertPwd() == null + || SDKConfig.getConfig().getSignCertType() == null) { + LogUtil.writeErrorLog("WARN: " + SDKConfig.SDK_SIGNCERT_PATH + "或" + SDKConfig.SDK_SIGNCERT_PWD + + "或" + SDKConfig.SDK_SIGNCERT_TYPE + "为空。 停止加载签名证书。"); + return; + } + if (null != keyStore) { + keyStore = null; + } + try { + keyStore = getKeyInfo(SDKConfig.getConfig().getSignCertPath(), + SDKConfig.getConfig().getSignCertPwd(), SDKConfig + .getConfig().getSignCertType()); + LogUtil.writeLog("InitSignCert Successful. CertId=[" + + getSignCertId() + "]"); + } catch (IOException e) { + LogUtil.writeErrorLog("InitSignCert Error", e); + } + } + + /** + * 用配置文件acp_sdk.properties配置路径 加载敏感信息加密证书 + */ + private static void initMiddleCert() { + LogUtil.writeLog("加载中级证书==>"+SDKConfig.getConfig().getMiddleCertPath()); + if (!SDKUtil.isEmpty(SDKConfig.getConfig().getMiddleCertPath())) { + middleCert = initCert(SDKConfig.getConfig().getMiddleCertPath()); + LogUtil.writeLog("Load MiddleCert Successful"); + } else { + LogUtil.writeLog("WARN: acpsdk.middle.path is empty"); + } + } + + /** + * 用配置文件acp_sdk.properties配置路径 加载敏感信息加密证书 + */ + private static void initRootCert() { + LogUtil.writeLog("加载根证书==>"+SDKConfig.getConfig().getRootCertPath()); + if (!SDKUtil.isEmpty(SDKConfig.getConfig().getRootCertPath())) { + rootCert = initCert(SDKConfig.getConfig().getRootCertPath()); + LogUtil.writeLog("Load RootCert Successful"); + } else { + LogUtil.writeLog("WARN: acpsdk.rootCert.path is empty"); + } + } + + /** + * 用配置文件acp_sdk.properties配置路径 加载银联公钥上级证书(中级证书) + */ + private static void initEncryptCert() { + LogUtil.writeLog("加载敏感信息加密证书==>"+SDKConfig.getConfig().getEncryptCertPath()); + if (!SDKUtil.isEmpty(SDKConfig.getConfig().getEncryptCertPath())) { + encryptCert = initCert(SDKConfig.getConfig().getEncryptCertPath()); + LogUtil.writeLog("Load EncryptCert Successful"); + } else { + LogUtil.writeLog("WARN: acpsdk.encryptCert.path is empty"); + } + } + + /** + * 用配置文件acp_sdk.properties配置路径 加载磁道公钥 + */ + private static void initTrackKey() { + if (!SDKUtil.isEmpty(SDKConfig.getConfig().getEncryptTrackKeyModulus()) + && !SDKUtil.isEmpty(SDKConfig.getConfig().getEncryptTrackKeyExponent())) { + encryptTrackKey = getPublicKey(SDKConfig.getConfig().getEncryptTrackKeyModulus(), + SDKConfig.getConfig().getEncryptTrackKeyExponent()); + LogUtil.writeLog("LoadEncryptTrackKey Successful"); + } else { + LogUtil.writeLog("WARN: acpsdk.encryptTrackKey.modulus or acpsdk.encryptTrackKey.exponent is empty"); + } + } + + /** + * 用配置文件acp_sdk.properties配置路径 加载验证签名证书 + */ + private static void initValidateCertFromDir() { + if(!"01".equals(SDKConfig.getConfig().getSignMethod())){ + LogUtil.writeLog("非rsa签名方式,不加载验签证书。"); + return; + } + certMap.clear(); + String dir = SDKConfig.getConfig().getValidateCertDir(); + LogUtil.writeLog("加载验证签名证书目录==>" + dir +" 注:如果请求报文中version=5.1.0那么此验签证书目录使用不到,可以不需要设置(version=5.0.0必须设置)。"); + if (SDKUtil.isEmpty(dir)) { + LogUtil.writeErrorLog("WARN: acpsdk.validateCert.dir is empty"); + return; + } + CertificateFactory cf = null; + FileInputStream in = null; + try { + cf = CertificateFactory.getInstance("X.509", "BC"); + File fileDir = new File(dir); + File[] files = fileDir.listFiles(new CerFilter()); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + in = new FileInputStream(file.getAbsolutePath()); + validateCert = (X509Certificate) cf.generateCertificate(in); + certMap.put(validateCert.getSerialNumber().toString(), + validateCert); + // 打印证书加载信息,供测试阶段调试 + LogUtil.writeLog("[" + file.getAbsolutePath() + "][CertId=" + + validateCert.getSerialNumber().toString() + "]"); + } + LogUtil.writeLog("LoadVerifyCert Successful"); + } catch (CertificateException e) { + LogUtil.writeErrorLog("LoadVerifyCert Error", e); + } catch (FileNotFoundException e) { + LogUtil.writeErrorLog("LoadVerifyCert Error File Not Found", e); + } catch (NoSuchProviderException e) { + LogUtil.writeErrorLog("LoadVerifyCert Error No BC Provider", e); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.toString()); + } + } + } + } + + /** + * 用给定的路径和密码 加载签名证书,并保存到certKeyStoreMap + * + * @param certFilePath + * @param certPwd + */ + private static void loadSignCert(String certFilePath, String certPwd) { + KeyStore keyStore = null; + try { + keyStore = getKeyInfo(certFilePath, certPwd, "PKCS12"); + keyStoreMap.put(certFilePath, keyStore); + LogUtil.writeLog("LoadRsaCert Successful"); + } catch (IOException e) { + LogUtil.writeErrorLog("LoadRsaCert Error", e); + } + } + + /** + * 通过证书路径初始化为公钥证书 + * @param path + * @return + */ + private static X509Certificate initCert(String path) { + X509Certificate encryptCertTemp = null; + CertificateFactory cf = null; + FileInputStream in = null; + //相对路径变为绝对路径 + path = getRealCertPath() + path; + try { + cf = CertificateFactory.getInstance("X.509", "BC"); + in = new FileInputStream(path); + encryptCertTemp = (X509Certificate) cf.generateCertificate(in); + // 打印证书加载信息,供测试阶段调试 + LogUtil.writeLog("[" + path + "][CertId=" + + encryptCertTemp.getSerialNumber().toString() + "]"); + } catch (CertificateException e) { + LogUtil.writeErrorLog("InitCert Error", e); + } catch (FileNotFoundException e) { + LogUtil.writeErrorLog("InitCert Error File Not Found", e); + } catch (NoSuchProviderException e) { + LogUtil.writeErrorLog("LoadVerifyCert Error No BC Provider", e); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.toString()); + } + } + } + return encryptCertTemp; + } + + /** + * 通过keyStore 获取私钥签名证书PrivateKey对象 + * + * @return + */ + public static PrivateKey getSignCertPrivateKey() { + try { + Enumeration aliasenum = keyStore.aliases(); + String keyAlias = null; + if (aliasenum.hasMoreElements()) { + keyAlias = aliasenum.nextElement(); + } + PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, + SDKConfig.getConfig().getSignCertPwd().toCharArray()); + return privateKey; + } catch (KeyStoreException e) { + LogUtil.writeErrorLog("getSignCertPrivateKey Error", e); + return null; + } catch (UnrecoverableKeyException e) { + LogUtil.writeErrorLog("getSignCertPrivateKey Error", e); + return null; + } catch (NoSuchAlgorithmException e) { + LogUtil.writeErrorLog("getSignCertPrivateKey Error", e); + return null; + } + } + /** + * 通过指定路径的私钥证书 获取PrivateKey对象 + * + * @return + */ + public static PrivateKey getSignCertPrivateKeyByStoreMap(String certPath, + String certPwd) { + if (!keyStoreMap.containsKey(certPath)) { + loadSignCert(certPath, certPwd); + } + try { + Enumeration aliasenum = keyStoreMap.get(certPath) + .aliases(); + String keyAlias = null; + if (aliasenum.hasMoreElements()) { + keyAlias = aliasenum.nextElement(); + } + PrivateKey privateKey = (PrivateKey) keyStoreMap.get(certPath) + .getKey(keyAlias, certPwd.toCharArray()); + return privateKey; + } catch (KeyStoreException e) { + LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e); + return null; + } catch (UnrecoverableKeyException e) { + LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e); + return null; + } catch (NoSuchAlgorithmException e) { + LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e); + return null; + } + } + + /** + * 获取敏感信息加密证书PublicKey + * + * @return + */ + public static PublicKey getEncryptCertPublicKey() { + if (null == encryptCert) { + String path = SDKConfig.getConfig().getEncryptCertPath(); + if (!SDKUtil.isEmpty(path)) { + encryptCert = initCert(path); + return encryptCert.getPublicKey(); + } else { + LogUtil.writeErrorLog("acpsdk.encryptCert.path is empty"); + return null; + } + } else { + return encryptCert.getPublicKey(); + } + } + + /** + * 重置敏感信息加密证书公钥 + */ + public static void resetEncryptCertPublicKey() { + encryptCert = null; + } + + /** + * 获取磁道加密证书PublicKey + * + * @return + */ + public static PublicKey getEncryptTrackPublicKey() { + if (null == encryptTrackKey) { + initTrackKey(); + } + return encryptTrackKey; + } + + /** + * 通过certId获取验签证书Map中对应证书PublicKey + * + * @param certId 证书物理序号 + * @return 通过证书编号获取到的公钥 + */ + public static PublicKey getValidatePublicKey(String certId) { + X509Certificate cf = null; + if (certMap.containsKey(certId)) { + // 存在certId对应的证书对象 + cf = certMap.get(certId); + return cf.getPublicKey(); + } else { + // 不存在则重新Load证书文件目录 + initValidateCertFromDir(); + if (certMap.containsKey(certId)) { + // 存在certId对应的证书对象 + cf = certMap.get(certId); + return cf.getPublicKey(); + } else { + LogUtil.writeErrorLog("缺少certId=[" + certId + "]对应的验签证书."); + return null; + } + } + } + + /** + * 获取配置文件acp_sdk.properties中配置的签名私钥证书certId + * + * @return 证书的物理编号 + */ + public static String getSignCertId() { + try { + Enumeration aliasenum = keyStore.aliases(); + String keyAlias = null; + if (aliasenum.hasMoreElements()) { + keyAlias = aliasenum.nextElement(); + } + X509Certificate cert = (X509Certificate) keyStore + .getCertificate(keyAlias); + return cert.getSerialNumber().toString(); + } catch (Exception e) { + LogUtil.writeErrorLog("getSignCertId Error", e); + return null; + } + } + + /** + * 获取敏感信息加密证书的certId + * + * @return + */ + public static String getEncryptCertId() { + if (null == encryptCert) { + String path = SDKConfig.getConfig().getEncryptCertPath(); + if (!SDKUtil.isEmpty(path)) { + encryptCert = initCert(path); + return encryptCert.getSerialNumber().toString(); + } else { + LogUtil.writeErrorLog("acpsdk.encryptCert.path is empty"); + return null; + } + } else { + return encryptCert.getSerialNumber().toString(); + } + } + + /** + * 将签名私钥证书文件读取为证书存储对象 + * + * @param pfxkeyfile + * 证书文件名 + * @param keypwd + * 证书密码 + * @param type + * 证书类型 + * @return 证书对象 + * @throws IOException + */ + private static KeyStore getKeyInfo(String pfxkeyfile, String keypwd, + String type) throws IOException { + LogUtil.writeLog("加载签名证书==>" + pfxkeyfile); + FileInputStream fis = null; + try { + KeyStore ks = KeyStore.getInstance(type, "BC"); + LogUtil.writeLog("Load RSA CertPath=[" + pfxkeyfile + "],Pwd=["+ keypwd + "],type=["+type+"]"); + + File file=new File(getRealCertPath() + pfxkeyfile); + fis = new FileInputStream(file); + char[] nPassword = null; + nPassword = null == keypwd || "".equals(keypwd.trim()) ? null: keypwd.toCharArray(); + if (null != ks) { + ks.load(fis, nPassword); + } + return ks; + } catch (Exception e) { + LogUtil.writeErrorLog("getKeyInfo Error", e); + return null; + } finally { + if(null!=fis) + fis.close(); + } + } + + /** + * 通过签名私钥证书路径,密码获取私钥证书certId + * @param certPath + * @param certPwd + * @return + */ + public static String getCertIdByKeyStoreMap(String certPath, String certPwd) { + if (!keyStoreMap.containsKey(certPath)) { + // 缓存中未查询到,则加载RSA证书 + loadSignCert(certPath, certPwd); + } + return getCertIdIdByStore(keyStoreMap.get(certPath)); + } + + /** + * 通过keystore获取私钥证书的certId值 + * @param keyStore + * @return + */ + private static String getCertIdIdByStore(KeyStore keyStore) { + Enumeration aliasenum = null; + try { + aliasenum = keyStore.aliases(); + String keyAlias = null; + if (aliasenum.hasMoreElements()) { + keyAlias = aliasenum.nextElement(); + } + X509Certificate cert = (X509Certificate) keyStore + .getCertificate(keyAlias); + return cert.getSerialNumber().toString(); + } catch (KeyStoreException e) { + LogUtil.writeErrorLog("getCertIdIdByStore Error", e); + return null; + } + } + + /** + * 使用模和指数生成RSA公钥 注意:此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同 + * + * @param modulus + * 模 + * @param exponent + * 指数 + * @return + */ + private static PublicKey getPublicKey(String modulus, String exponent) { + try { + BigInteger b1 = new BigInteger(modulus); + BigInteger b2 = new BigInteger(exponent); + KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); + RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); + return keyFactory.generatePublic(keySpec); + } catch (Exception e) { + LogUtil.writeErrorLog("构造RSA公钥失败:" + e); + return null; + } + } + + /** + * 将字符串转换为X509Certificate对象. + * + * @param x509CertString + * @return + */ + public static X509Certificate genCertificateByStr(String x509CertString) { + X509Certificate x509Cert = null; + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + InputStream tIn = new ByteArrayInputStream( + x509CertString.getBytes("ISO-8859-1")); + x509Cert = (X509Certificate) cf.generateCertificate(tIn); + } catch (Exception e) { + LogUtil.writeErrorLog("gen certificate error", e); + } + return x509Cert; + } + + /** + * 从配置文件acp_sdk.properties中获取验签公钥使用的中级证书 + * @return + */ + public static X509Certificate getMiddleCert() { + if (null == middleCert) { + String path = SDKConfig.getConfig().getMiddleCertPath(); + if (!SDKUtil.isEmpty(path)) { + initMiddleCert(); + } else { + LogUtil.writeErrorLog(SDKConfig.SDK_MIDDLECERT_PATH + " not set in " + SDKConfig.FILE_NAME); + return null; + } + } + return middleCert; + } + + /** + * 从配置文件acp_sdk.properties中获取验签公钥使用的根证书 + * @return + */ + public static X509Certificate getRootCert() { + if (null == rootCert) { + String path = SDKConfig.getConfig().getRootCertPath(); + if (!SDKUtil.isEmpty(path)) { + initRootCert(); + } else { + LogUtil.writeErrorLog(SDKConfig.SDK_ROOTCERT_PATH + " not set in " + SDKConfig.FILE_NAME); + return null; + } + } + return rootCert; + } + + /** + * 获取证书的CN + * @param aCert + * @return + */ + private static String getIdentitiesFromCertficate(X509Certificate aCert) { + String tDN = aCert.getSubjectDN().toString(); + String tPart = ""; + if ((tDN != null)) { + String tSplitStr[] = tDN.substring(tDN.indexOf("CN=")).split("@"); + if (tSplitStr != null && tSplitStr.length > 2 + && tSplitStr[2] != null) + tPart = tSplitStr[2]; + } + return tPart; + } + + /** + * 验证书链。 + * @param cert + * @return + */ + private static boolean verifyCertificateChain(X509Certificate cert){ + + if ( null == cert) { + LogUtil.writeErrorLog("cert must Not null"); + return false; + } + + X509Certificate middleCert = CertUtil.getMiddleCert(); + if (null == middleCert) { + LogUtil.writeErrorLog("middleCert must Not null"); + return false; + } + + X509Certificate rootCert = CertUtil.getRootCert(); + if (null == rootCert) { + LogUtil.writeErrorLog("rootCert or cert must Not null"); + return false; + } + + try { + + X509CertSelector selector = new X509CertSelector(); + selector.setCertificate(cert); + + Set trustAnchors = new HashSet(); + trustAnchors.add(new TrustAnchor(rootCert, null)); + PKIXBuilderParameters pkixParams = new PKIXBuilderParameters( + trustAnchors, selector); + + Set intermediateCerts = new HashSet(); + intermediateCerts.add(rootCert); + intermediateCerts.add(middleCert); + intermediateCerts.add(cert); + + pkixParams.setRevocationEnabled(false); + + CertStore intermediateCertStore = CertStore.getInstance("Collection", + new CollectionCertStoreParameters(intermediateCerts), "BC"); + pkixParams.addCertStore(intermediateCertStore); + + CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); + + @SuppressWarnings("unused") + PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder + .build(pkixParams); + LogUtil.writeLog("verify certificate chain succeed."); + return true; + } catch (CertPathBuilderException e){ + LogUtil.writeErrorLog("verify certificate chain fail.", e); + } catch (Exception e) { + LogUtil.writeErrorLog("verify certificate chain exception: ", e); + } + return false; + } + + /** + * 检查证书链 + * + * rootCerts + * 根证书 + * @param cert + * 待验证的证书 + * @return + */ + public static boolean verifyCertificate(X509Certificate cert) { + + if ( null == cert) { + LogUtil.writeErrorLog("cert must Not null"); + return false; + } + try { + cert.checkValidity();//验证有效期 +// cert.verify(middleCert.getPublicKey()); + if(!verifyCertificateChain(cert)){ + return false; + } + } catch (Exception e) { + LogUtil.writeErrorLog("verifyCertificate fail", e); + return false; + } + + if(SDKConfig.getConfig().isIfValidateCNName()){ + // 验证公钥是否属于银联 + if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert))) { + LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert)); + return false; + } + } else { + // 验证公钥是否属于银联 + if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert)) + && !"00040000:SIGN".equals(CertUtil.getIdentitiesFromCertficate(cert))) { + LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert)); + return false; + } + } + return true; + } + + /** + * 打印系统环境信息 + */ + private static void printSysInfo() { + LogUtil.writeLog("================= SYS INFO begin===================="); + LogUtil.writeLog("os_name:" + System.getProperty("os.name")); + LogUtil.writeLog("os_arch:" + System.getProperty("os.arch")); + LogUtil.writeLog("os_version:" + System.getProperty("os.version")); + LogUtil.writeLog("java_vm_specification_version:" + + System.getProperty("java.vm.specification.version")); + LogUtil.writeLog("java_vm_specification_vendor:" + + System.getProperty("java.vm.specification.vendor")); + LogUtil.writeLog("java_vm_specification_name:" + + System.getProperty("java.vm.specification.name")); + LogUtil.writeLog("java_vm_version:" + + System.getProperty("java.vm.version")); + LogUtil.writeLog("java_vm_name:" + System.getProperty("java.vm.name")); + LogUtil.writeLog("java.version:" + System.getProperty("java.version")); + LogUtil.writeLog("java.vm.vendor=[" + System.getProperty("java.vm.vendor") + "]"); + LogUtil.writeLog("java.version=[" + System.getProperty("java.version") + "]"); + printProviders(); + LogUtil.writeLog("================= SYS INFO end====================="); + } + + /** + * 打jre中印算法提供者列表 + */ + private static void printProviders() { + LogUtil.writeLog("Providers List:"); + Provider[] providers = Security.getProviders(); + for (int i = 0; i < providers.length; i++) { + LogUtil.writeLog(i + 1 + "." + providers[i].getName()); + } + } + + /** + * 证书文件过滤器 + * + */ + static class CerFilter implements FilenameFilter { + public boolean isCer(String name) { + if (name.toLowerCase().endsWith(".cer")) { + return true; + } else { + return false; + } + } + public boolean accept(File dir, String name) { + return isCer(name); + } + } + + private static String getRealCertPath(){ + String clazzPath=Thread.currentThread().getContextClassLoader().getResource("").getPath(); + clazzPath=clazzPath.replace("test-classes","classes"); + clazzPath=clazzPath.replace("/classes/","/classes"); + return clazzPath; + } +} diff --git a/back-end_code/src/main/java/com/shop/union/util/HttpClient.java b/back-end_code/src/main/java/com/shop/union/util/HttpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..5cabe1ce554ef4b5c0d74c741e719efb79ae601f --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/util/HttpClient.java @@ -0,0 +1,306 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 HTTP通信工具类 + * ============================================================================= + */ +package com.shop.union.util; + + +import com.shop.union.config.SDKConfig; +import com.shop.union.service.BaseHttpSSLSocketFactory; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.net.*; +import java.util.Map; +import java.util.Map.Entry; + +/** + * + * @ClassName HttpClient + * @Description acpsdk发送后台http请求类 + * @date 2016-7-22 下午4:03:25 + * + */ +public class HttpClient { + /** + * 目标地址 + */ + private URL url; + + /** + * 通信连接超时时间 + */ + private int connectionTimeout; + + /** + * 通信读超时时间 + */ + private int readTimeOut; + + /** + * 通信结果 + */ + private String result; + + /** + * 获取通信结果 + * @return + */ + public String getResult() { + return result; + } + + /** + * 设置通信结果 + * @param result + */ + public void setResult(String result) { + this.result = result; + } + + /** + * 构造函数 + * @param url 目标地址 + * @param connectionTimeout HTTP连接超时时间 + * @param readTimeOut HTTP读写超时时间 + */ + public HttpClient(String url, int connectionTimeout, int readTimeOut) { + try { + this.url = new URL(url); + this.connectionTimeout = connectionTimeout; + this.readTimeOut = readTimeOut; + } catch (MalformedURLException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + + /** + * 发送信息到服务端 + * @param data + * @param encoding + * @return + * @throws Exception + */ + public int send(Map data, String encoding) throws Exception { + try { + HttpURLConnection httpURLConnection = createConnection(encoding); + if (null == httpURLConnection) { + throw new Exception("Create httpURLConnection Failure"); + } + String sendData = this.getRequestParamString(data, encoding); + LogUtil.writeLog("请求报文:[" + sendData + "]"); + this.requestServer(httpURLConnection, sendData, + encoding); + this.result = this.response(httpURLConnection, encoding); + LogUtil.writeLog("Response message:[" + result + "]"); + return httpURLConnection.getResponseCode(); + } catch (Exception e) { + throw e; + } + } + + /** + * 发送信息到服务端 GET方式 + * @param encoding + * @return + * @throws Exception + */ + public int sendGet(String encoding) throws Exception { + try { + HttpURLConnection httpURLConnection = createConnectionGet(encoding); + if(null == httpURLConnection){ + throw new Exception("创建联接失败"); + } + this.result = this.response(httpURLConnection, encoding); + LogUtil.writeLog("同步返回报文:[" + result + "]"); + return httpURLConnection.getResponseCode(); + } catch (Exception e) { + throw e; + } + } + + + /** + * HTTP Post发送消息 + * + * @param connection + * @param message + * @throws IOException + */ + private void requestServer(final URLConnection connection, String message, String encoder) + throws Exception { + PrintStream out = null; + try { + connection.connect(); + out = new PrintStream(connection.getOutputStream(), false, encoder); + out.print(message); + out.flush(); + } catch (Exception e) { + throw e; + } finally { + if (null != out) { + out.close(); + } + } + } + + /** + * 显示Response消息 + * + * @param connection + * @param encoding + * @return + * @throws URISyntaxException + * @throws IOException + */ + private String response(final HttpURLConnection connection, String encoding) + throws URISyntaxException, IOException, Exception { + InputStream in = null; + StringBuilder sb = new StringBuilder(1024); + BufferedReader br = null; + try { + if (200 == connection.getResponseCode()) { + in = connection.getInputStream(); + sb.append(new String(read(in), encoding)); + } else { + in = connection.getErrorStream(); + sb.append(new String(read(in), encoding)); + } + LogUtil.writeLog("HTTP Return Status-Code:[" + + connection.getResponseCode() + "]"); + return sb.toString(); + } catch (Exception e) { + throw e; + } finally { + if (null != br) { + br.close(); + } + if (null != in) { + in.close(); + } + if (null != connection) { + connection.disconnect(); + } + } + } + + public static byte[] read(InputStream in) throws IOException { + byte[] buf = new byte[1024]; + int length = 0; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + while ((length = in.read(buf, 0, buf.length)) > 0) { + bout.write(buf, 0, length); + } + bout.flush(); + return bout.toByteArray(); + } + + /** + * 创建连接 + * + * @return + * @throws ProtocolException + */ + private HttpURLConnection createConnection(String encoding) throws ProtocolException { + HttpURLConnection httpURLConnection = null; + try { + httpURLConnection = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return null; + } + httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间 + httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间 + httpURLConnection.setDoInput(true); // 可读 + httpURLConnection.setDoOutput(true); // 可写 + httpURLConnection.setUseCaches(false);// 取消缓存 + httpURLConnection.setRequestProperty("Content-type", + "application/x-www-form-urlencoded;charset=" + encoding); + httpURLConnection.setRequestMethod("POST"); + if ("https".equalsIgnoreCase(url.getProtocol())) { + HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection; + //是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false + if(!SDKConfig.getConfig().isIfValidateRemoteCert()){ + husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory()); + husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况 + } + return husn; + } + return httpURLConnection; + } + + /** + * 创建连接 + * + * @return + * @throws ProtocolException + */ + private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException { + HttpURLConnection httpURLConnection = null; + try { + httpURLConnection = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return null; + } + httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间 + httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间 + httpURLConnection.setUseCaches(false);// 取消缓存 + httpURLConnection.setRequestProperty("Content-type", + "application/x-www-form-urlencoded;charset=" + encoding); + httpURLConnection.setRequestMethod("GET"); + if ("https".equalsIgnoreCase(url.getProtocol())) { + HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection; + //是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false + if(!SDKConfig.getConfig().isIfValidateRemoteCert()){ + husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory()); + husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况 + } + return husn; + } + return httpURLConnection; + } + + /** + * 将Map存储的对象,转换为key=value&key=value的字符 + * + * @param requestParam + * @param coder + * @return + */ + private String getRequestParamString(Map requestParam, String coder) { + if (null == coder || "".equals(coder)) { + coder = "UTF-8"; + } + StringBuffer sf = new StringBuffer(""); + String reqstr = ""; + if (null != requestParam && 0 != requestParam.size()) { + for (Entry en : requestParam.entrySet()) { + try { + sf.append(en.getKey() + + "=" + + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder + .encode(en.getValue(), coder)) + "&"); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return ""; + } + } + reqstr = sf.substring(0, sf.length() - 1); + } + LogUtil.writeLog("Request Message:[" + reqstr + "]"); + return reqstr; + } + +} diff --git a/back-end_code/src/main/java/com/shop/union/util/LogUtil.java b/back-end_code/src/main/java/com/shop/union/util/LogUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..dce7bf1cce7b06f01d0488e44b64da62f5461062 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/util/LogUtil.java @@ -0,0 +1,116 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 日志打印工具类 + * ============================================================================= + */ +package com.shop.union.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +/** + * + * @ClassName LogUtil + * @Description acpsdk日志工具类 + * @date 2016-7-22 下午4:04:35 + * + */ +public class LogUtil { + + private final static Logger GATELOG = LoggerFactory.getLogger("ACP_SDK_LOG"); + private final static Logger GATELOG_ERROR = LoggerFactory.getLogger("SDK_ERR_LOG"); + private final static Logger GATELOG_MESSAGE = LoggerFactory.getLogger("SDK_MSG_LOG"); + + final static String LOG_STRING_REQ_MSG_BEGIN = "============================== SDK REQ MSG BEGIN =============================="; + final static String LOG_STRING_REQ_MSG_END = "============================== SDK REQ MSG END =============================="; + final static String LOG_STRING_RSP_MSG_BEGIN = "============================== SDK RSP MSG BEGIN =============================="; + final static String LOG_STRING_RSP_MSG_END = "============================== SDK RSP MSG END =============================="; + + /** + * 记录普通日志 + * + * @param cont + */ + public static void writeLog(String cont) { + GATELOG.info(cont); + } + + /** + * 记录ERORR日志 + * + * @param cont + */ + public static void writeErrorLog(String cont) { + GATELOG_ERROR.error(cont); + } + + /** + * 记录ERROR日志 + * + * @param cont + * @param ex + */ + public static void writeErrorLog(String cont, Throwable ex) { + GATELOG_ERROR.error(cont, ex); + } + + /** + * 记录通信报文 + * + * @param msg + */ + public static void writeMessage(String msg) { + GATELOG_MESSAGE.info(msg); + } + + /** + * 打印请求报文 + * + * @param reqParam + */ + public static void printRequestLog(Map reqParam) { + writeMessage(LOG_STRING_REQ_MSG_BEGIN); + Iterator> it = reqParam.entrySet().iterator(); + while (it.hasNext()) { + Entry en = it.next(); + writeMessage("[" + en.getKey() + "] = [" + en.getValue() + "]"); + } + writeMessage(LOG_STRING_REQ_MSG_END); + } + + /** + * 打印响应报文. + * + * @param res + */ + public static void printResponseLog(String res) { + writeMessage(LOG_STRING_RSP_MSG_BEGIN); + writeMessage(res); + writeMessage(LOG_STRING_RSP_MSG_END); + } + + /** + * debug方法 + * + * @param cont + */ + public static void debug(String cont) { + if (GATELOG.isDebugEnabled()) { + GATELOG.debug(cont); + } + } +} diff --git a/back-end_code/src/main/java/com/shop/union/util/SDKUtil.java b/back-end_code/src/main/java/com/shop/union/util/SDKUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..be74b2a9b1e9800ffcf667e6cb87de35f8f93db3 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/util/SDKUtil.java @@ -0,0 +1,866 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 MPI工具类 + * ============================================================================= + */ +package com.shop.union.util; + +import com.shop.union.config.SDKConfig; +import com.shop.union.constants.SDKConstants; +import org.apache.commons.lang.StringUtils; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.security.cert.X509Certificate; +import java.util.*; +import java.util.Map.Entry; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +import static com.shop.union.constants.SDKConstants.*; + +/** + * + * @ClassName SDKUtil + * @Description acpsdk工具类 + * @date 2016-7-22 下午4:06:18 + * + */ +public class SDKUtil { + + /** + * 根据signMethod的值,提供三种计算签名的方法 + * + * @param data + * 待签名数据Map键值对形式 + * @param encoding + * 编码 + * @return 签名是否成功 + */ + public static boolean sign(Map data, String encoding) { + + if (isEmpty(encoding)) { + encoding = "UTF-8"; + } + String signMethod = data.get(param_signMethod); + String version = data.get(SDKConstants.param_version); + if (!VERSION_1_0_0.equals(version) && !VERSION_5_0_1.equals(version) && isEmpty(signMethod)) { + LogUtil.writeErrorLog("signMethod must Not null"); + return false; + } + + if (isEmpty(version)) { + LogUtil.writeErrorLog("version must Not null"); + return false; + } + if (SIGNMETHOD_RSA.equals(signMethod)|| VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + if (VERSION_5_0_0.equals(version)|| VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + // 设置签名证书序列号 + data.put(SDKConstants.param_certId, CertUtil.getSignCertId()); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + byte[] byteSign = null; + String stringSign = null; + try { + // 通过SHA1进行摘要并转16进制 + byte[] signDigest = SecureUtil + .sha1X16(stringData, encoding); + byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft( + CertUtil.getSignCertPrivateKey(), signDigest)); + stringSign = new String(byteSign); + // 设置签名域值 + data.put(SDKConstants.param_signature, stringSign); + return true; + } catch (Exception e) { + LogUtil.writeErrorLog("Sign Error", e); + return false; + } + } else if (VERSION_5_1_0.equals(version)) { + // 设置签名证书序列号 + data.put(SDKConstants.param_certId, CertUtil.getSignCertId()); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + byte[] byteSign = null; + String stringSign = null; + try { + // 通过SHA256进行摘要并转16进制 + byte[] signDigest = SecureUtil + .sha256X16(stringData, encoding); + byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft256( + CertUtil.getSignCertPrivateKey(), signDigest)); + stringSign = new String(byteSign); + // 设置签名域值 + data.put(SDKConstants.param_signature, stringSign); + return true; + } catch (Exception e) { + LogUtil.writeErrorLog("Sign Error", e); + return false; + } + } + } else if (SIGNMETHOD_SHA256.equals(signMethod)) { + return signBySecureKey(data, SDKConfig.getConfig() + .getSecureKey(), encoding); + } else if (SIGNMETHOD_SM3.equals(signMethod)) { + return signBySecureKey(data, SDKConfig.getConfig() + .getSecureKey(), encoding); + } + return false; + } + + /** + * 通过传入的证书绝对路径和证书密码读取签名证书进行签名并返回签名值
+ * + * @param data + * 待签名数据Map键值对形式 + * @param encoding + * 编码 + * @param secureKey + * 证书绝对路径 + * @para certPwd + * 证书密码 + * @return 签名值 + */ + public static boolean signBySecureKey(Map data, String secureKey, + String encoding) { + + if (isEmpty(encoding)) { + encoding = "UTF-8"; + } + if (isEmpty(secureKey)) { + LogUtil.writeErrorLog("secureKey is empty"); + return false; + } + String signMethod = data.get(param_signMethod); + if (isEmpty(signMethod)) { + LogUtil.writeErrorLog("signMethod must Not null"); + return false; + } + + if (SIGNMETHOD_SHA256.equals(signMethod)) { + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + String strBeforeSha256 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sha256X16Str(secureKey, encoding); + String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256, + encoding); + // 设置签名域值 + data.put(SDKConstants.param_signature, strAfterSha256); + return true; + } else if (SIGNMETHOD_SM3.equals(signMethod)) { + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + String strBeforeSM3 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sm3X16Str(secureKey, encoding); + String strAfterSM3 = SecureUtil.sm3X16Str(strBeforeSM3, encoding); + // 设置签名域值 + data.put(SDKConstants.param_signature, strAfterSM3); + return true; + } + return false; + } + + /** + * 通过传入的签名密钥进行签名并返回签名值
+ * + * @param data + * 待签名数据Map键值对形式 + * @param encoding + * 编码 + * @param certPath + * 证书绝对路径 + * @param certPwd + * 证书密码 + * @return 签名值 + */ + public static boolean signByCertInfo(Map data, + String certPath, String certPwd, String encoding) { + + if (isEmpty(encoding)) { + encoding = "UTF-8"; + } + if (isEmpty(certPath) || isEmpty(certPwd)) { + LogUtil.writeErrorLog("CertPath or CertPwd is empty"); + return false; + } + String signMethod = data.get(param_signMethod); + String version = data.get(SDKConstants.param_version); + if (!VERSION_1_0_0.equals(version) && !VERSION_5_0_1.equals(version) && isEmpty(signMethod)) { + LogUtil.writeErrorLog("signMethod must Not null"); + return false; + } + if (isEmpty(version)) { + LogUtil.writeErrorLog("version must Not null"); + return false; + } + + if (SIGNMETHOD_RSA.equals(signMethod) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + if (VERSION_5_0_0.equals(version) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + // 设置签名证书序列号 + data.put(SDKConstants.param_certId, CertUtil.getCertIdByKeyStoreMap(certPath, certPwd)); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + byte[] byteSign = null; + String stringSign = null; + try { + // 通过SHA1进行摘要并转16进制 + byte[] signDigest = SecureUtil + .sha1X16(stringData, encoding); + byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft( + CertUtil.getSignCertPrivateKeyByStoreMap(certPath, certPwd), signDigest)); + stringSign = new String(byteSign); + // 设置签名域值 + data.put(SDKConstants.param_signature, stringSign); + return true; + } catch (Exception e) { + LogUtil.writeErrorLog("Sign Error", e); + return false; + } + } else if (VERSION_5_1_0.equals(version)) { + // 设置签名证书序列号 + data.put(SDKConstants.param_certId, CertUtil.getCertIdByKeyStoreMap(certPath, certPwd)); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(data); + LogUtil.writeLog("待签名请求报文串:[" + stringData + "]"); + byte[] byteSign = null; + String stringSign = null; + try { + // 通过SHA256进行摘要并转16进制 + byte[] signDigest = SecureUtil + .sha256X16(stringData, encoding); + byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft256( + CertUtil.getSignCertPrivateKeyByStoreMap(certPath, certPwd), signDigest)); + stringSign = new String(byteSign); + // 设置签名域值 + data.put(SDKConstants.param_signature, stringSign); + return true; + } catch (Exception e) { + LogUtil.writeErrorLog("Sign Error", e); + return false; + } + } + + } + return false; + } + + /** + * 验证签名 + * + * @param resData + * 返回报文数据 + * @param encoding + * 编码格式 + * @return + */ + public static boolean validateBySecureKey(Map resData, String secureKey, String encoding) { + LogUtil.writeLog("验签处理开始"); + if (isEmpty(encoding)) { + encoding = "UTF-8"; + } + String signMethod = resData.get(SDKConstants.param_signMethod); + if (SIGNMETHOD_SHA256.equals(signMethod)) { + // 1.进行SHA256验证 + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + String strBeforeSha256 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sha256X16Str(secureKey, encoding); + String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256, + encoding); + return stringSign.equals(strAfterSha256); + } else if (SIGNMETHOD_SM3.equals(signMethod)) { + // 1.进行SM3验证 + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + String strBeforeSM3 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sm3X16Str(secureKey, encoding); + String strAfterSM3 = SecureUtil + .sm3X16Str(strBeforeSM3, encoding); + return stringSign.equals(strAfterSM3); + } + return false; + } + + /** + * 验证签名 + * + * @param resData + * 返回报文数据 + * @param encoding + * 编码格式 + * @return + */ + public static boolean validate(Map resData, String encoding) { + LogUtil.writeLog("验签处理开始"); + if (isEmpty(encoding)) { + encoding = "UTF-8"; + } + String signMethod = resData.get(SDKConstants.param_signMethod); + String version = resData.get(SDKConstants.param_version); + if (SIGNMETHOD_RSA.equals(signMethod) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + // 获取返回报文的版本号 + if (VERSION_5_0_0.equals(version) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) { + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 从返回报文中获取certId ,然后去证书静态Map中查询对应验签证书对象 + String certId = resData.get(SDKConstants.param_certId); + LogUtil.writeLog("对返回报文串验签使用的验签公钥序列号:["+certId+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + try { + // 验证签名需要用银联发给商户的公钥证书. + return SecureUtil.validateSignBySoft(CertUtil + .getValidatePublicKey(certId), SecureUtil + .base64Decode(stringSign.getBytes(encoding)), + SecureUtil.sha1X16(stringData, encoding)); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } else if (VERSION_5_1_0.equals(version)) { + // 1.从返回报文中获取公钥信息转换成公钥对象 + String strCert = resData.get(SDKConstants.param_signPubKeyCert); +// LogUtil.writeLog("验签公钥证书:["+strCert+"]"); + X509Certificate x509Cert = CertUtil.genCertificateByStr(strCert); + if(x509Cert == null) { + LogUtil.writeErrorLog("convert signPubKeyCert failed"); + return false; + } + // 2.验证证书链 + if (!CertUtil.verifyCertificate(x509Cert)) { + LogUtil.writeErrorLog("验证公钥证书失败,证书信息:["+strCert+"]"); + return false; + } + + // 3.验签 + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + try { + // 验证签名需要用银联发给商户的公钥证书. + boolean result = SecureUtil.validateSignBySoft256(x509Cert + .getPublicKey(), SecureUtil.base64Decode(stringSign + .getBytes(encoding)), SecureUtil.sha256X16( + stringData, encoding)); + LogUtil.writeLog("验证签名" + (result? "成功":"失败")); + return result; + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + } + + } else if (SIGNMETHOD_SHA256.equals(signMethod)) { + // 1.进行SHA256验证 + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + String strBeforeSha256 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sha256X16Str(SDKConfig.getConfig() + .getSecureKey(), encoding); + String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256, + encoding); + boolean result = stringSign.equals(strAfterSha256); + LogUtil.writeLog("验证签名" + (result? "成功":"失败")); + return result; + } else if (SIGNMETHOD_SM3.equals(signMethod)) { + // 1.进行SM3验证 + String stringSign = resData.get(SDKConstants.param_signature); + LogUtil.writeLog("签名原文:["+stringSign+"]"); + // 将Map信息转换成key1=value1&key2=value2的形式 + String stringData = coverMap2String(resData); + LogUtil.writeLog("待验签返回报文串:["+stringData+"]"); + String strBeforeSM3 = stringData + + SDKConstants.AMPERSAND + + SecureUtil.sm3X16Str(SDKConfig.getConfig() + .getSecureKey(), encoding); + String strAfterSM3 = SecureUtil + .sm3X16Str(strBeforeSM3, encoding); + boolean result = stringSign.equals(strAfterSM3); + LogUtil.writeLog("验证签名" + (result? "成功":"失败")); + return result; + } + return false; + } + + /** + * 将Map中的数据转换成key1=value1&key2=value2的形式 不包含签名域signature + * + * @param data + * 待拼接的Map数据 + * @return 拼接好后的字符串 + */ + public static String coverMap2String(Map data) { + TreeMap tree = new TreeMap(); + Iterator> it = data.entrySet().iterator(); + while (it.hasNext()) { + Entry en = it.next(); + if (SDKConstants.param_signature.equals(en.getKey().trim())) { + continue; + } + tree.put(en.getKey(), en.getValue()); + } + it = tree.entrySet().iterator(); + StringBuffer sf = new StringBuffer(); + while (it.hasNext()) { + Entry en = it.next(); + sf.append(en.getKey() + SDKConstants.EQUAL + en.getValue() + + SDKConstants.AMPERSAND); + } + return sf.substring(0, sf.length() - 1); + } + + + /** + * 兼容老方法 将形如key=value&key=value的字符串转换为相应的Map对象 + * + * @param result + * @return + */ + public static Map coverResultString2Map(String result) { + return convertResultStringToMap(result); + } + + /** + * 将形如key=value&key=value的字符串转换为相应的Map对象 + * + * @param result + * @return + */ + public static Map convertResultStringToMap(String result) { + Map map =null; + try { + + if (StringUtils.isNotBlank(result)) { + if (result.startsWith("{") && result.endsWith("}")) { + result = result.substring(1, result.length() - 1); + } + map = parseQString(result); + } + + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + } + return map; + } + + + /** + * 解析应答字符串,生成应答要素 + * + * @param str + * 需要解析的字符串 + * @return 解析的结果map + * @throws UnsupportedEncodingException + */ + public static Map parseQString(String str) + throws UnsupportedEncodingException { + + Map map = new HashMap(); + int len = str.length(); + StringBuilder temp = new StringBuilder(); + char curChar; + String key = null; + boolean isKey = true; + boolean isOpen = false;//值里有嵌套 + char openName = 0; + if(len>0){ + for (int i = 0; i < len; i++) {// 遍历整个带解析的字符串 + curChar = str.charAt(i);// 取当前字符 + if (isKey) {// 如果当前生成的是key + + if (curChar == '=') {// 如果读取到=分隔符 + key = temp.toString(); + temp.setLength(0); + isKey = false; + } else { + temp.append(curChar); + } + } else {// 如果当前生成的是value + if(isOpen){ + if(curChar == openName){ + isOpen = false; + } + + }else{//如果没开启嵌套 + if(curChar == '{'){//如果碰到,就开启嵌套 + isOpen = true; + openName ='}'; + } + if(curChar == '['){ + isOpen = true; + openName =']'; + } + } + if (curChar == '&' && !isOpen) {// 如果读取到&分割符,同时这个分割符不是值域,这时将map里添加 + putKeyValueToMap(temp, isKey, key, map); + temp.setLength(0); + isKey = true; + }else{ + temp.append(curChar); + } + } + + } + putKeyValueToMap(temp, isKey, key, map); + } + return map; + } + + private static void putKeyValueToMap(StringBuilder temp, boolean isKey, + String key, Map map) + throws UnsupportedEncodingException { + if (isKey) { + key = temp.toString(); + if (key.length() == 0) { + throw new RuntimeException("QString format illegal"); + } + map.put(key, ""); + } else { + if (key.length() == 0) { + throw new RuntimeException("QString format illegal"); + } + map.put(key, temp.toString()); + } + } + + /** + * + * 获取应答报文中的加密公钥证书,并存储到本地,并备份原始证书
+ * 更新成功则返回1,无更新返回0,失败异常返回-1。 + * + * @param resData + * @param encoding + * @return + */ + public static int getEncryptCert(Map resData, + String encoding) { + String strCert = resData.get(SDKConstants.param_encryptPubKeyCert); + String certType = resData.get(SDKConstants.param_certType); + if (isEmpty(strCert) || isEmpty(certType)) + return -1; + X509Certificate x509Cert = CertUtil.genCertificateByStr(strCert); + if (CERTTYPE_01.equals(certType)) { + // 更新敏感信息加密公钥 + if (!CertUtil.getEncryptCertId().equals( + x509Cert.getSerialNumber().toString())) { + // ID不同时进行本地证书更新操作 + String localCertPath = SDKConfig.getConfig().getEncryptCertPath(); + String newLocalCertPath = genBackupName(localCertPath); + // 1.将本地证书进行备份存储 + if (!copyFile(localCertPath, newLocalCertPath)) + return -1; + // 2.备份成功,进行新证书的存储 + if (!writeFile(localCertPath, strCert, encoding)) + return -1; + LogUtil.writeLog("save new encryptPubKeyCert success"); + CertUtil.resetEncryptCertPublicKey(); + return 1; + }else { + return 0; + } + + } else if (CERTTYPE_02.equals(certType)) { +// // 更新磁道加密公钥 +// if (!CertUtil.getEncryptTrackCertId().equals( +// x509Cert.getSerialNumber().toString())) { +// // ID不同时进行本地证书更新操作 +// String localCertPath = SDKConfig.getConfig().getEncryptTrackCertPath(); +// String newLocalCertPath = genBackupName(localCertPath); +// // 1.将本地证书进行备份存储 +// if (!copyFile(localCertPath, newLocalCertPath)) +// return -1; +// // 2.备份成功,进行新证书的存储 +// if (!writeFile(localCertPath, strCert, encoding)) +// return -1; +// LogUtil.writeLog("save new encryptPubKeyCert success"); +// CertUtil.resetEncryptTrackCertPublicKey(); +// return 1; +// }else { + return 0; +// } + }else { + LogUtil.writeLog("unknown cerType:"+certType); + return -1; + } + } + + /** + * 文件拷贝方法 + * + * @param srcFile + * 源文件 + * @param destFile + * 目标文件 + * @return + * @throws IOException + */ + public static boolean copyFile(String srcFile, String destFile) { + boolean flag = false; + FileInputStream fin = null; + FileOutputStream fout = null; + FileChannel fcin = null; + FileChannel fcout = null; + try { + // 获取源文件和目标文件的输入输出流 + fin = new FileInputStream(srcFile); + fout = new FileOutputStream(destFile); + // 获取输入输出通道 + fcin = fin.getChannel(); + fcout = fout.getChannel(); + // 创建缓冲区 + ByteBuffer buffer = ByteBuffer.allocate(1024); + while (true) { + // clear方法重设缓冲区,使它可以接受读入的数据 + buffer.clear(); + // 从输入通道中将数据读到缓冲区 + int r = fcin.read(buffer); + // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1 + if (r == -1) { + flag = true; + break; + } + // flip方法让缓冲区可以将新读入的数据写入另一个通道 + buffer.flip(); + // 从输出通道中将数据写入缓冲区 + fcout.write(buffer); + } + fout.flush(); + } catch (IOException e) { + LogUtil.writeErrorLog("CopyFile fail", e); + } finally { + try { + if (null != fin) + fin.close(); + if (null != fout) + fout.close(); + if (null != fcin) + fcin.close(); + if (null != fcout) + fcout.close(); + } catch (IOException ex) { + LogUtil.writeErrorLog("Releases any system resources fail", ex); + } + } + return flag; + } + + /** + * 写文件方法 + * + * @param filePath + * 文件路径 + * @param fileContent + * 文件内容 + * @param encoding + * 编码 + * @return + */ + public static boolean writeFile(String filePath, String fileContent, + String encoding) { + FileOutputStream fout = null; + FileChannel fcout = null; + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + + try { + fout = new FileOutputStream(filePath); + // 获取输出通道 + fcout = fout.getChannel(); + // 创建缓冲区 + // ByteBuffer buffer = ByteBuffer.allocate(1024); + ByteBuffer buffer = ByteBuffer.wrap(fileContent.getBytes(encoding)); + fcout.write(buffer); + fout.flush(); + } catch (FileNotFoundException e) { + LogUtil.writeErrorLog("WriteFile fail", e); + return false; + } catch (IOException ex) { + LogUtil.writeErrorLog("WriteFile fail", ex); + return false; + } finally { + try { + if (null != fout) + fout.close(); + if (null != fcout) + fcout.close(); + } catch (IOException ex) { + LogUtil.writeErrorLog("Releases any system resources fail", ex); + return false; + } + } + return true; + } + + /** + * 将传入的文件名(xxx)改名
+ * 结果为: xxx_backup.cer + * + * @param fileName + * @return + */ + public static String genBackupName(String fileName) { + if (isEmpty(fileName)) + return ""; + int i = fileName.lastIndexOf(POINT); + String leftFileName = fileName.substring(0, i); + String rightFileName = fileName.substring(i + 1); + String newFileName = leftFileName + "_backup" + POINT + rightFileName; + return newFileName; + } + + + public static byte[] readFileByNIO(String filePath) { + FileInputStream in = null; + FileChannel fc = null; + ByteBuffer bf = null; + try { + in = new FileInputStream(filePath); + fc = in.getChannel(); + bf = ByteBuffer.allocate((int) fc.size()); + fc.read(bf); + return bf.array(); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage()); + return null; + } finally { + try { + if (null != fc) { + fc.close(); + } + if (null != in) { + in.close(); + } + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage()); + return null; + } + } + } + + /** + * 过滤请求报文中的空字符串或者空字符串 + * @param contentData + * @return + */ + public static Map filterBlank(Map contentData){ + LogUtil.writeLog("打印请求报文域 :"); + Map submitFromData = new HashMap(); + Set keyset = contentData.keySet(); + + for(String key:keyset){ + String value = contentData.get(key); + if (StringUtils.isNotBlank(value)) { + // 对value值进行去除前后空处理 + submitFromData.put(key, value.trim()); + LogUtil.writeLog(key + "-->" + String.valueOf(value)); + } + } + return submitFromData; + } + + /** + * 解压缩. + * + * @param inputByte + * byte[]数组类型的数据 + * @return 解压缩后的数据 + * @throws IOException + */ + public static byte[] inflater(final byte[] inputByte) throws IOException { + int compressedDataLength = 0; + Inflater compresser = new Inflater(false); + compresser.setInput(inputByte, 0, inputByte.length); + ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length); + byte[] result = new byte[1024]; + try { + while (!compresser.finished()) { + compressedDataLength = compresser.inflate(result); + if (compressedDataLength == 0) { + break; + } + o.write(result, 0, compressedDataLength); + } + } catch (Exception ex) { + System.err.println("Data format error!\n"); + ex.printStackTrace(); + } finally { + o.close(); + } + compresser.end(); + return o.toByteArray(); + } + + /** + * 压缩. + * + * @param inputByte + * 需要解压缩的byte[]数组 + * @return 压缩后的数据 + * @throws IOException + */ + public static byte[] deflater(final byte[] inputByte) throws IOException { + int compressedDataLength = 0; + Deflater compresser = new Deflater(); + compresser.setInput(inputByte); + compresser.finish(); + ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length); + byte[] result = new byte[1024]; + try { + while (!compresser.finished()) { + compressedDataLength = compresser.deflate(result); + o.write(result, 0, compressedDataLength); + } + } finally { + o.close(); + } + compresser.end(); + return o.toByteArray(); + } + + /** + * 判断字符串是否为NULL或空 + * + * @param s + * 待判断的字符串数据 + * @return 判断结果 true-是 false-否 + */ + public static boolean isEmpty(String s) { + return null == s || "".equals(s.trim()); + } + +} diff --git a/back-end_code/src/main/java/com/shop/union/util/SecureUtil.java b/back-end_code/src/main/java/com/shop/union/util/SecureUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..c285c39cd1fb7b1ca03a39068a0eccd8de414886 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/union/util/SecureUtil.java @@ -0,0 +1,577 @@ +/** + * + * Licensed Property to China UnionPay Co., Ltd. + * + * (C) Copyright of China UnionPay Co., Ltd. 2010 + * All Rights Reserved. + * + * + * Modification History: + * ============================================================================= + * Author Date Description + * ------------ ---------- --------------------------------------------------- + * xshu 2014-05-28 报文加密解密等操作的工具类 + * ============================================================================= + */ +package com.shop.union.util; + +import org.apache.commons.codec.binary.Base64; +import org.bouncycastle.crypto.digests.SM3Digest; + +import javax.crypto.Cipher; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; + +/** + * + * @ClassName SecureUtil + * @Description acpsdk安全算法工具类 + * @date 2016-7-22 下午4:08:32 + * + */ +public class SecureUtil { + /** + * 算法常量: SHA1 + */ + private static final String ALGORITHM_SHA1 = "SHA-1"; + /** + * 算法常量: SHA256 + */ + private static final String ALGORITHM_SHA256 = "SHA-256"; + /** + * 算法常量:SHA1withRSA + */ + private static final String BC_PROV_ALGORITHM_SHA1RSA = "SHA1withRSA"; + /** + * 算法常量:SHA256withRSA + */ + private static final String BC_PROV_ALGORITHM_SHA256RSA = "SHA256withRSA"; + + /** + * sm3计算后进行16进制转换 + * + * @param data + * 待计算的数据 + * @param encoding + * 编码 + * @return 计算结果 + */ + public static String sm3X16Str(String data, String encoding) { + byte[] bytes = sm3(data, encoding); + StringBuilder sm3StrBuff = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + if (Integer.toHexString(0xFF & bytes[i]).length() == 1) { + sm3StrBuff.append("0").append( + Integer.toHexString(0xFF & bytes[i])); + } else { + sm3StrBuff.append(Integer.toHexString(0xFF & bytes[i])); + } + } + return sm3StrBuff.toString(); + } + + /** + * sha1计算后进行16进制转换 + * + * @param data + * 待计算的数据 + * @param encoding + * 编码 + * @return 计算结果 + */ + public static byte[] sha1X16(String data, String encoding) { + byte[] bytes = sha1(data, encoding); + StringBuilder sha1StrBuff = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + if (Integer.toHexString(0xFF & bytes[i]).length() == 1) { + sha1StrBuff.append("0").append( + Integer.toHexString(0xFF & bytes[i])); + } else { + sha1StrBuff.append(Integer.toHexString(0xFF & bytes[i])); + } + } + try { + return sha1StrBuff.toString().getBytes(encoding); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return null; + } + } + + + /** + * sha256计算后进行16进制转换 + * + * @param data + * 待计算的数据 + * @param encoding + * 编码 + * @return 计算结果 + */ + public static String sha256X16Str(String data, String encoding) { + byte[] bytes = sha256(data, encoding); + StringBuilder sha256StrBuff = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + if (Integer.toHexString(0xFF & bytes[i]).length() == 1) { + sha256StrBuff.append("0").append( + Integer.toHexString(0xFF & bytes[i])); + } else { + sha256StrBuff.append(Integer.toHexString(0xFF & bytes[i])); + } + } + return sha256StrBuff.toString(); + } + + /** + * sha256计算后进行16进制转换 + * + * @param data + * 待计算的数据 + * @param encoding + * 编码 + * @return 计算结果 + */ + public static byte[] sha256X16(String data, String encoding) { + byte[] bytes = sha256(data, encoding); + StringBuilder sha256StrBuff = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + if (Integer.toHexString(0xFF & bytes[i]).length() == 1) { + sha256StrBuff.append("0").append( + Integer.toHexString(0xFF & bytes[i])); + } else { + sha256StrBuff.append(Integer.toHexString(0xFF & bytes[i])); + } + } + try { + return sha256StrBuff.toString().getBytes(encoding); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return null; + } + } + + /** + * sha1计算. + * + * @param data + * 待计算的数据 + * @return 计算结果 + */ + private static byte[] sha1(byte[] data) { + MessageDigest md = null; + try { + md = MessageDigest.getInstance(ALGORITHM_SHA1); + md.reset(); + md.update(data); + return md.digest(); + } catch (Exception e) { + LogUtil.writeErrorLog("SHA1计算失败", e); + return null; + } + } + + /** + * sha256计算. + * + * @param data + * 待计算的数据 + * @return 计算结果 + */ + private static byte[] sha256(byte[] data) { + MessageDigest md = null; + try { + md = MessageDigest.getInstance(ALGORITHM_SHA256); + md.reset(); + md.update(data); + return md.digest(); + } catch (Exception e) { + LogUtil.writeErrorLog("SHA256计算失败", e); + return null; + } + } + + /** + * SM3计算. + * + * @param data + * 待计算的数据 + * @return 计算结果 + */ + private static byte[] sm3(byte[] data) { + SM3Digest sm3 = new SM3Digest(); + sm3.update(data, 0, data.length); + byte[] result = new byte[sm3.getDigestSize()]; + sm3.doFinal(result, 0); + return result; + } + + /** + * sha1计算 + * + * @param datas + * 待计算的数据 + * @param encoding + * 字符集编码 + * @return + */ + private static byte[] sha1(String datas, String encoding) { + try { + return sha1(datas.getBytes(encoding)); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog("SHA1计算失败", e); + return null; + } + } + + /** + * sha256计算 + * + * @param datas + * 待计算的数据 + * @param encoding + * 字符集编码 + * @return + */ + private static byte[] sha256(String datas, String encoding) { + try { + return sha256(datas.getBytes(encoding)); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog("SHA256计算失败", e); + return null; + } + } + + /** + * sm3计算 + * + * @param datas + * 待计算的数据 + * @param encoding + * 字符集编码 + * @return + */ + private static byte[] sm3(String datas, String encoding) { + try { + return sm3(datas.getBytes(encoding)); + } catch (UnsupportedEncodingException e) { + LogUtil.writeErrorLog("SM3计算失败", e); + return null; + } + } + + /** + * + * @param privateKey + * @param data + * @return + * @throws Exception + */ + public static byte[] signBySoft(PrivateKey privateKey, byte[] data) + throws Exception { + byte[] result = null; + Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC"); + st.initSign(privateKey); + st.update(data); + result = st.sign(); + return result; + } + + /** + * @param privateKey + * @param data + * @return + * @throws Exception + */ + public static byte[] signBySoft256(PrivateKey privateKey, byte[] data) + throws Exception { + byte[] result = null; + Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA256RSA, "BC"); + st.initSign(privateKey); + st.update(data); + result = st.sign(); + return result; + } + + public static boolean validateSignBySoft(PublicKey publicKey, + byte[] signData, byte[] srcData) throws Exception { + Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC"); + st.initVerify(publicKey); + st.update(srcData); + return st.verify(signData); + } + + public static boolean validateSignBySoft256(PublicKey publicKey, + byte[] signData, byte[] srcData) throws Exception { + Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA256RSA, "BC"); + st.initVerify(publicKey); + st.update(srcData); + return st.verify(signData); + } + + /** + * 对数据通过公钥进行加密,并进行base64计算 + * + * @param dataString + * 待处理数据 + * @param encoding + * 字符编码 + * @param key + * 公钥 + * @return + */ + public static String encryptData(String dataString, String encoding, + PublicKey key) { + /** 使用公钥对密码加密 **/ + byte[] data = null; + try { + data = encryptData(key, dataString.getBytes(encoding)); + return new String(SecureUtil.base64Encode(data), encoding); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return ""; + } + } + + /** + * 对数据通过公钥进行加密,并进行base64计算 + * + * @param pin + * 待处理数据 + * @param encoding + * 字符编码 + * @param key + * 公钥 + * @return + */ + public static String encryptPin(String accNo, String pin, String encoding, + PublicKey key) { + /** 使用公钥对密码加密 **/ + byte[] data = null; + try { + data = pin2PinBlockWithCardNO(pin, accNo); + data = encryptData(key, data); + return new String(SecureUtil.base64Encode(data), encoding); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return ""; + } + } + + /** + * 通过私钥解密 + * + * @param dataString + * base64过的数据 + * @param encoding + * 编码 + * @param key + * 私钥 + * @return 解密后的数据 + */ + public static String decryptData(String dataString, String encoding, + PrivateKey key) { + byte[] data = null; + try { + data = SecureUtil.base64Decode(dataString.getBytes(encoding)); + data = decryptData(key, data); + return new String(data, encoding); + } catch (Exception e) { + LogUtil.writeErrorLog(e.getMessage(), e); + return ""; + } + } + + /** + * BASE64解码 + * + * @param inputByte + * 待解码数据 + * @return 解码后的数据 + * @throws IOException + */ + public static byte[] base64Decode(byte[] inputByte) throws IOException { + return Base64.decodeBase64(inputByte); + } + + /** + * BASE64编码 + * + * @param inputByte + * 待编码数据 + * @return 解码后的数据 + * @throws IOException + */ + public static byte[] base64Encode(byte[] inputByte) throws IOException { + return Base64.encodeBase64(inputByte); + } + + /** + * 加密除pin之外的其他信息 + * + * @param publicKey + * @param plainData + * @return + * @throws Exception + */ + private static byte[] encryptData(PublicKey publicKey, byte[] plainData) + throws Exception { + try { + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","BC"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + return cipher.doFinal(plainData); + } catch (Exception e) { + throw new Exception(e.getMessage()); + } + } + + /** + * @param privateKey + * @param data + * @return + * @throws Exception + */ + private static byte[] decryptData(PrivateKey privateKey, byte[] data) + throws Exception { + try { + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","BC"); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + return cipher.doFinal(data); + } catch (Exception e) { + LogUtil.writeErrorLog("解密失败", e); + } + return null; + } + + /** + * + * @param aPin + * @return + */ + private static byte[] pin2PinBlock(String aPin) { + int tTemp = 1; + int tPinLen = aPin.length(); + + byte[] tByte = new byte[8]; + try { + /******************************************************************* + * if (tPinLen > 9) { tByte[0] = (byte) Integer.parseInt(new + * Integer(tPinLen) .toString(), 16); } else { tByte[0] = (byte) + * Integer.parseInt(new Integer(tPinLen) .toString(), 10); } + ******************************************************************/ +// tByte[0] = (byte) Integer.parseInt(new Integer(tPinLen).toString(), +// 10); + tByte[0] = (byte) Integer.parseInt(Integer.toString(tPinLen), 10); + if (tPinLen % 2 == 0) { + for (int i = 0; i < tPinLen;) { + String a = aPin.substring(i, i + 2); + tByte[tTemp] = (byte) Integer.parseInt(a, 16); + if (i == (tPinLen - 2)) { + if (tTemp < 7) { + for (int x = (tTemp + 1); x < 8; x++) { + tByte[x] = (byte) 0xff; + } + } + } + tTemp++; + i = i + 2; + } + } else { + for (int i = 0; i < tPinLen - 1;) { + String a; + a = aPin.substring(i, i + 2); + tByte[tTemp] = (byte) Integer.parseInt(a, 16); + if (i == (tPinLen - 3)) { + String b = aPin.substring(tPinLen - 1) + "F"; + tByte[tTemp + 1] = (byte) Integer.parseInt(b, 16); + if ((tTemp + 1) < 7) { + for (int x = (tTemp + 2); x < 8; x++) { + tByte[x] = (byte) 0xff; + } + } + } + tTemp++; + i = i + 2; + } + } + } catch (Exception e) { + } + + return tByte; + } + + /** + * + * @param aPan + * @return + */ + private static byte[] formatPan(String aPan) { + int tPanLen = aPan.length(); + byte[] tByte = new byte[8]; + ; + int temp = tPanLen - 13; + try { + tByte[0] = (byte) 0x00; + tByte[1] = (byte) 0x00; + for (int i = 2; i < 8; i++) { + String a = aPan.substring(temp, temp + 2); + tByte[i] = (byte) Integer.parseInt(a, 16); + temp = temp + 2; + } + } catch (Exception e) { + } + return tByte; + } + + /** + * + * @param aPin + * @param aCardNO + * @return + */ + private static byte[] pin2PinBlockWithCardNO(String aPin, String aCardNO) { + byte[] tPinByte = pin2PinBlock(aPin); + if (aCardNO.length() == 11) { + aCardNO = "00" + aCardNO; + } else if (aCardNO.length() == 12) { + aCardNO = "0" + aCardNO; + } + byte[] tPanByte = formatPan(aCardNO); + byte[] tByte = new byte[8]; + for (int i = 0; i < 8; i++) { + tByte[i] = (byte) (tPinByte[i] ^ tPanByte[i]); + } + return tByte; + } + + /** + * luhn算法 + * + * @param number + * @return + */ + public static int genLuhn(String number) { + number = number + "0"; + int s1 = 0, s2 = 0; + String reverse = new StringBuffer(number).reverse().toString(); + for (int i = 0; i < reverse.length(); i++) { + int digit = Character.digit(reverse.charAt(i), 10); + if (i % 2 == 0) {// this is for odd digits, they are 1-indexed in // + // the algorithm + s1 += digit; + } else {// add 2 * digit for 0-4, add 2 * digit - 9 for 5-9 + s2 += 2 * digit; + if (digit >= 5) { + s2 -= 9; + } + } + } + int check = 10 - ((s1 + s2) % 10); + if (check == 10) + check = 0; + return check; + } +} diff --git a/back-end_code/src/main/java/com/shop/utils/AlipayConfig.java b/back-end_code/src/main/java/com/shop/utils/AlipayConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..85316f9448d3b35f3c2b853c4169b57928fe2315 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/utils/AlipayConfig.java @@ -0,0 +1,70 @@ +package com.shop.utils; + +import java.io.FileWriter; +import java.io.IOException; + +/* * + *类名:AlipayConfig + *功能:基础配置类 + *详细:设置帐户有关信息及返回路径 + *修改日期:2017-04-05 + *说明: + *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。 + *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。 + */ + +public class AlipayConfig { + +//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ + + // 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号 + public static String app_id = "2021000119638275"; + + // 商户私钥,您的PKCS8格式RSA2私钥 + public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC13ueKIsQYFhvM9AiT8/4KTPG2RUqWmXyCI90C2MRE13c/H+y8ejiVoYRlnx79lhU+uMXooXxld1KPuUd1YyCcmLcvPGnhkRRDhfoayCY643ODZ5vYrtqQrgpqCPSrYkzc9/j5eVkdIVai3e8hENzcUDJwxSjD1Jat3pdPTo4t6fh/itQiyevDTN5RPRW7m6xsE9BcVum8Q/rgUeyoRNexfktZzgUdxJvSYXIOGxqXNIJ8XnAA+PHu+I4vhCqD8QEtg/JfZpUKf6CnBrN8SPL+YvCUR408izYOMhkr6N1w+/CP/X8vcTAOqtg4wJg/HppqYoglf6hgz65S85bf8BBbAgMBAAECggEAHRPMVQuF6ovuWfBSRsVlwmPW6Vtet4FGpM/zD/d0OcVxLUh/YwrvbQzrzAuKuuR59RM5oR3gc6CGNLBcumnk1uSbtROlogi+AqWy/QEvC4898q5n/lbGXwdUZuuToqsOuu1ygwBhvQSNg3CUQOcfSKIRznHXOKgOhzHlYyqeFLzkBI4PDbJyU/d0biiCCup6wlNCttlvueb8owqeFerhafVwt676d8AQvjAkpONA6RlL+quIxvMMkbqAKuxrjMzcvUJTbdj/liVJBo+bX9LcCPt6x4cY3YmDo88ScBJc6pC8bKXd/kOHcvsNchzumq5NMVedt4pSDC+suRMXN9L84QKBgQD2CAOS4L25oUH19biQ7gSQpVsxTj6gubLuh2fjyKRhS5RC4EyROwramuiQwOVUN7UG7L2RX5UmIJO6TnTW/I4eFhLmnpt8TXrrEZv77b+VqrxmYXlbnIQQX+8kIj0aJ4s0vn7r7zly0iKlbmfCLFXOQhZN2cLko/MBUjp0JgE5iQKBgQC9PWDCaYrNdmM+nMcEpWk7nbk7LHwZ0sKI2lM2QWFxo0RRWknwbEP60k0s0hMWD+Sa+0nOl1P50UAuldfnEbYEN/WMjhxSqdeguOz9pF+KSSgVuvHB5+XkBg2j5SZW1Zd1eARNFBreD5CLNNAlMbF+CDkYjR3quBSBZcdyG8EVwwKBgQCAf50GOJU+/8dIpEb6gyYlOggQD3LMVVDsHhKXuLKKEoRkDWxQKgs4M9Il0Gm2e8Xz0PANnmNy327ozpNdudisRBEpHEvPN1Rss+zJPtpiXCM8Qcq1m2CqgMCRGcTaBS9Co//8UBysKK5pwuk0VB2YtZGapZKSAkMoPH9FLJhVKQKBgE1VbdtFAkIgpUILE5GkfzKrq+ywqy5qYLFId0TuxwGHdP3B5gFoXQd9NaihWMdlS0jCdFEGqnymtJHVDlwRcs6ah7AeyxhE7Cd0KvUkXR7H8qees/lH6Tyb9KsLk/VcZ/7LQwa0tp4Uwj8BICZy/lPAzIRp9tXa0BZpH25URT29AoGBAOzkmsPgrtDrqKX7bXKP9soUfSnT3TqHv4Wau4eapBJdjnJ12i7+v+R5lvJrjgX39gU4zamiKv2Jj4DAYjPMEM82Z1ptr1WcEiMNu3EyOJ2sE7CL8qeFd8VRLC7Y18N4uGSj7oWbd4qNKAP6h9bsou5Nu17F7mYf+1hAINbh33Zq"; + // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。 + public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXO3+a2ne7NHY9gvqhkWYZ4iKdK83/S4JRF02xiyXPrF/rTJVefEMPNkJ6lW3/5OPBmx173gxtZ6/1bIX2gj32a8KICbuYW6QlhzkTa6SWk9A7/VD/o7rLuM2jIKA/U2VYzTAGWMYApnvdYL042BPmedplxj0ZJvc/DxCmktdk4E3QP5Xl/tO7ntUVEeZcslA8iFXDP2DCloZ/L/FcYLFCrPHFCijiGb2gMdfWqA9i2FVSd7taSZJNCI5+WJl5LDUDoA3BC/x2FAZ0ZTyX0IVEI4RTARaHXzzc9ROnCyv9YXOHRBvaUooqsM+Pmyj7Y4mHS+SKzvWyyYuPrAZTi8gQIDAQAB"; + // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 + public static String notify_url = "http://souldays.top:8085/pay/notify"; + + // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 + public static String return_url = "http://localhost:8069"; + + // 签名方式 + public static String sign_type = "RSA2"; + + // 字符编码格式 + public static String charset = "utf-8"; + + // 支付宝网关 + public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; + + // 日志地址 + public static String log_path = "C:\\"; + + +//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ + + /** + * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库) + * @param sWord 要写入日志里的文本内容 + */ + public static void logResult(String sWord) { + FileWriter writer = null; + try { + writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt"); + writer.write(sWord); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } +} + diff --git a/back-end_code/src/main/java/com/shop/utils/AlipayUtil.java b/back-end_code/src/main/java/com/shop/utils/AlipayUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..37d7823ad650305378b3c076bb682338964b6318 --- /dev/null +++ b/back-end_code/src/main/java/com/shop/utils/AlipayUtil.java @@ -0,0 +1,74 @@ +package com.shop.utils; + +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.request.AlipayTradePagePayRequest; +import com.alipay.api.request.AlipayTradeQueryRequest; +import com.alipay.api.response.AlipayTradePagePayResponse; +import com.alipay.api.response.AlipayTradeQueryResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * @author mumuwei + * @date 0004 + */ +@Component +public class AlipayUtil { + + + + public String pay(Integer id, Float price, Integer title ){ + AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id, + AlipayConfig.merchant_private_key,"json","UTf-8",AlipayConfig.alipay_public_key,"RSA2"); + AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); + request.setNotifyUrl(AlipayConfig.notify_url); + request.setReturnUrl(AlipayConfig.return_url); + JSONObject bizContent = new JSONObject(); + bizContent.put("out_trade_no", id); + bizContent.put("total_amount", price); + bizContent.put("subject", title); + bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); + + request.setBizContent(bizContent.toString()); + AlipayTradePagePayResponse response = null; + String form = null; + try { + response = alipayClient.pageExecute(request); + form = response.getBody(); + } catch (AlipayApiException e) { + e.printStackTrace(); + } + if(response.isSuccess()){ + System.out.println("调用成功"); + } else { + System.out.println("调用失败"); + } + return form; + } + + public String query(String id){ + AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key, + "json","UTf-8",AlipayConfig.alipay_public_key,"RSA2"); + AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); + JSONObject bizContent = new JSONObject(); + bizContent.put("out_trade_no", id); + request.setBizContent(bizContent.toString()); + AlipayTradeQueryResponse response = null; + String body = null; + try { + response = alipayClient.execute(request); + body = response.getBody(); + } catch (AlipayApiException e) { + e.printStackTrace(); + } + if(response.isSuccess()){ + System.out.println("调用成功"); + } else { + System.out.println("调用失败"); + } + return body; + } +} diff --git a/back-end_code/src/main/java/com/shop/utils/JsonResult.java b/back-end_code/src/main/java/com/shop/utils/JsonResult.java new file mode 100644 index 0000000000000000000000000000000000000000..2a853cf0c3d9778be12849baea544aa9b8199d5d --- /dev/null +++ b/back-end_code/src/main/java/com/shop/utils/JsonResult.java @@ -0,0 +1,100 @@ +package com.shop.utils; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by think on 2017/6/5. + */ +public class JsonResult { + private Boolean success = Boolean.valueOf(false); + private String msg = ""; + private Object obj = null; + private Integer type = Integer.valueOf(0); + private Map fieldErrors = new HashMap(); + + public JsonResult() { + } + + public JsonResult(Boolean success, String msg) { + this.success = success; + this.msg = msg; + } + + public JsonResult(Boolean success, String msg, Integer type) { + this.success = success; + this.msg = msg; + this.type = type; + } + + public JsonResult(Boolean success, String msg, Object obj, Integer type) { + this.success = success; + this.msg = msg; + this.obj = obj; + this.type = type; + } + + public Boolean getSuccess() { + return Boolean.valueOf(this.success.booleanValue() && this.fieldErrors.size() == 0); + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getMsg() { + return this.msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Object getObj() { + return this.obj; + } + + public void setObj(Object obj) { + this.obj = obj; + } + + public Integer getType() { + return this.type; + } + + public void setType(Integer type) { + this.type = type; + } + + public void addFieldError(String field, String message) { + this.fieldErrors.put(field, message); + } + + public void addFieldErrors(Map fieldErrors) { + this.fieldErrors.putAll(fieldErrors); + } + + public Map getFieldErrors() { + return this.fieldErrors; + } + + public static JsonResult resultError(String message) { + return resultError(message, 0); + } + + public static JsonResult resultError(String message, int type) { + return new JsonResult(Boolean.valueOf(false), message, Integer.valueOf(0)); + } + + public static JsonResult resultSuccess(Object obj) { + return resultSuccess("", obj); + } + + public static JsonResult resultSuccess(String message, Object obj) { + return resultSuccess(message, obj, 0); + } + + public static JsonResult resultSuccess(String message, Object obj, int type) { + return new JsonResult(Boolean.valueOf(true), message, obj, Integer.valueOf(type)); + } +} diff --git a/back-end_code/src/main/resources/application-dev.yml b/back-end_code/src/main/resources/application-dev.yml index e5d39829615bf4820167a4ddacdd5b6c72a0a6ff..a9e3822dd3f7508f02b6ff1dfe119e3ba1db5879 100644 --- a/back-end_code/src/main/resources/application-dev.yml +++ b/back-end_code/src/main/resources/application-dev.yml @@ -1,12 +1,12 @@ server: - port: 8084 + port: 8085 spring: datasource: username: xiangwan password: dingwanren #url中database为对应的数据库名称 - url: jdbc:mysql://47.103.214.177:3306/service3.0?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC + url: jdbc:mysql://47.103.214.177:3306/service4.0?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver devtools: restart: @@ -15,6 +15,25 @@ spring: exclude: WEB-INF/** freemarker: cache: false #页面不加载缓存,修改即时生效 + redis: + host: localhost # Redis服务器地址 + database: 0 # Redis数据库索引(默认为0) + port: 6379 # Redis服务器连接端口 + password: # Redis服务器连接密码(默认为空) + jedis: + pool: + max-active: 8 # 连接池最大连接数(使用负值表示没有限制) + max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) + max-idle: 8 # 连接池中的最大空闲连接 + min-idle: 0 # 连接池中的最小空闲连接 + timeout: 3000ms # 连接超时时间(毫秒) +# 自定义redis key +redis: + key: + prefix: + authCode: "portal:authCode:" + expire: + authCode: 120 # 验证码超期时间 mybatis: mapper-locations: classpath:mapping/*.xml diff --git a/back-end_code/src/main/resources/application-pro.yml b/back-end_code/src/main/resources/application-pro.yml index 9b61ba781c44def941683003c91982f0000622a0..2baead9cdaf3de98533541e7fca2fa6ef5188fde 100644 --- a/back-end_code/src/main/resources/application-pro.yml +++ b/back-end_code/src/main/resources/application-pro.yml @@ -1,12 +1,12 @@ server: - port: 8084 + port: 8085 spring: datasource: username: root password: jiaxintang #url中database为对应的数据库名称 - url: jdbc:mysql://localhost:3306/service3.0?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC + url: jdbc:mysql://localhost:3306/service4.0?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver mybatis: diff --git a/back-end_code/src/main/resources/application.yml b/back-end_code/src/main/resources/application.yml index 3d7808a0c672513d472ab235d04d18e363fc8a87..0cecd7ba0be448af0abe2e91bd2dfc9b4c4cd163 100644 --- a/back-end_code/src/main/resources/application.yml +++ b/back-end_code/src/main/resources/application.yml @@ -1,3 +1,7 @@ spring: profiles: active: dev +# thymeleaf: +# cache: false +# suffix: .html +# prefix: classpath:/templates/ \ No newline at end of file diff --git a/back-end_code/src/main/resources/certs/acp_test_enc.cer b/back-end_code/src/main/resources/certs/acp_test_enc.cer new file mode 100644 index 0000000000000000000000000000000000000000..f6e26309fadbd4c1e7690a0e6c009ed05694317a --- /dev/null +++ b/back-end_code/src/main/resources/certs/acp_test_enc.cer @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEPzCCAyegAwIBAgIFEDl2NhIwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UEBhMC +Q04xMDAuBgNVBAoTJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhv +cml0eTEXMBUGA1UEAxMOQ0ZDQSBURVNUIE9DQTEwHhcNMjAwOTExMDI0MzI2WhcN +MjUwOTExMDI0MzI2WjBzMQswCQYDVQQGEwJDTjESMBAGA1UEChMJQ0ZDQSBPQ0Ex +MQ0wCwYDVQQLEwRZQ0NBMRUwEwYDVQQLEwxJbmRpdmlkdWFsLTExKjAoBgNVBAMM +IVlDQ0FA5rWL6K+V5L2/55SoQDAwMDQwMDAwOlNJR05AMTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBALUwYYpqUXZyDAu0gX5d8XkiUfFxdCan/VyLa6Cz +KH38cjX0QZIShn/O6Cw2hn2WurP/r3LdopLRzTHI0vIDJpQY/0Y135QHRFZHkAH0 +omRTfAZ/atePnRF7VW766LGhR5n05h1nITDHlzCZYPSumpDPpVcJj4y30+G3A5Ou +1VVAsuLi48XtGIKwRX6gMXI+P75RwHSmPt5/pHlEPT6wUbmF0HBoF2gRBpYZwiSK +51Z52XUVEk96reolFFLu/9qyL767/v2izd5YuN9i7oSXNw1gDYcLnAuww6V6BUnK +Kq4KUG6H3Lz3WyXbEay72f12A5pnHWDjLEOwJ2SG1VVMLN8CAwEAAaOB9DCB8TAf +BgNVHSMEGDAWgBTPcJ1h6518Lrj3ywJA9wmd/jN0gDBIBgNVHSAEQTA/MD0GCGCB +HIbvKgEBMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2ZjYS5jb20uY24vdXMv +dXMtMTQuaHRtMDkGA1UdHwQyMDAwLqAsoCqGKGh0dHA6Ly91Y3JsLmNmY2EuY29t +LmNuL1JTQS9jcmw3NTM3Ni5jcmwwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBSwaOVL +eW+I7Pm7C8lXu94+MTXAzjAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQw +DQYJKoZIhvcNAQEFBQADggEBADhYan/FCZWzD0BS+KvZivpp498eWRqzXjH2QkBv +IDYv2+Ntue66WxECMW7i9+RZVjyMeYbFkoxVEcg0cE/mcHOnqd1mTBpeb62NRbWR +OuquWHxcdIHJ/TjGX8+NwtpAKsn/IvTdEBz+EOOzmXuxNqNxV3Gg7Ay3YavWZzci +h9GEAQ11WKAjaNqq+XO6dDwBSVEQEkvHqf1DeqCZ9wl58I4MvUmAI7wKfnoonquu +1wCNMxnkHYS5EAk1Zb0nsprjz771+YZI6ai/I2ehn8hyUR46TYmPMn0WyaXkmEO7 +ig055dazyfvMinsHmKyLa/yJvQMlZIWtsKzaNG4ikdA+ELQ= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/back-end_code/src/main/resources/certs/acp_test_middle.cer b/back-end_code/src/main/resources/certs/acp_test_middle.cer new file mode 100644 index 0000000000000000000000000000000000000000..3275b90f7cfe37b1c6d81ceabdd81c6bb825e224 --- /dev/null +++ b/back-end_code/src/main/resources/certs/acp_test_middle.cer @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIIDzjCCAragAwIBAgIKGNDz/H99Hd/CxjANBgkqhkiG9w0BAQUFADBZMQswCQYD +VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g +QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODMwMDMx +NDMzWhcNMzEwNTExMDMxNDMzWjBYMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp +bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRcwFQYDVQQDEw5D +RkNBIFRFU1QgT0NBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALiL +J/BrdvHSbXNfLIMTwUg9tDtVjMRGXOl6aZnu9IpxjI5SMUJ4hVwgJnmbTokxs6GF +IXKsCLSm5H1jHLI22ysc/ltByEybLWj5jjJuC9+Uknbl3/Ls1RBG6MogUCqZckuo +hKrf5DmlV3C/jVLxGn3pUeanvmqVUi4TKpXxgm5QqKSPF8VtQY4qCpNcQwwZqbMr +D+IfJtfpGAeVrP+Kg6i1t65seeEnVSaLhqpRUDU0PTblOuUv3OhiKJWA3cYWxUrg +7U7SIHNJLSEUWmjy4mKty+g7Cnjzt29F9qXFb6oB2mR8yt4GHCilw1Rc5RBXY63H +eTuOwdtGE3M2p7Q++OECAwEAAaOBmDCBlTAfBgNVHSMEGDAWgBR03sWNCn0QGqpp +g1tNIc6Gm8xxODAMBgNVHRMEBTADAQH/MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6 +Ly8yMTAuNzQuNDIuMy90ZXN0cmNhL1JTQS9jcmwxLmNybDALBgNVHQ8EBAMCAQYw +HQYDVR0OBBYEFM9wnWHrnXwuuPfLAkD3CZ3+M3SAMA0GCSqGSIb3DQEBBQUAA4IB +AQC0JOazrbkk0XMxMMeBCc3lgBId1RjQLgWUZ7zaUISpPstGIrE5A9aB6Ppq0Sxl +pt2gkFhPEKUqgOFN1CzCDEbP3n4H0chqK1DOMrgTCD8ID5UW+ECTYNe35rZ+1JiF +lOPEhFL3pv6XSkiKTfDnjum8+wFwUBGlfoWK1Hcx0P2Hk1jcZZKwGTx1IAkesF83 +pufhxHE2Ur7W4d4tfp+eC7XXcA91pdd+VUrAfkj9eKHcDEYZz66HvHzmt6rtJVBa +pwrtCi9pW3rcm8c/1jSnEETZIaokai0fD7260h/LkD/GrNCibSWxFj1CqyP9Y5Yv +cj6aA5LnUcJYeNkrQ3V4XvVc +-----END CERTIFICATE----- diff --git a/back-end_code/src/main/resources/certs/acp_test_root.cer b/back-end_code/src/main/resources/certs/acp_test_root.cer new file mode 100644 index 0000000000000000000000000000000000000000..779647c0b57541e92fec695ddad479ea2dd5505e --- /dev/null +++ b/back-end_code/src/main/resources/certs/acp_test_root.cer @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDkzCCAnugAwIBAgIKUhN+zB19hbc65jANBgkqhkiG9w0BAQUFADBZMQswCQYD +VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g +QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODI5MDUw +MTI5WhcNMzIwODI5MDUwMTI5WjBZMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp +bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRgwFgYDVQQDEw9D +RkNBIFRFU1QgQ1MgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa +rMJGruH6rOBPFxUI7T1ybydSRRtOM1xvkVjQNX0qmYir8feE6Tb0ctgtKR7a20DI +YCj9kZ5ANBQqjRcj3Soq9XH3cirqhYHJ723OKyTpS0RPQ0N6vtVt3P5JQ+ztjWHd +qIbbTOQ6O024TGTiqi6uHgMuz9/OVur81X3a5YVkK7jFeZ9o8cTcvQxD853/1sgZ +QcmR9aUSw0RXH4XFLTrn7n4QSfWKiNotlD8Ag5gS1pH9ONUb6nGkMn3gh1xfJqjm +ONMSknPXTGiNpXtqvYi8oIvByVCbUDO59IwPP1r1SYyE3P8Nr7DdQRu0KQSdXLoG +iugSR3fn+toObVAQmplDAgMBAAGjXTBbMB8GA1UdIwQYMBaAFHTexY0KfRAaqmmD +W00hzoabzHE4MAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBR0 +3sWNCn0QGqppg1tNIc6Gm8xxODANBgkqhkiG9w0BAQUFAAOCAQEAM0eTkM35D4hj +RlGC63wY0h++wVPUvOrObqAVBbzEEQ7ScBienmeY8Q6lWMUTXM9ALibZklpJPcJv +3ntht7LL6ztd4wdX7E9RzZCQnRvbL9A/BU3NxWdeSpCg/OyPod5oCKP+6Uc7kApi +F9OtYNWnt3l2Zp/NiedzEQD8H4qEWQLAq+0dFo5BkfVhb/jPcktndpfPOuH1IMhP +tVcvo6jpFHw4U/nP2Jv59osIE97KJz/SPt2JAYnZOlIDqWwp9/Afvt0/MDr8y0PK +Q9c6eqIzBx7a9LpUTUl5u1jS+xSDZ/KF2lXnjwaFp7jICLWEMlBstCoogi7KwH9A +LpJP7/dj9g== +-----END CERTIFICATE----- diff --git a/back-end_code/src/main/resources/certs/acp_test_sign.pfx b/back-end_code/src/main/resources/certs/acp_test_sign.pfx new file mode 100644 index 0000000000000000000000000000000000000000..523ae1e310ca318b15fd7b8918c6b4e11febf9a6 Binary files /dev/null and b/back-end_code/src/main/resources/certs/acp_test_sign.pfx differ diff --git a/back-end_code/src/main/resources/mapping/AddressMapper.xml b/back-end_code/src/main/resources/mapping/AddressMapper.xml new file mode 100644 index 0000000000000000000000000000000000000000..59d4023363d5ee2c697a3e1792ec96f2ff1c8284 --- /dev/null +++ b/back-end_code/src/main/resources/mapping/AddressMapper.xml @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + insert into address + + + + username, + + + realname, + + + region, + + + detail, + + + phonenumber, + + + selected, + + + + + + + #{username,jdbcType=VARCHAR}, + + + #{realname,jdbcType=VARCHAR}, + + + #{region,jdbcType=VARCHAR}, + + + #{detail,jdbcType=VARCHAR}, + + + #{phonenumber,jdbcType=VARCHAR}, + + + #{selected,jdbcType=VARCHAR}, + + + + + + + + + + + + + delete from address where addressId = #{address_id} and username = #{username} + + + + + update address + + + realname = #{realname,jdbcType=VARCHAR}, + + + region = #{region,jdbcType=VARCHAR}, + + + detail = #{detail,jdbcType=VARCHAR}, + + + phonenumber = #{phonenumber,jdbcType=VARCHAR}, + + + selected = #{selected,jdbcType=VARCHAR}, + + + where addressId = #{address_id,jdbcType=INTEGER} + + + + + update address set where addressId = #{address_id,jdbcType=INTEGER} and username = #{username} and + + + + + update address set where username = #{username} and + + + + + + + + + + diff --git a/back-end_code/src/main/resources/mapping/AftApplicationMapper.xml b/back-end_code/src/main/resources/mapping/AftApplicationMapper.xml new file mode 100644 index 0000000000000000000000000000000000000000..06ce19ddc30f299ddf87c7c80715ce0866bfbb74 --- /dev/null +++ b/back-end_code/src/main/resources/mapping/AftApplicationMapper.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + insert into aftapplication + + + orderId, + + + aftApplicationBuyerusername, + + + aftApplicationSellerusername, + + + packageState, + + + aftApplicationType, + + + aftApplicationReason, + + + aftApplicationImages, + + aftApplicationState, + + createTime, + + + + + + + #{order_id}, + + + #{aftApplication_buyerusername,jdbcType=VARCHAR}, + + + #{aftApplication_sellerusername,jdbcType=VARCHAR}, + + + #{package_state,jdbcType=VARCHAR}, + + + #{aftApplication_type,jdbcType=VARCHAR}, + + + #{aftApplication_reason,jdbcType=VARCHAR}, + + + #{aftApplication_images,jdbcType=VARCHAR}, + + + + #{create_time,jdbcType=TIMESTAMP}, + + + + + + + + + + + + + + + + + + + update aftapplication + + + aftApplicationReason = #{aftApplication_reason,jdbcType=VARCHAR}, + + + aftApplicationImages = #{aftApplication_images,jdbcType=VARCHAR}, + + + where aftApplicationId = #{aftApplication_id,jdbcType=INTEGER} and aftApplicationBuyerusername = #{aftApplication_buyerusername} and + + + + + update aftapplication + + + + finishTime = #{finish_time,jdbcType=TIMESTAMP}, + + where aftApplicationId = #{aftApplication_id} and aftApplicationBuyerusername = #{aftApplication_buyerusername} and + + + + + update aftapplication + + + + finishTime = #{finish_time,jdbcType=TIMESTAMP}, + + where aftApplicationId = #{aftApplication_id} and aftApplicationSellerusername = #{aftApplication_sellerusername} and + + + + + update aftapplication + + + where aftApplicationId = #{aftApplication_id} and aftApplicationSellerusername = #{aftApplication_sellerusername} and + + + + + update aftapplication + + + + finishTime = #{finish_time,jdbcType=TIMESTAMP}, + + where aftApplicationId = #{aftApplication_id} and aftApplicationSellerusername = #{aftApplication_sellerusername} and + + + + + update aftapplication + + + where aftApplicationId = #{aftApplication_id} and aftApplicationSellerusername = #{aftApplication_sellerusername} and + + + + diff --git a/back-end_code/src/main/resources/mapping/GOMapper.xml b/back-end_code/src/main/resources/mapping/GOMapper.xml index ead124d44b98207af3a02fdf43e53790be28375a..62505b7542fa780f81353a1815e329666d0f6aca 100644 --- a/back-end_code/src/main/resources/mapping/GOMapper.xml +++ b/back-end_code/src/main/resources/mapping/GOMapper.xml @@ -4,7 +4,7 @@ - + diff --git a/back-end_code/src/main/resources/mapping/GoodsMapper.xml b/back-end_code/src/main/resources/mapping/GoodsMapper.xml index 593271809ecb044de4ad8126e9219ddb16e4cb6c..9e2df59a52320c9a42e7f157cb91dd5cd5af119c 100644 --- a/back-end_code/src/main/resources/mapping/GoodsMapper.xml +++ b/back-end_code/src/main/resources/mapping/GoodsMapper.xml @@ -7,10 +7,10 @@ - + - + @@ -30,8 +30,8 @@ goodsImg, - - goodsDiscribe, + + goodsDescribe, goodsCategory, @@ -56,8 +56,8 @@ #{goods_img,jdbcType=VARCHAR}, - - #{goods_discribe,jdbcType=VARCHAR}, + + #{goods_describe,jdbcType=VARCHAR}, #{goods_category,jdbcType=VARCHAR}, @@ -65,10 +65,15 @@ #{goods_price,jdbcType=REAL}, - 1, + , + + + + select * + from orderdetail ,snapshot + where orderId = #{order_id} and orderdetail.snapshotId = snapshot.snapshotId + + + + + + + + + diff --git a/back-end_code/src/main/resources/mapping/OrderMapper.xml b/back-end_code/src/main/resources/mapping/OrderMapper.xml index 4d10a34ee5fcbb7e8e672ad8ae12441d4132ae2d..685fb70688b2915c731777ff2d02a3be4889808b 100644 --- a/back-end_code/src/main/resources/mapping/OrderMapper.xml +++ b/back-end_code/src/main/resources/mapping/OrderMapper.xml @@ -1,103 +1,57 @@ - - + + + - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + + - - - - - - - - - - - - - - - - update orders set state = 1 where orderId = #{order_id} and sellerUsername = #{seller_username} - - - - - update orders set state = 4 where itemId = #{item_id} and state = 5 and sellerUsername = #{seller_username} - - - - - update orders set state = 6 where orderId = #{order_id} and state = 1 and sellerUsername = #{seller_username} - - - - - - - - - - - - - - - - + insert into orders - - - itemId, - - - goodsName, - - - goodsImg, - - - goodsDiscribe, - - - goodsPrice, + + orderId, sellerUsername, @@ -105,44 +59,20 @@ buyerUsername, - - buyerRealname, - - - buyerPhonenumber, - - - buyerAddress, - - - buySum, + + addressId, buyAmount, - - state, - createTime, - - #{item_id,jdbcType=INTEGER}, - - - #{goods_name,jdbcType=VARCHAR}, - - - #{goods_img,jdbcType=VARCHAR}, - - - #{goods_discribe,jdbcType=VARCHAR}, - - - #{goods_price,jdbcType=REAL}, + + #{order_id,jdbcType=BIGINT}, #{seller_username,jdbcType=VARCHAR}, @@ -150,126 +80,312 @@ #{buyer_username,jdbcType=VARCHAR}, - - #{buyer_realname,jdbcType=VARCHAR}, - - - #{buyer_phonenumber,jdbcType=VARCHAR}, - - - #{buyer_address ,jdbcType=VARCHAR}, - - - #{buy_sum ,jdbcType=INTEGER}, + + #{address.address_id,jdbcType=INTEGER}, #{buy_amount ,jdbcType=REAL}, - - #{state ,jdbcType=INTEGER}, - #{create_time ,jdbcType=VARCHAR}, + + + + + + + + + + + + + + + + + + update orders + set + where orderId = #{order_id} and + + - - update orders set state = 2 where orderId = #{order_id} and state = 1 and sellerUsername = #{seller_username} + + update orders + set + where orderId = #{order_id} and sellerUsername = #{seller_username} and - + select * + from orders ,address ,orderdetail ,snapshot + where orders.buyerUsername = #{buyer_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and - + select * + from orders ,address ,orderdetail ,snapshot + where orders.sellerUsername = #{seller_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and - - update orders set state = 3 where orderId = #{order_id} and state = 2 and sellerUsername = #{seller_username} + + update orders + set + where orderId = #{order_id} and sellerUsername = #{seller_username} and - + select * + from orders ,address ,orderdetail ,snapshot + where orders.buyerUsername = #{buyer_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and + + + + - + update orders - - buyerPhonenumber = #{buyer_phonenumber,jdbcType=VARCHAR}, - - - buyerAddress = #{buyer_address,jdbcType=VARCHAR}, - - - buyerRealname = #{buyer_realname,jdbcType=VARCHAR}, + + addressId = #{address.address_id,jdbcType=INTEGER}, - where orderId = #{order_id} and state = 3 and buyerUsername = #{buyer_username} + where orderId = #{order_id} and buyerUsername = #{buyer_username} + and - - - - - update orders set state = 4 where orderId = #{order_id} and state = 3 and sellerUsername = #{seller_username} + + update orders + set + where orderId = #{order_id} and sellerUsername = #{seller_username} and + + + - + select * + from orders ,address ,orderdetail ,snapshot + where orders.sellerUsername = #{seller_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and - - update orders set state = 5 , finishTime = #{finish_time} where orderId = #{order_id} and state = 4 and buyerUsername = #{buyer_username} + + update orders + set , finishTime = #{finish_time} + where orderId = #{order_id} and buyerUsername = #{buyer_username} and + + + + + + + + + + + update orders + set , finishTime = #{finish_time} + where orderId = #{order_id} and buyerUsername = #{buyer_username} + and - update orders set state = 6 where orderId = #{order_id} and sellerUsername = #{seller_username} and state < 4 + update orders + set , finishTime = #{finish_time} + where orderId = #{order_id} and sellerUsername = #{seller_username} + and - - - update orders set state = 7 where orderId = #{order_id} and buyerUsername = #{buyer_username} and state < 5 + + + + + + + + + update orders + set + where orderId = #{order_id} and buyerUsername = #{buyer_username} - - + select * + from orders ,address ,orderdetail ,snapshot + where orders.buyerUsername = #{buyer_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and - - + select * + from orders ,address ,orderdetail ,snapshot + where orders.sellerUsername = #{seller_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and + + + update orders + set ,finishTime = #{finish_time} + where orderId = #{order_id} and sellerUsername = #{seller_username} + + + + + update orders + set + where orderId = #{order_id} and sellerUsername = #{seller_username} + + - + select * + from orders ,address ,orderdetail ,snapshot + where orders.buyerUsername = #{buyer_username} and orderdetail.orderId = orders.orderId and orders.addressId = address.addressId and orderdetail.snapshotId = snapshot.snapshotId + and + + + + + + + + + + + + + + + + + + + update orders set buyAmount = #{buy_amount} + where orderId = #{order_id} and sellerUsername = #{seller_username} and + + + + + update orders set packageNumber = #{package_number}, + where orderId = #{order_id} and sellerUsername = #{seller_username} and + diff --git a/back-end_code/src/main/resources/mapping/SnapshotMapper.xml b/back-end_code/src/main/resources/mapping/SnapshotMapper.xml new file mode 100644 index 0000000000000000000000000000000000000000..6572f6180aa876cbbea1a9a8b44a8b1d6e542396 --- /dev/null +++ b/back-end_code/src/main/resources/mapping/SnapshotMapper.xml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + insert into snapshot + + + + itemId, + + + goodsName, + + + goodsImg, + + + goodsDescribe, + + + goodsCategory, + + + goodsPrice, + + + snapshotTime, + + + + + + + #{item_id,jdbcType=INTEGER}, + + + #{goods_name,jdbcType=VARCHAR}, + + + #{goods_img,jdbcType=VARCHAR}, + + + #{goods_describe,jdbcType=VARCHAR}, + + + #{goods_category,jdbcType=INTEGER}, + + + #{goods_price,jdbcType=REAL}, + + + #{snapshot_time,jdbcType=VARCHAR}, + + + + + + + delete from snapshot where snapshotId = #{snapshot_id} + + + + + update snapshot + + + goodsName = #{goods_name,jdbcType=VARCHAR}, + + + goodsImg = #{goods_img,jdbcType=VARCHAR}, + + + goodsDescribe = #{goods_describe,jdbcType=VARCHAR}, + + + goodsCategory = #{goods_category,jdbcType=INTEGER}, + + + goodsPrice = #{goods_price,jdbcType=REAL}, + + + where snapshotId = #{snapshot_id,jdbcType=INTEGER} + + + + + + + + + + + + diff --git a/back-end_code/src/main/resources/mapping/UserMapper.xml b/back-end_code/src/main/resources/mapping/UserMapper.xml index 971050b2a3e66c0353d4865ea02e402e7b4cbdeb..1cffa8393d09810245412a4d93b26e1f98983710 100644 --- a/back-end_code/src/main/resources/mapping/UserMapper.xml +++ b/back-end_code/src/main/resources/mapping/UserMapper.xml @@ -4,12 +4,10 @@ - - - + @@ -24,10 +22,11 @@ - + insert into user @@ -41,21 +40,15 @@ nickName, - - realName, - - - phoneNumber, - - - address, - permission, userHead, + + shopName, + @@ -69,21 +62,15 @@ #{nickname,jdbcType=VARCHAR}, - - #{realname,jdbcType=VARCHAR}, - - - #{phonenumber,jdbcType=VARCHAR}, - - - #{address,jdbcType=VARCHAR}, - - #{permission,jdbcType=INTEGER}, + #{permission,jdbcType=VARCHAR}, #{user_head,jdbcType=VARCHAR}, + + #{shop_name,jdbcType=VARCHAR}, + @@ -94,28 +81,26 @@ nickName = #{nickname,jdbcType=VARCHAR}, - - permission = #{permission,jdbcType=INTEGER}, - - - phoneNumber = #{phonenumber,jdbcType=VARCHAR}, - - - address = #{address,jdbcType=VARCHAR}, - - - realName = #{realname,jdbcType=VARCHAR}, - userHead = #{user_head,jdbcType=VARCHAR}, + + shopName = #{shop_name,jdbcType=VARCHAR}, + where userName = #{username,jdbcType=VARCHAR} - + + + + - \ No newline at end of file + diff --git a/back-end_code/src/main/resources/properties/acp_sdk.properties b/back-end_code/src/main/resources/properties/acp_sdk.properties new file mode 100644 index 0000000000000000000000000000000000000000..9ec30fd439381fbb85982d4d506a4643fd3586ac --- /dev/null +++ b/back-end_code/src/main/resources/properties/acp_sdk.properties @@ -0,0 +1,77 @@ +##############SDK配置文件(证书方式签名)################ +# 说明: +# 1. 使用时请删除后缀的“.证书”,并将此文件复制到src文件夹下替换原来的acp_sdk.properties。 +# 2. 具体配置项请根据注释修改。 +# +################################################ + +#商户号 +acpsdk.merId=777290058197286 +#acpsdk.merId=700000000000001 + +##########################入网测试环境交易发送地址(线上测试需要使用生产环境交易请求地址)############################# + +##交易请求地址 +acpsdk.frontTransUrl=https://gateway.test.95516.com/gateway/api/frontTransReq.do +acpsdk.backTransUrl=https://gateway.test.95516.com/gateway/api/backTransReq.do +acpsdk.singleQueryUrl=https://gateway.test.95516.com/gateway/api/queryTrans.do +acpsdk.batchTransUrl=https://gateway.test.95516.com/gateway/api/batchTrans.do +acpsdk.fileTransUrl=https://filedownload.test.95516.com/ +acpsdk.appTransUrl=https://gateway.test.95516.com/gateway/api/appTransReq.do +acpsdk.cardTransUrl=https://gateway.test.95516.com/gateway/api/cardTransReq.do + +#以下缴费产品使用,其余产品用不到 +acpsdk.jfFrontTransUrl=https://gateway.test.95516.com/jiaofei/api/frontTransReq.do +acpsdk.jfBackTransUrl=https://gateway.test.95516.com/jiaofei/api/backTransReq.do +acpsdk.jfSingleQueryUrl=https://gateway.test.95516.com/jiaofei/api/queryTrans.do +acpsdk.jfCardTransUrl=https://gateway.test.95516.com/jiaofei/api/cardTransReq.do +acpsdk.jfAppTransUrl=https://gateway.test.95516.com/jiaofei/api/appTransReq.do + +######################################################################## + +# 报文版本号,固定5.1.0,请勿改动 +acpsdk.version=5.1.0 + +# 签名方式,证书方式固定01,请勿改动 +acpsdk.signMethod=01 + +# 是否验证验签证书的CN,测试环境请设置false,生产环境请设置true。非false的值默认都当true处理。 +acpsdk.ifValidateCNName=false + +# 是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false。非true的值默认都当false处理。 +acpsdk.ifValidateRemoteCert=false + +#前台通知地址,填写后台接收银联前台通知的地址 +acpsdk.frontUrl=http://localhost:8085/union/frontRcvResponse + +#后台通知地址,填写后台接收银联后台通知的地址,必须外网能访问 +#111.204.128.115:8929 ---> 192.168.0.54:8087 +acpsdk.backUrl=http://souldays.top:8085/union/backRcvResponse +#111.204.128.115:8917 ---> 192.168.0.54:8085 +#acpsdk.backUrl=http://111.204.128.115:8917/garage/wx/pay/union/backRcvResponse +#111.204.128.115:8925 ---> 192.168.1.19:8087 +#acpsdk.backUrl=http://111.204.128.115:8925/garageWechat/wx/pay/union/backRcvResponse + +#########################入网测试环境签名证书配置 ################################ +# 多证书的情况证书路径为代码指定,可不对此块做配置。 +# 签名证书路径,必须使用绝对路径,如果不想使用绝对路径,可以自行实现相对路径获取证书的方法;测试证书所有商户共用开发包中的测试签名证书,生产环境请从cfca下载得到。 +# windows样例: +acpsdk.signCert.path=/certs/acp_test_sign.pfx +# linux样例(注意:在linux下读取证书需要保证证书有被应用读的权限)(后续其他路径配置也同此条说明) +#acpsdk.signCert.path=/SERVICE01/usr/ac_frnas/conf/ACPtest/acp700000000000001.pfx + +# 签名证书密码,测试环境固定000000,生产环境请修改为从cfca下载的正式证书的密码,正式环境证书密码位数需小于等于6位,否则上传到商户服务网站会失败 +acpsdk.signCert.pwd=000000 +# 签名证书类型,固定不需要修改 +acpsdk.signCert.type=PKCS12 + +##########################加密证书配置################################ +# 敏感信息加密证书路径(商户号开通了商户对敏感信息加密的权限,需要对 卡号accNo,pin和phoneNo,cvn2,expired加密(如果这些上送的话),对敏感信息加密使用) +acpsdk.encryptCert.path=/certs/acp_test_enc.cer + +##########################验签证书配置################################ +# 验签中级证书路径(银联提供) +acpsdk.middleCert.path=/certs/acp_test_middle.cer +# 验签根证书路径(银联提供) +acpsdk.rootCert.path=/certs/acp_test_root.cer + diff --git a/back-end_code/src/main/resources/templates/index.html b/back-end_code/src/main/resources/templates/index.html index b7c103a0bf06de07f244e9b73b107d09edfc2431..511f7b273f5a131a8dc156851c1cb58e15e93f18 100644 --- a/back-end_code/src/main/resources/templates/index.html +++ b/back-end_code/src/main/resources/templates/index.html @@ -1,58 +1,15 @@ - + - - demo - - - + + Title - - -
- - - -
- +

支付宝沙箱支付

+
订单编号:
+ 订单金额:
+ 订单标题:
+ +
\ No newline at end of file diff --git a/back-end_code/src/main/resources/templates/pay.html b/back-end_code/src/main/resources/templates/pay.html new file mode 100644 index 0000000000000000000000000000000000000000..d8a3be3c8a4ae5fd67de205fca57b57722488645 --- /dev/null +++ b/back-end_code/src/main/resources/templates/pay.html @@ -0,0 +1,10 @@ + + + + + Title + + +
+ + \ No newline at end of file diff --git a/back-end_code/src/main/resources/templates/query.html b/back-end_code/src/main/resources/templates/query.html new file mode 100644 index 0000000000000000000000000000000000000000..7654bb89e888f0a444a359c546c5300ea5a11ff6 --- /dev/null +++ b/back-end_code/src/main/resources/templates/query.html @@ -0,0 +1,10 @@ + + + + + Title + + +
+ + \ No newline at end of file