Java - 微信支付

首先贴出官方文档,关于介绍,场景,参数说明,可以直接看文档:https://pay.weixin.qq.com/wiki/doc/api/index.html

一. APP支付

官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1

   推荐maven依赖:



    com.github.wxpay
    wxpay-sdk
    3.0.9

1. 【统一下单】

商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易会话标识后再在APP里面调起支付。

   微信统一工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class WXUtil {

    public static final String APP_ID = "";
    
    public static final String APPLET_APP_ID = "";
    
    public static final String MCH_ID = ""; // 微信商户号
   
    public static final String KEY = "";  // 微信支付密钥
    
    public static final String NOTIFY_URL = ""; // 微信支付成功回调url
  
    public static final String REFUND_NOTIFY_URL = "";   // 微信退款成功回调

    public static final String SIGN_PACKAGE = "Sign=WXPay";

    private static Cipher cipher = null;  //解码器


    public static String createSign(Map parameters) throws Exception {
        List keys = new ArrayList(parameters.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        Object value = parameters.get(key);
//        value = URLEncoder.encode(value, "UTF-8");
        if(StringUtils.isNotBlank(parameters.get(key)+"") && value != null) {
        	if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }	
        }
        }
        prestr += "&key="+KEY;
        return prestr;
    }
    
    public static Map objectToMap(Object obj) throws Exception { 
    	if(obj == null){ 
    	return null; 
    	} 
    	Map map = new HashMap(); 
    	Field[] declaredFields = obj.getClass().getDeclaredFields(); 
    	for (Field field : declaredFields) { 
    	field.setAccessible(true); 
    	map.put(field.getName(), field.get(obj)); 
    	} 
    	return map; 
    	}

    public static Map applayRefund(String userId, String payId, String orderNo, Double amount, Double refundMoney) throws Exception {
        Map map = new HashMap();
        map.put("appid", APP_ID);
        map.put("mch_id", MCH_ID);
        map.put("nonce_str", UUID_MD5.getUUID());
        map.put("transaction_id", payId);
        map.put("out_refund_no", orderNo);
        int total_fee = (int) (amount * 100);
        map.put("total_fee", total_fee+"");
        int refund_fee = (int) (refundMoney * 100);
        map.put("refund_fee", refund_fee+"");
        map.put("notify_url", REFUND_NOTIFY_URL);
                             
        String stringSign = WXUtil.createSign(map);
        String sign = WXPayUtil.MD5(stringSign).toUpperCase();
        map.put("sign", sign);

        String data = WXPayUtil.mapToXml(map);

        File file = new File("apiclient_cert.p12");
        InputStream in = new FileInputStream(file);

        char password[] = WXUtil.MCH_ID.toCharArray();
        java.io.InputStream certStream = in;
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(certStream, password);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1" }, null, new DefaultHostnameVerifier());

        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        String url = (new StringBuilder()).append("https://").append("api.mch.weixin.qq.com")
                .append("/secapi/pay/refund").toString();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", (new StringBuilder()).append(WXPayConstants.USER_AGENT).append(" ")
                .append(map.get("mch_id")).toString());
        httpPost.setEntity(postEntity);
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        org.apache.http.HttpEntity httpEntity = httpResponse.getEntity();
        String reponseString = EntityUtils.toString(httpEntity, "UTF-8");
        return WXPayUtil.xmlToMap(reponseString);
    }
    
    /**
     * 提现
     * @param openid 微信openid
     * @param realName 真实姓名
     * @param money 提现金额
     * @return
     * @throws Exception
     */
    public static Map wxWithdraw(String openid,String realName, Double money) throws Exception{
    	  Map map = new HashMap();
          map.put("mch_appid", APP_ID);
          map.put("mchid", MCH_ID);
          map.put("nonce_str", UUID_MD5.getUUID());
          map.put("partner_trade_no", UUID_MD5.getUUID());
          map.put("openid", openid);
          map.put("check_name", "FORCE_CHECK"); //强制实名,如需不校真实姓名,则改为NO_CHECK
          map.put("re_user_name", realName);
          int total_fee = (int) (money * 100);
          map.put("amount", total_fee+"");
          map.put("desc", "账户提现");
          map.put("spbill_create_ip", "xxx.xxx.xxx.xxx");

          String stringSign = WXUtil.createSign(map);
          String sign = WXPayUtil.MD5(stringSign).toUpperCase();
          map.put("sign", sign);

          String data = WXPayUtil.mapToXml(map);

          File file = new File("apiclient_cert.p12");

          InputStream in = new FileInputStream(file);

          char password[] = WXUtil.MCH_ID.toCharArray();
          java.io.InputStream certStream = in;
          KeyStore ks = KeyStore.getInstance("PKCS12");
          ks.load(certStream, password);
          KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
          kmf.init(ks, password);
          SSLContext sslContext = SSLContext.getInstance("TLS");
          sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
          SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                  new String[] { "TLSv1" }, null, new DefaultHostnameVerifier());

          BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
          CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
          String url = (new StringBuilder()).append("https://").append("api.mch.weixin.qq.com")
                  .append("/mmpaymkttransfers/promotion/transfers").toString();
          HttpPost httpPost = new HttpPost(url);
          RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
          httpPost.setConfig(requestConfig);
          StringEntity postEntity = new StringEntity(data, "UTF-8");
          httpPost.addHeader("Content-Type", "text/xml");
          httpPost.addHeader("User-Agent", (new StringBuilder()).append(WXPayConstants.USER_AGENT).append(" ")
                  .append(map.get("mch_id")).toString());
          httpPost.setEntity(postEntity);
          CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
          org.apache.http.HttpEntity httpEntity = httpResponse.getEntity();
          String reponseString = EntityUtils.toString(httpEntity, "UTF-8");
          return WXPayUtil.xmlToMap(reponseString);
    	
    	
    }

    /**
  * 微信返回参数解密
  * @param reqInfo
  * @return
  * @throws Exception
  */
    public static Map parseReqInfo(String reqInfo) throws Exception {
    	init();
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] base64ByteArr = decoder.decode(reqInfo);
 
        String result = new String(cipher.doFinal(base64ByteArr));
        return WXPayUtil.xmlToMap(result);
    }
 
    public static void init() {
        String key = getMD5(KEY);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Security.addProvider(new BouncyCastleProvider());
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }
 
    public static String getMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            String result = MD5(str, md);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
 
    public static String MD5(String strSrc, MessageDigest md) {
        byte[] bt = strSrc.getBytes();
        md.update(bt);
        String strDes = bytes2Hex(md.digest());
        return strDes;
    }
 
    public static String bytes2Hex(byte[] bts) {
        StringBuffer des = new StringBuffer();
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des.append("0");
            }
            des.append(tmp);
        }
        return des.toString();
    }

    public static String httpClient(String data) throws Exception{
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
        String url = (new StringBuilder()).append("https://").append("api.mch.weixin.qq.com").append("/pay/unifiedorder").toString();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", (new StringBuilder()).append(WXPayConstants.USER_AGENT).append(" ").append(WXUtil.MCH_ID).toString());
        httpPost.setEntity(postEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        org.apache.http.HttpEntity httpEntity = httpResponse.getEntity();
        String reponseString = EntityUtils.toString(httpEntity, "UTF-8");
        return reponseString;
    }

}

   统一下单 - 微信预支付

@NoArgsConstructor
@Data
@Accessors(chain = true)
public class WeixinPayReqDto {

    @ApiModelProperty(value="请求参数")
    private WeixinPayReqData data;

    @NoArgsConstructor
    @Data
    @Accessors(chain=true)
    public class WeixinPayReqData {
        @ApiModelProperty(value="总金额")
        private double totalMoney;
	       
        @ApiModelProperty(value="订单号")
        private String out_trade_no;

        @ApiModelProperty(value="openid")
        private String openid;
    }
}
@PostMapping("weixinPay")
public BaseDataResDto> weixinPay(@RequestBody WeixinPayReqDto param) throws Exception {
    return capitalMainLogService.weixinPay(param, maijiToken);
}
@Override
public BaseDataResDto> weixinPay(WeixinPayReqDto param) throws Exception {
    // 根据订单号查看订单是否存在
    ShopingOrder shopingOrder = new ShopingOrder();
    shopingOrder.setOrderNo(param.getData().getOut_trade_no());
    ShopingOrder newShopingOrder = shopingOrderMapper.selectOne(shopingOrder);
    if (newShopingOrder == null) return new BaseDataResDto<>(Status.PARAMETERERROR, "订单编号不存在");
    if (newShopingOrder.getStatus() != 0) {
        return new BaseDataResDto<>(Status.PARAMETERERROR, "该订单已支付");
    }
    // 校验支付金额和应付金额是否一致
    if (param.getData().getTotalMoney() != newShopingOrder.getAmount()) {
        return new BaseDataResDto<>(Status.PARAMETERERROR, "支付金额错误");
    }

    String out_trade_no = shopingOrder.getOrderNo() + "_" + (int) (Math.random() * 1000000);
    Map map = new HashMap();
    map.put("appid", WXUtil.APP_ID);
    map.put("mch_id", WXUtil.MCH_ID);
    map.put("nonce_str", UUID_MD5.getUUID());
    map.put("sign_type", "MD5");
    map.put("body", "商品支付");
    map.put("out_trade_no", out_trade_no);
    map.put("fee_type", "CNY");
    map.put("total_fee", (int) (param.getData().getTotalMoney() * 100) + "");
    map.put("spbill_create_ip", "192.168.100.8");
    map.put("notify_url", WXUtil.NOTIFY_URL);
    map.put("trade_type", "APP");
    map.put("sign", WXPayUtil.MD5(WXUtil.createSign(map)).toUpperCase());
    // 请求报文 (map转为xml)
    String data = WXPayUtil.mapToXml(map);

    Map mapResponse = WXPayUtil.xmlToMap(WXUtil.httpClient(data));
    BaseDataResDto paramMap = new BaseDataResDto(Status.SUCCESS);

    Map mapWeixinPay = new HashMap();
    if (mapResponse.get("return_code") != null && mapResponse.get("result_code") != null) {
        mapWeixinPay.put("appid", WXUtil.APP_ID);
        mapWeixinPay.put("partnerid", WXUtil.MCH_ID);
        if (mapResponse.get("prepay_id") == null) return new BaseDataResDto<>(Status.PARAMETERERROR);
        long time = System.currentTimeMillis() / 1000;
        mapWeixinPay.put("noncestr", Long.toString(time));
        mapWeixinPay.put("timestamp", Long.toString(time));
        mapWeixinPay.put("prepayid", (String) mapResponse.get("prepay_id"));
        mapWeixinPay.put("package", "Sign=WXPay");
        String signString = WXUtil.createSign(mapWeixinPay);
        String signs = WXPayUtil.MD5(signString).toUpperCase();
        mapWeixinPay.put("sign", signs);
        paramMap.setData(mapWeixinPay);
        newShopingOrder.setPrepayId((String) mapResponse.get("prepay_id"));
        newShopingOrder.setNonceStr(map.get("nonce_str") + "");
    } else {
        paramMap.setStatus(Status.PARAMETERERROR);
    }
    // 保存预支付订单号
    shopingOrderMapper.updateById(newShopingOrder.setOutTradeNo(out_trade_no));
    return paramMap;
}

Java - 微信支付_第1张图片    Java - 微信支付_第2张图片

成功返回给安卓/IOS,由他们调起微信收银台发起付款即可。

2. 【微信支付成功回调】 (支付结果通知)

支付完成后,微信会把相关支付结果及用户信息通过数据流的形式发送给商户,商户需要接收处理,并按文档规范返回应答。

该链接是通过【统一下单API】中提交的参数notify_url设置,如果链接无法访问,商户将无法接收到微信通知。

通知url必须为直接可访问的url,不能携带参数。

注意:

① 同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。

② 后台通知交互时,如果微信收到商户的应答不符合规范或超时,微信会判定本次通知失败,重新发送通知,直到成功为止(在通知一直不成功的情况下,微信总共会发起多次通知,通知频率为15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m),但微信不保证通知最终一定能成功。

③ 在订单状态不明或者没有收到微信支付结果通知的情况下,建议商户主动调用微信支付【查询订单API】确认订单状态。

@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
@NoArgsConstructor
@Data
@Accessors(chain=true)
public class PayResDto {
    private String return_msg;
    private String return_code;
    private String appid;
    private String mch_id;
    private String device_info;
    private String nonce_str;
    private String sign;
    private String result_code;
    private String err_code;
    private String err_code_des;
    private String openid;
    private String is_subscribe;
    private String trade_type;
    private String bank_type;
    private Integer total_fee;
    private String fee_type;
    private Integer cash_fee;
    private String cash_fee_type;
    private Integer coupon_fee;
    private Integer coupon_count;
    private String coupon_id_$n;
    private Integer coupon_fee_$n;
    private String transaction_id;
    private String out_trade_no;
    private String attach;
    private String time_end;
}
import com.github.wxpay.sdk.WXPayUtil;

@PostMapping("weixinPayCallBack")
public String weixinPayCallBack(@RequestBody PayResDto param) throws Exception {
    Map map = capitalMainLogService.weixinPayCallBack(param);
    return WXPayUtil.mapToXml(map);
}
@Override
public Map weixinPayCallBack(PayResDto param) {
    Map map = new HashMap();
    map.put("return_code", "SUCCESS");
    if (param == null) {
        map.put("return_msg", "参数为空");
         return map;
    }

    // 根据订单号查看订单信息
    ShopingOrder shopingOrder = shopingOrderService.selectOne(new EntityWrapper().eq("order_no", param.getOut_trade_no().substring(0, 20)));

    // 已经付款
    if (Arrays.asList(1, 2, 3, 5, 6).contains(shopingOrder.getStatus())) {
        map.put("return_msg", "OK");
        return map;
    }
             
    shopingOrder.setStatus(1).setPayId(param.getTransaction_id()).setPayDate(newDate()).setOutTradeNo(param.getOut_trade_no()).setPayType(2);
    // 修改支付状态为成功
    shopingOrderMapper.updateById(shopingOrder);

    // 分销
    distributionService.asyncDistributionFund(shopingOrder);
    map.put("return_msg", "OK");
    return map;
}

3. 【查询订单】

接口提供所有微信支付订单的查询,商户可以通过该接口主动查询订单状态,完成下一步的业务逻辑。

需要调用查询接口的情况:

◆ 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知;

◆ 调用支付接口后,返回系统错误或未知交易状态情况;

◆ 调用被扫支付API,返回USERPAYING的状态;

◆ 调用关单或撤销接口API之前,需确认支付状态;
 

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    Charset thirdRequest = Charset.forName("UTF-8");

    // 处理请求中文乱码问题
    List> messageConverters = restTemplate.getMessageConverters();
    for (HttpMessageConverter messageConverter : messageConverters) {
        if (messageConverter instanceof StringHttpMessageConverter) {
            ((StringHttpMessageConverter) messageConverter).setDefaultCharset(thirdRequest);
        }
        if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
            ((MappingJackson2HttpMessageConverter) messageConverter).setDefaultCharset(thirdRequest);
        }
        if (messageConverter instanceof AllEncompassingFormHttpMessageConverter) {
            ((AllEncompassingFormHttpMessageConverter) messageConverter).setCharset(thirdRequest);
        }
    }

    return restTemplate;
}
@Autowired
private RestTemplate restTemplate;

/** 微信查询订单 */
@PostMapping("weixinOrderQuery")
public Map weixinOrderQuery(@RequestParam String out_trade_no)  throws Exception {
    Map map = new HashMap();
    map.put("appid", WXUtil.APP_ID);
    map.put("mch_id", WXUtil.MCH_ID);
    map.put("nonce_str", UUID_MD5.getUUID());
    map.put("out_trade_no", out_trade_no);
    String sign = WXPayUtil.MD5(WXUtil.createSign(map)).toUpperCase();
    map.put("sign", sign);

    String data = WXPayUtil.mapToXml(map);

    String response = restTemplate.postForObject("https://api.mch.weixin.qq.com/pay/orderquery", data, String.class);
    return WXPayUtil.xmlToMap(response);
}

Java - 微信支付_第3张图片   Java - 微信支付_第4张图片

4. 【退款】

当交易发生之后一段时间内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付款退还给买家,微信支付将在收到退款请求并且验证成功之后,按照退款规则将支付款按原路退到买家帐号上。

注意:

◆ 交易时间超过一年的订单无法提交退款;

◆ 微信支付退款支持单笔交易分多次退款,多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。申请退款总金额不能超过订单金额。 一笔退款失败后重新提交,请不要更换退款单号,请使用原商户退款单号。

◆ 请求频率限制:150qps,即每秒钟正常的申请退款请求次数不超过150次

   错误或无效请求频率限制:6qps,即每秒钟异常或错误的退款申请请求不超过6次

◆ 每个支付订单的部分退款次数不能超过50次

◆ 如果同一个用户有多笔退款,建议分不同批次进行退款,避免并发退款导致退款失败

@Override
public BaseResDto executeRefund(String orderRefundId) throws Exception{

    ShoppingOrderRefundEntity shoppingOrderRefund = shopingOrderRefundService.selectById(orderRefundId).setRefundMiddleTime(new Date()).setStatus(3);//退款中
    String orderId = shoppingOrderRefund.getOrderId();
    ShopingOrder shopingOrder = shopingOrderMapper.selectById(orderId)         .setRefundStatus(3);//退款中
    Double refundMoney = shoppingOrderRefund.getRefundMoney();
    Double amount = shopingOrder.getAmount();
    if (refundManey > amount) 
        return BaseResDto.baseResDto(Status.ERROR, "退款金额错误!");
    Map wxMap = WXUtil.applayRefund(shopingOrder.getUserId(), shopingOrder.getPayId(), shopingOrder.getOutTradeNo(), amount, refundMoney);
    if (!wxMap.get("result_code").equals("SUCCESS"))
        return BaseResDto.baseResDto(Status.ERROR, "申请微信退款失败!");

    // 下面接入自己的业务逻辑...

    return new BaseResDto(Status.SUCCESS);       
}

5. 【退款回调通知】

当商户申请的退款有结果后(退款状态为:退款成功、退款关闭、退款异常),微信会把相关结果发送给商户,商户需要接收处理,并返回应答。
对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功(通知频率为15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m)。
注意:同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。
推荐的做法是,当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。
特别说明:退款结果对重要的数据进行了加密,商户需要用商户秘钥进行解密后才能获得结果通知的内容。

@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
@NoArgsConstructor
@Data
@Accessors(chain = true)
public class WXRefundReqDto { //严格按照微信官方文档封装的实体类
	
    private String return_msg;
    private String return_code;
    private String appid;
    private String mch_id;
    private String nonce_str;
    private String req_info;
    private String transaction_id; //微信订单号
    private String out_trade_no; //商户订单号
    private String refund_id; //微信退款单号
    private String out_refund_no; //商户退款单号
    private String total_fee; //订单金额
    private String settlement_total_fee; //应结订单金额
    private String refund_fee; //申请退款金额
    private String settlement_refund_fee; //退款金额
    private String refund_status; //退款状态
    private String success_time; //退款成功时间
    private String refund_recv_accout; //退款入账账户
    private String refund_account; //退款资金来源
    private String refund_request_source; //退款发起来源

}
@PostMapping("refundCallBack")
public String refundCallBack(@RequestBody WXRefundReqDto param) throws Exception {
    Map map = capitalMainLogService.refundCallBack(param);
    return WXPayUtil.mapToXml(map);
}
@Override
public Map refundCallBack(WXRefundReqDto param) throws Exception {
       
    Map map = new HashMap();
    if (param == null) {
        map.put("return_code", "FAIL");
        map.put("return_msg", "参数为空");
        return map;
    }
    if (!"SUCCESS".equals(param.getReturn_code())) {
        map.put("return_code", "FAIL");
        map.put("return_msg", "退款失败");
        return map;
    }

    Map signMap = objectToMap(param);
    signMap.remove("return_code");
    signMap.remove("return_msg");
    signMap.remove("appid");
    signMap.remove("mch_id");
    signMap.remove("nonce_str");
    signMap.remove("req_info");
    String refundSignString = WXUtil.createSign(signMap);
    String sign = WXPayUtil.MD5(refundSignString).toUpperCase();
    // 验证签名
    if (!sign.equals(param.getReq_info())) {
        map.put("return_code", "FAIL");
        map.put("return_msg", "签名错误");
    }

    // 根据订单号查看订单信息
    String order_no = (String) WXUtil.parseReqInfo(param.getReq_info()).get("out_trade_no");
    ShopingOrder shopingOrder = shopingOrderMapper.selectOne(new ShopingOrder().setOutTradeNo(order_no));

    // 已经退款
    if (shopingOrder.getStatus() == 4) {
        map.put("return_msg", "OK");
        map.put("return_code", "SUCCESS");
        return map;
    }

    // 修改订单表退款状态     
    shopingOrder.setRefundStatus(4); //退款成功
    if (!shopingOrderService.updateById(shopingOrder)) {
        map.put("return_code", "FAIL");
        return map;
    }

    // 其他业务逻辑自行编写...

    map.put("return_msg", "OK");
    map.put("return_code", "SUCCESS");
    return map;
}

6. 【查询退款】

提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。

@Autowired
private RestTemplate restTemplate;

/** 查询微信退款 */
@PostMapping("wxRefundQuery")
public Map wxRefundQuery(@RequestParam String out_trade_no) throws Exception{
    Map map = new HashMap();
    map.put("appid", WXUtil.APP_ID);
    map.put("mch_id", WXUtil.MCH_ID);
	map.put("nonce_str", UUID_MD5.getUUID());
    map.put("out_trade_no", out_trade_no);
	String sign = WXPayUtil.MD5(WXUtil.createSign(map)).toUpperCase();
	map.put("sign", sign);

    String data = WXPayUtil.mapToXml(map);

    String response = restTemplate.postForObject("https://api.mch.weixin.qq.com/pay/refundquery", data, String.class);
    return WXPayUtil.xmlToMap(response);
}

Java - 微信支付_第5张图片

7. 【企业付款到零钱】(提现)

使用条件和开通步骤参考官方文档:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_1

企业付款为企业提供付款至用户零钱的能力,支持通过API接口付款,或通过微信支付商户平台(pay.weixin.qq.com)网页操作付款。

【使用条件】(切记,博主就被坑过)

◆ 商户号(或同主体其他非服务商商户号)已入驻90日

◆ 截止今日回推30天,商户号(或同主体其他非服务商商户号)连续不间断保持有交易

◆ 登录微信支付商户平台-产品中心,开通企业付款。

◆ spbill_create_ip 必须在商户平台配置好IP白名单

@PostMapping("withdraw")
public BaseResDto withdraw(@RequestParam Bigdecimal money,@RequestHeader("token") String token) {
       
    // 验证token,并根据token获取用户实体UserEntity,此处省略...

    Map map = WXUtil.wxWithdraw(userEntity.getWxOpenId(), userEntity.getRealName(), money); //如果check_name为NO_CHECK,则传昵称也可以

    if (!("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))))
        return new BaseResDto(Status.PARAMETERERROR, "提现失败");

    // 此处编写业务逻辑,并记录提现日志

    return new BaseResDto(Status.SUCCESS);
}

二. 扫码支付

Native支付可分为两种模式,商户根据支付场景选择相应模式。

Java - 微信支付_第6张图片

一般我们电商网站都会选用模式二:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5

@RestController
public class WxNativePay {

    @PostMapping("/wxNativePay")
    public BaseDataResDto wxNativePay()  {
        try{
            Map map = new HashMap();
            map.put("appid", WXUtil.APP_ID);
            map.put("mch_id", WXUtil.MCH_ID);
            map.put("nonce_str", UUID_MD5.getUUID());
            map.put("sign_type", "MD5");
            map.put("body", "商品支付");
            map.put("out_trade_no", "1234560001");
            map.put("fee_type", "CNY");
            map.put("total_fee", 10 + "");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", WXUtil.NOTIFY_URL);
            map.put("trade_type", "NATIVE");
            map.put("sign", WXPayUtil.MD5(WXUtil.createSign(map)).toUpperCase());
            // 请求报文 (map转为xml)
            String data = WXPayUtil.mapToXml(map);
            Map mapResponse = WXPayUtil.xmlToMap(WXUtil.httpClient(data));

            if (Objects.equals(mapResponse.get("result_code"),"SUCCESS")) {
                String content = mapResponse.get("code_url");
                JSONObject json = new JSONObject();
                json.put("codeUrl", content);
                return new BaseDataResDto(Status.SUCCESS).setData(json);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseDataResDto(Status.ERROR);
    }
}

Java - 微信支付_第7张图片      Java - 微信支付_第8张图片

直接将code_url返给前端,前端调用第三方库转化为二维码,供用户扫码付款;注意:code_url有效期为2小时,过期后扫码不能再发起支付。

【小结】:

原理很简单,签名验签是关键,无非就是API;微信小程序支付,H5,Web扫码支付,APP支付,区别不大,且支付结果通知(异步回调),查询订单,退款,查询退款等的API是一致的;下单API仅仅也只是 trade_type 不同而已 ~

你可能感兴趣的:(第三方支付,java)