用java结合接口写个微信支付小程序的案例
时间: 2023-09-15 19:24:20 浏览: 106
微信小程序 支付后台java实现实例
好的,下面是一个简单的微信支付小程序的Java代码示例:
首先,我们需要创建一个接口,定义微信支付相关的方法:
```java
public interface WeChatPayService {
String unifiedOrder(String orderId, BigDecimal amount, String openid);
boolean verifyNotify(String notifyData);
}
```
接着,我们实现这个接口:
```java
public class WeChatPayServiceImpl implements WeChatPayService {
private static final String APP_ID = "your_app_id";
private static final String MCH_ID = "your_mch_id";
private static final String KEY = "your_key";
private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
private static final String NOTIFY_URL = "your_notify_url";
@Override
public String unifiedOrder(String orderId, BigDecimal amount, String openid) {
SortedMap<String, String> parameters = new TreeMap<>();
parameters.put("appid", APP_ID);
parameters.put("mch_id", MCH_ID);
parameters.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
parameters.put("body", "商品描述");
parameters.put("out_trade_no", orderId);
parameters.put("total_fee", amount.multiply(new BigDecimal(100)).intValue() + "");
parameters.put("spbill_create_ip", "127.0.0.1");
parameters.put("notify_url", NOTIFY_URL);
parameters.put("trade_type", "JSAPI");
parameters.put("openid", openid);
String sign = createSign(parameters, KEY);
parameters.put("sign", sign);
String requestXml = mapToXml(parameters);
String responseXml = HttpUtil.post(UNIFIED_ORDER_URL, requestXml);
Map<String, String> responseMap = xmlToMap(responseXml);
String prepayId = responseMap.get("prepay_id");
SortedMap<String, String> resultMap = new TreeMap<>();
resultMap.put("appId", APP_ID);
resultMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
resultMap.put("nonceStr", UUID.randomUUID().toString().replaceAll("-", ""));
resultMap.put("package", "prepay_id=" + prepayId);
resultMap.put("signType", "MD5");
String resultSign = createSign(resultMap, KEY);
resultMap.put("paySign", resultSign);
return mapToJson(resultMap);
}
@Override
public boolean verifyNotify(String notifyData) {
Map<String, String> map = xmlToMap(notifyData);
if (!map.containsKey("sign")) {
return false;
}
String sign = map.get("sign");
map.remove("sign");
String sign2 = createSign(map, KEY);
return sign.equals(sign2);
}
private String createSign(SortedMap<String, String> parameters, String key) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (StringUtils.isNotBlank(entry.getValue())) {
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
}
sb.append("key=").append(key);
return DigestUtils.md5Hex(sb.toString()).toUpperCase();
}
private String mapToXml(Map<String, String> map) {
StringBuilder sb = new StringBuilder("<xml>");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append("<").append(entry.getKey()).append(">")
.append(entry.getValue())
.append("</").append(entry.getKey()).append(">");
}
sb.append("</xml>");
return sb.toString();
}
private Map<String, String> xmlToMap(String xml) {
Map<String, String> map = new HashMap<>();
try {
Document doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
List<Element> elements = root.elements();
for (Element element : elements) {
map.put(element.getName(), element.getTextTrim());
}
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
private String mapToJson(Map<String, String> map) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
```
其中,`unifiedOrder` 方法用于生成预支付订单信息,并返回给前端;`verifyNotify` 方法用于验证微信支付异步通知的签名是否正确。
接着,我们可以在Spring Boot中使用这个接口:
```java
@RestController
public class WeChatPayController {
@Autowired
private WeChatPayService weChatPayService;
@PostMapping("/unifiedOrder")
public String unifiedOrder(@RequestParam String orderId,
@RequestParam BigDecimal amount,
@RequestParam String openid) {
return weChatPayService.unifiedOrder(orderId, amount, openid);
}
@PostMapping("/notify")
public String notify(@RequestBody String notifyData) {
if (weChatPayService.verifyNotify(notifyData)) {
// 处理支付成功逻辑
return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
} else {
return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>";
}
}
}
```
其中,`/unifiedOrder` 接口用于生成预支付订单信息,并返回给前端;`/notify` 接口用于接收微信支付的异步通知。如果签名验证成功,我们可以在这个接口中处理支付成功的逻辑。
以上就是一个简单的微信支付小程序的Java代码示例。
阅读全文