以下是Java调用微信支付接口的示例代码:
1.配置微信支付参数
public class WeChatPayConfig {
// 商户号
public static final String MCH_ID = "xxxxxxxxxxxxx";
// 应用ID
public static final String APP_ID = "xxxxxxxxxxxxx";
// API密钥,在商户平台设置
public static final String API_KEY = "xxxxxxxxxxxxx";
// 统一下单API接口
public static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}
2.发起微信支付
public class WeChatPay {
/**
* 发起微信支付
*
* @param body 商品描述
* @param outTradeNo 商户订单号
* @param totalFee 订单总金额,单位为分
* @param spbillCreateIp 用户端实际ip
* @param notifyUrl 支付成功回调地址
* @param tradeType 支付类型,JSAPI或NATIVE或APP等
* @param openid 用户openid,tradeType为JSAPI时必传
* @return
*/
public static Map<String, String> weChatPay(String body, String outTradeNo, int totalFee, String spbillCreateIp, String notifyUrl, String tradeType, String openid) {
// 生成随机字符串
String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
// 组装请求参数
SortedMap<String, String> params = new TreeMap<>();
params.put("appid", WeChatPayConfig.APP_ID);
params.put("mch_id", WeChatPayConfig.MCH_ID);
params.put("nonce_str", nonceStr);
params.put("body", body);
params.put("out_trade_no", outTradeNo);
params.put("total_fee", String.valueOf(totalFee));
params.put("spbill_create_ip", spbillCreateIp);
params.put("notify_url", notifyUrl);
params.put("trade_type", tradeType);
if ("JSAPI".equals(tradeType)) {
params.put("openid", openid);
}
// 签名
String sign = WeChatPayUtil.createSign