Selaa lähdekoodia

H5支付与Native支付调

anderx 4 vuotta sitten
vanhempi
commit
60e4e91f2f

+ 44 - 0
src/main/java/com/kede/common/controller/PublicApiController.java

@@ -4,6 +4,7 @@ package com.kede.common.controller;
 
 
 
+
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -18,6 +19,7 @@ import com.kede.activity.service.ActivityService;
 import com.kede.banners.service.BannersService;
 import com.kede.common.bo.Result;
 import com.kede.common.constant.ErrorConstants;
+import com.kede.common.model.Project;
 import com.kede.common.model.VisitingCustomers;
 import com.kede.common.utils.LoggerUtils;
 import com.kede.common.utils.StringUtils;
@@ -157,6 +159,48 @@ public class PublicApiController extends BaseController {
 		wxService.wxPayCallBack(req);
 		return NOTIFY_SUCCESS;
 	}
+	
+	
+	@RequestMapping(value = "/nativePay",method = RequestMethod.POST)
+	@CrossOrigin(origins="*",allowCredentials="true")
+	public Result wxNativePay(Project p) {
+		LoggerUtils.debug(getClass(), "===============微信nativePay==========================");
+		Result res=new Result();
+		p=projectService.get(p.getId());
+		if (p==null) {	
+			res.getError().add(buildError("","项目不存在"));
+			return res;
+		}
+		//网页支付目前有个BUG,就是可以无限发起订单,因为目前在未登录的情况下支付,则没有当前用户id
+		//则无法判断出重复订单
+		if (!projectService.checkBuy(p.getId(),0)) {
+			res.getError().add(buildError("","订单已存在"));
+			return res;
+		}
+		return res.data(wxService.pushNativePay(p,"NATIVE"));
+	}
+	
+	
+	
+	@RequestMapping(value = "/H5Pay",method = RequestMethod.POST)
+	@CrossOrigin(origins="*",allowCredentials="true")
+	public Result H5Pay(Project p) {
+		LoggerUtils.debug(getClass(), "===============微信nativePay==========================");
+		Result res=new Result();
+		p=projectService.get(p.getId());
+		if (p==null) {	
+			res.getError().add(buildError("","项目不存在"));
+			return res;
+		}
+		//网页支付目前有个BUG,就是可以无限发起订单,因为目前在未登录的情况下支付,则没有当前用户id
+		//则无法判断出重复订单
+		if (!projectService.checkBuy(p.getId(),0)) {
+			res.getError().add(buildError("","订单已存在"));
+			return res;
+		}
+		return res.data(wxService.pushNativePay(p,"MWEB"));
+	}
+	
 
 	
 	

+ 11 - 0
src/main/java/com/kede/user/controller/UserApiController.java

@@ -36,6 +36,11 @@ public class UserApiController extends BaseController{
 	private WxService wxService;
 
 	
+	/**
+	 * 	微信下单
+	 * @param id
+	 * @return
+	 */
 	@RequestMapping(value = "/wxPush", method = RequestMethod.POST)
 	public Result wxPush(Integer id) {
 		Result res=new Result();
@@ -56,6 +61,12 @@ public class UserApiController extends BaseController{
 		return res.data(map);
 	}
 	
+	/**
+	 * 	撤销订单
+	 * 
+	 * @param orderNo
+	 * @return
+	 */
 	@RequestMapping(value = "/wxClose", method = RequestMethod.GET)
 	public Result pushWxClose(String orderNo) {
 		Result res=new Result();

+ 1 - 1
src/main/java/com/kede/wxsdk/WXPayUtil.java

@@ -183,7 +183,7 @@ public class WXPayUtil {
      * @return 签名
      */
     public static String generateSignature(final Map<String, String> data, String key) throws Exception {
-        return generateSignature(data, key, SignType.HMACSHA256);
+        return generateSignature(data, key, SignType.MD5);
     }
 
     /**

+ 1 - 6
src/main/java/com/kede/wxsdk/service/WXPay.java

@@ -40,12 +40,7 @@ public class WXPay {
         this.config = config;
         this.autoReport = autoReport;
         this.useSandbox = useSandbox;
-        if (useSandbox) {
-            this.signType = SignType.MD5; // 沙箱环境
-        }
-        else {
-            this.signType = SignType.HMACSHA256;
-        }
+        this.signType = SignType.MD5;
         this.wxPayRequest = new WXPayRequest(config);
     }
 

+ 68 - 8
src/main/java/com/kede/wxsdk/service/WxService.java

@@ -25,6 +25,7 @@ import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.collections4.map.HashedMap;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
+import org.apache.http.ParseException;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpGet;
@@ -55,6 +56,11 @@ import com.kede.order.service.impl.OrderService;
 import com.kede.wxsdk.WXPayConstants;
 import com.kede.wxsdk.WXPayUtil;
 
+/**
+ * 	小程序
+ * @author Administrator
+ *
+ */
 @Service
 public class WxService {
 	
@@ -73,6 +79,7 @@ public class WxService {
 	@Value(value = "${wx.certPath}")
 	private String certPath;
 	
+	
 	@Autowired
 	private JDBCIdGenerator	idGenerator;
 	@Autowired
@@ -83,8 +90,10 @@ public class WxService {
 	@Autowired
 	private OrderMapper	orderMapper;
 	
+	
+	
 	/**
-	 * 	下单
+	 * 	小程序下单
 	 * @param p
 	 * @return
 	 */
@@ -430,20 +439,17 @@ public class WxService {
 	public JSONObject getPostMethod(String url,Map<String, Object>map){
 		HttpClient httpClient = HttpClientBuilder.create().build();
 		HttpPost httpPost = new HttpPost(url);
-		httpPost.addHeader("Content-type", "application/json; charset=utf-8");
+		httpPost.addHeader("Content-type", "application/json");
 		httpPost.setHeader("Accept", "application/json");
 		httpPost.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
-		HttpResponse response;
+		HttpResponse response = null;
 		try {
 			response = httpClient.execute(httpPost);
 		if (null == response || response.getStatusLine() == null) {
 			throw new Exception("Post Request For Url[{}] is not ok. Response is null");
 		} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
-			throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {}");
+			throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {"+response.getStatusLine().getStatusCode()+"}");
 		}
-		String resultString = EntityUtils.toString(response.getEntity());
-		JSONObject jsonObj = JSONObject.parseObject(resultString);
-		return jsonObj;
 		} catch (ClientProtocolException e) {
 			e.printStackTrace();
 		} catch (IOException e) {
@@ -451,7 +457,61 @@ public class WxService {
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
-		return null;
+		String resultString=null;
+		try {
+			resultString = EntityUtils.toString(response.getEntity());
+		} catch (ParseException | IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		JSONObject jsonObj = JSONObject.parseObject(resultString);
+		return jsonObj;
+		}
+
+		public Map<String, String> pushNativePay(Project p,String tradeType) {
+			WXPay wxpay = null;
+			Map<String, String> map = new HashMap<>();
+			try {
+				IWxPayConfig iWxPayConfig = new IWxPayConfig(appId, mchId, apiKiy, certPath);
+				wxpay = new WXPay(iWxPayConfig); // *** 注入自己实现的微信配置类, 创建WXPay核心类, WXPay 包括统一下单接口
+				InetAddress addr = InetAddress.getLocalHost();
+				String ip = addr.getHostAddress();
+				Map<String, String> data = new HashMap<String, String>();
+				data.put("body", p.getName());
+				String orderNo = idGenerator.generateId().toString();
+				data.put("out_trade_no", orderNo); // 订单唯一编号, 不允许重复
+				// 订单金额, 单位分
+				String amout = p.getAmount().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
+				Order o = new Order();
+				o.setOrderNo(orderNo);
+				o.setPayAmount(new BigDecimal(0));
+				o.setPayStatus(0);
+				o.setProjectAmount(p.getAmount());
+				o.setProjectId(p.getId());
+				o.setProjectName(p.getName());
+				o.setStatus(0);
+				o.setUid("");
+				data.put("total_fee", amout);
+				data.put("spbill_create_ip", ip); // 下单ip
+				data.put("notify_url", notifyUrl); // 订单结果通知, 微信主动回调此接口
+				data.put("trade_type", tradeType); // 固定填写
+				Map<String, String> wxPayMap = new HashMap<String, String>();
+				// 前端调起微信支付必要参数
+				String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
+				wxPayMap.put("appId", iWxPayConfig.getAppID());
+				wxPayMap.put("timeStamp", String.valueOf(new Date().getTime()));
+				wxPayMap.put("nonce_str", uuid);
+				String sign = WXPayUtil.generateSignature(wxPayMap, iWxPayConfig.getKey());
+				map.put("sign", sign);
+				map.put("out_trade_no", orderNo);
+				map = wxpay.unifiedOrder(data); // 微信sdk集成方法, 统一下单接口unifiedOrder, 此处请求 MD5加密
+				LoggerUtils.debug(getClass(), "微信支付下单成功, 返回值 response=%s", map);
+				orderService.insert(o);
+			} catch (Exception e) {
+				e.printStackTrace();
+				throw new BusinessException("支付异常");
+			}
+			return map;
 		}