Attention! Attention! Attention!
It’s so important that it should be repeated for three times.
Just make the following changes:
1. The front end modifies the circled URL address
Util needs to be changed to its own APP_ID KEY MCH_ID certPath
3. The IMPL layer mainly changes NOTIFY_URL
The introduction of pom
< the dependency > < groupId > com. Making. Wxpay < / groupId > < artifactId > wxpay - SDK < / artifactId > < version > 0.0.3 < / version > </dependency>Copy the code
uniapp
WxPay () {var price =0.01; Console. log(price) uni.request({url: 'XXXXXX /order/wx', // domain name + interface method: 'POST', header: {'content-type': 'application/x-www-form-urlencoded' }, data: { 'price': price, }, success: function(data) { console.log(JSON.stringify(data.data)) uni.requestPayment({ provider: 'wxpay', orderInfo: Function (res) {console.log('success:' + json.stringify (res)); }, fail: function(err) { uni.showToast({ title:JSON.stringify(err), duration:100000000, icon:'none' }) console.log('fail:' + JSON.stringify(err)); }}); }}); }Copy the code
Back-end code:
controller
1 package com.tf.medicaworkers.wxpay; 2 3 import io.swagger.annotations.ApiOperation; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.web.bind.annotation.PostMapping; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RestController; 8 9 import javax.servlet.http.HttpServletRequest; 10 import java.io.BufferedReader; 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.io.InputStreamReader; 14 import java.util.Map; 15 16 @RestController 17 @RequestMapping("/order") 18 public class OrderController { 19 20 @Autowired 21 private WxService wxService; 22 23 @PostMapping("/wx") 24 public Map wxAdd(HttpServletRequest request, Throws Exception {26 int prices= (int) (price*100); float price) throws Exception {26 int prices= (int) (price*100); 27 return wxService.doUnifiedOrder(request,prices); 31 @apiOperation (" HttpServletRequest Request ") 32 public String wxPayNotify(HttpServletRequest Request) {32 public String wxPayNotify(HttpServletRequest Request) { 33 String resXml = ""; 34 try { 35 InputStream inputStream = request.getInputStream(); 37 BufferedReader reader = new BufferedReader(new InputStreamReader(InputStream)); 38 StringBuilder sb = new StringBuilder(); 39 String line = null; 40 try { 41 while ((line = reader.readLine()) ! = null) { 42 sb.append(line + "\n"); 43 } 44 } catch (IOException e) { 45 System.out.println(e.getMessage()); 46 } finally { 47 try { 48 inputStream.close(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 resXml = sb.toString(); 54 String result = wxService.payBack(resXml); 55 return result; 56} catch (Exception e) {57 system.out.println (" + LLDB message ()); 58 String result = "<xml>" + "<return_code><! [CDATA[FAIL]]></return_code>" + "<return_msg><! [CDATA[message empty]]></return_msg>" + "</ XML >"; 59 return result; 60} 61} 62}Copy the code
util
1 package com.tf.medicaworkers.wxpay; 2 3 import com.github.wxpay.sdk.WXPayConfig; 4 import org.springframework.util.ClassUtils; 5 6 import java.io.ByteArrayInputStream; 7 import java.io.File; 8 import java.io.FileInputStream; 9 import java.io.InputStream; 10 11 public class WXConfigUtil implements WXPayConfig { 12 private byte[] certData; 13 public static final String APP_ID = "xxxxxxxx"; //appid 14 public static final String KEY = "xxxxxxxxxxxx"; 15 public static final String MCH_ID = "XXXXX "; Merchant ID 16 17 public WXConfigUtil() throws Exception {18 19 20 String certPath = "D:/Java/tfMW/JAR/weixin/apiclient_cert.p12"; 21 22 File File = new File(certPath); 23 System.out.println(certPath); 24 InputStream certStream = new FileInputStream(file); 25 this.certData = new byte[(int) file.length()]; 26 certStream.read(this.certData); 27 certStream.close(); 28 } 29 30 @Override 31 public String getAppID() { 32 return APP_ID; @override 37 public String getMchID() {37 return MCH_ID; 39 } 40 41 @Override 42 public String getKey() { 43 return KEY; 44 } 45 46 @Override 47 public InputStream getCertStream() { 48 ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData); 49 return certBis; 50 } 51 52 @Override 53 public int getHttpConnectTimeoutMs() { 54 return 8000; 55 } 56 57 @Override 58 public int getHttpReadTimeoutMs() { 59 return 10000; 60}} 61Copy the code
The service layer
package com.tf.medicaworkers.wxpay;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public interface WxService {
String payBack(String resXml);
Map doUnifiedOrder(HttpServletRequest request, int price) throws Exception;
}
Copy the code
Impl layer
package com.tf.medicaworkers.wxpay; import com.github.wxpay.sdk.WXPay; import com.github.wxpay.sdk.WXPayConstants; import com.github.wxpay.sdk.WXPayUtil; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Service public class WxServiceImpl implements WxService{ // public static final String SPBILL_CREATE_IP = ""; Public static final String NOTIFY_URL = "http://127.0.0.1:8234/order/notify"; Public static final String TRADE_TYPE_APP = "APP"; // Type APP, JSPI...... @Override public String payBack(String resXml) { WXConfigUtil config = null; try { config = new WXConfigUtil(); } catch (Exception e) { e.printStackTrace(); } WXPay wxpay = new WXPay(config); String xmlBack = ""; Map<String, String> notifyMap = null; try { notifyMap = WXPayUtil.xmlToMap(resXml); / / call the official SDK into map types data if (wxpay. IsPayResultNotifySignatureValid (notifyMap)) {/ / verify the signature is valid, String return_code = notifymap. get("return_code"); // State String out_trade_NO = notifymap. get("out_trade_no"); // State String out_trade_no = notifymap. get("out_trade_no"); If (return_code.equals("SUCCESS")) {if (out_trade_no! // Pay attention to special cases: the order has been refunded, but received a successful payment notification, should not change the merchant's order status from refund to payment success // Pay attention to special cases: The same notification may be sent to the merchant System by wechat server for several times, so it is necessary to check whether the data has been processed before persisting. If it has been processed, it directly returns a success sign // Business data persisting system.err. System.err.println(out_trade_no); xmlBack = "<xml>" + "<return_code><! [CDATA[SUCCESS]]></return_code>" + "<return_msg><! [CDATA[OK]]></return_msg>" + "</xml> "; } else {system.err. Println (" wechat mobile payment callback failed order number :{}"); System.err.println(out_trade_no); xmlBack = "<xml>" + "<return_code><! [CDATA[FAIL]]></return_code>" + "<return_msg><! [CDATA[message empty]]></return_msg>" + "</ XML >"; } } return xmlBack; } else {// Sign error, if there is no sign field in the data, also consider the sign error // do not store the failed data? System.err. Println (" Mobile payment callback notification signature error "); xmlBack = "<xml>" + "<return_code><! [CDATA[FAIL]]></return_code>" + "<return_msg><! [CDATA[message empty]]></return_msg>" + "</ XML >"; return xmlBack; }} catch (Exception e) {system.err.println (" mobile payment callback signature error "); System.err.println(e); xmlBack = "<xml>" + "<return_code><! [CDATA[FAIL]]></return_code>" + "<return_msg><! [CDATA[message empty]]></return_msg>" + "</ XML >"; } return xmlBack; } @Override public Map doUnifiedOrder(HttpServletRequest request,int price) throws Exception { try { WXConfigUtil config = new WXConfigUtil(); WXPay wxpay = new WXPay(config); Map<String, String> data = new HashMap<>(); Data.put (" appID ", config.getAppId ()); data.put("mch_id", config.getMchID()); data.put("nonce_str", WXPayUtil.generateNonceStr()); String body = "Order payment "; data.put("body", body); data.put("out_trade_no", System.currentTimeMillis()+ ""); data.put("total_fee", String.valueOf(price)); // Own server IP address data.put(" spbill_create_IP ", request.getremoteaddr ()); // Own server IP address data.put(" spbill_create_IP ", request.getremoteaddr ()); Data. put(" notify_URL ", notify_url); // Trade type data.put("trade_type", TRADE_TYPE_APP); // Attach data, which is returned as is in the query API and payment notice. This field is mainly used for custom data data.put("attach", ""); data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5)); Map<String, String> Response = wxpay.unifiedOrder(data); System.out.println(response); If ("SUCCESS".equals(response.get("return_code"))) {Map<String, String> param = new HashMap<>(); param.put("appid", config.getAppID()); param.put("partnerid", response.get("mch_id")); param.put("prepayid", response.get("prepay_id")); param.put("package", "Sign=WXPay"); param.put("noncestr", WXPayUtil.generateNonceStr()); param.put("timestamp", System.currentTimeMillis() / 1000 + ""); param.put("sign", WXPayUtil.generateSignature(param, config.getKey(), WXPayConstants.SignType.MD5)); System.out.println(param); return param; } } catch (Exception e) { e.printStackTrace(); Throw new Exception(" order failed "); } throw new Exception(" order failed "); }}Copy the code