Sfoglia il codice sorgente

上传文件至 ''

微信支付企业打款模板代码
恐龙ID 5 anni fa
parent
commit
bb6cfb4902
2 ha cambiato i file con 403 aggiunte e 0 eliminazioni
  1. 143 0
      AbstractWechatPaymentHandler.java
  2. 260 0
      WechatPaymentHandler.java

+ 143 - 0
AbstractWechatPaymentHandler.java

@@ -0,0 +1,143 @@
+package com.mb.payment.handler.wchat;
+
+import cn.beecloud.bean.TransferParameter;
+import com.mb.payment.context.IPayment;
+import com.mb.payment.context.RefundContext;
+import com.mb.payment.exception.PaymentException;
+import com.mb.payment.handler.AbstractPaymentHandler;
+import net.sf.json.xml.XMLSerializer;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLContexts;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.*;
+import java.security.cert.CertificateException;
+
+public abstract class AbstractWechatPaymentHandler extends AbstractPaymentHandler {
+
+
+    protected String appId;
+    /**
+     * 商户号id
+     */
+    protected String mchId;
+
+    /**
+     * API密钥
+     */
+    protected String apiKey;
+    protected String notifyPayUrl;
+    protected String notifyRefundUrl;
+
+
+    public AbstractWechatPaymentHandler(String appId, String mchId, String apiKey, String notifyPayUrl, String notifyRefundUrl) {
+        this.appId = appId;
+        this.mchId = mchId;
+        this.apiKey = apiKey;
+        this.notifyPayUrl = notifyPayUrl;
+        this.notifyRefundUrl = notifyRefundUrl;
+    }
+
+    @Override
+    public String refundApply(RefundContext refundContext) {
+        return null;
+    }
+
+    @Override
+    public boolean isPayment(String orderNo) {
+        return false;
+    }
+
+    @Override
+    public String findPaymentOrder(String orderNo) {
+        return null;
+    }
+
+    @Override
+    public String transfer(TransferParameter transferParameter){
+        throw new UnsupportedOperationException("不支持的操作");
+    }
+
+    protected String sendSSLRequest(String url,String mapToXml) {
+        CloseableHttpClient httpclient = null;
+        try {
+            httpclient = getCloseableHttpClient();
+            HttpPost httpost = new HttpPost(url); // 设置响应头信息
+            httpost.setEntity(new StringEntity(mapToXml, "UTF-8"));
+            CloseableHttpResponse response = httpclient.execute(httpost);
+            try {
+                HttpEntity entity = response.getEntity();
+                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
+                EntityUtils.consume(entity);
+                XMLSerializer xmlSerializer = new XMLSerializer();
+                String result = xmlSerializer.read(jsonStr).toString();
+                log.info("微信小程序返回信息:" + result);
+                return result;
+            } finally {
+                response.close();
+            }
+        } catch (Exception ex) {
+            log.error("发送支付请求错误", ex);
+        } finally {
+            if (httpclient != null) {
+                try {
+                    httpclient.close();
+                } catch (IOException e) {
+                    log.error("关闭httpclient错误", e);
+                }
+            }
+        }
+        log.info("支付参数"+mapToXml);
+        throw new PaymentException("支付渠道不可用,请稍后再试");
+    }
+
+
+    protected CloseableHttpClient getCloseableHttpClient() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
+        KeyStore keyStore = KeyStore.getInstance("PKCS12");
+        InputStream instream = this.getClass().getResourceAsStream("/cert/apiclient_cert.p12");
+        try {
+            keyStore.load(instream, this.mchId.toCharArray());
+        } finally {
+            instream.close();
+        }
+        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, this.mchId.toCharArray()).build();
+        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
+                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
+    }
+
+    @Override
+    public String doPay(IPayment payment) throws PaymentException {
+        return null;
+    }
+
+    @Override
+    public String refund(RefundContext refundContext) throws Exception {
+        return null;
+    }
+
+    public String getAppId() {
+        return appId;
+    }
+
+    public void setAppId(String appId) {
+        this.appId = appId;
+    }
+
+    public String getMchId() {
+        return mchId;
+    }
+
+    public void setMchId(String mchId) {
+        this.mchId = mchId;
+    }
+}

+ 260 - 0
WechatPaymentHandler.java

@@ -0,0 +1,260 @@
+package com.mb.payment.handler.wchat;
+
+import cn.beecloud.bean.RedpackInfo;
+import cn.beecloud.bean.TransferParameter;
+import com.alibaba.fastjson.JSONObject;
+import com.mb.game.platform.util.CommonUtil;
+import com.mb.game.platform.util.NumberUtils;
+import com.mb.payment.context.PaymentContext;
+import com.mb.payment.exception.PaymentException;
+import com.mb.payment.handler.wchat.parameter.WchatTransferParameter;
+import com.mb.payment.handler.wchat.parameter.WechatTransferBankParameter;
+import com.mb.payment.handler.wchat.parameter.WechatTransferSmallChangeParameter;
+import com.mb.payment.utils.WechatRSAUtils;
+import org.apache.commons.lang.StringUtils;
+
+import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 微信公众号支付
+ */
+public class WechatPaymentHandler extends AbstractWechatPaymentHandler {
+    /**
+     * 红包转账
+     */
+    private String transferUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
+
+    private String redpackQueryUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
+
+    //转款到零钱
+    private final String transferSmallChangeUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
+
+    //转款到银行卡
+    private final String transferSmallBankUrl = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
+
+
+
+    public WechatPaymentHandler(String appId, String mchId, String apiKey, String notifyPayUrl, String notifyRefundUrl) {
+        super(appId, mchId, apiKey, notifyPayUrl, notifyRefundUrl);
+    }
+
+    @Override
+    public String doRestPay(PaymentContext paymentContext) {
+        throw new UnsupportedOperationException("不支持的操作");
+    }
+
+    @Override
+    public String transfer(TransferParameter transferParameter) {
+        Map<String, Object> parameter = new HashMap<>();
+        String sendUrl;
+        if (transferParameter instanceof WchatTransferParameter){
+            transferParameter(parameter, (WchatTransferParameter) transferParameter);
+            sendUrl = transferUrl;
+        }else if (transferParameter instanceof WechatTransferBankParameter){
+            transferBankParameter(parameter, (WechatTransferBankParameter) transferParameter);
+            sendUrl = transferSmallBankUrl;
+        }else if (transferParameter instanceof WechatTransferSmallChangeParameter){
+            transferSmallChangeParameter(parameter, (WechatTransferSmallChangeParameter) transferParameter);
+            sendUrl = transferSmallChangeUrl;
+        }else {
+            throw new PaymentException("不支持的参数");
+        }
+
+        parameter.put("nonce_str", NumberUtils.getNonceString());
+        parameter.put("sign", NumberUtils.getSign(parameter, apiKey));
+        String mapToXml;
+        try {
+            mapToXml = CommonUtil.mapToXml(parameter);
+        } catch (Exception ex) {
+            throw new PaymentException("支付参数错误", ex);
+        }
+
+        String result = sendSSLRequest(sendUrl, mapToXml);
+        JSONObject jsonObject = JSONObject.parseObject(result);
+        if (!jsonObject.get("return_code").toString().equals("SUCCESS") || !jsonObject.get("result_code").toString().equals("SUCCESS")) {
+            log.info(mapToXml + "-" + jsonObject.toJSONString());
+            throw new PaymentException("支付错误");
+        }
+        return result;
+    }
+
+    /**
+     * 企业打款到银行卡
+     * @param parameter
+     * @param wchatTransferObject
+     */
+    private void transferBankParameter(Map<String, Object> parameter, WechatTransferBankParameter wchatTransferObject){
+        parameter.put("mch_id", this.mchId);
+        parameter.put("partner_trade_no", wchatTransferObject.getPartner_trade_no());
+        parameter.put("bank_code", wchatTransferObject.getBank_code());
+
+        try{
+            parameter.put("enc_bank_no", WechatRSAUtils.encrypt(wchatTransferObject.getEnc_bank_no()));
+            parameter.put("enc_true_name", WechatRSAUtils.encrypt(wchatTransferObject.getEnc_true_name()));
+        }catch (Exception e){
+            log.info(parameter.toString()+"----enc_bank_no:"+wchatTransferObject.getEnc_bank_no()+"---enc_true_name:"+wchatTransferObject.getEnc_true_name());
+            throw new PaymentException("对银行卡或收款方用户名加密失败");
+        }
+        BigDecimal amount = wchatTransferObject.getAmount();
+        if (amount.compareTo(new BigDecimal("0.01")) < 0){
+            log.info(parameter.toString() + "---" + amount);
+            throw new PaymentException("支付金额错误, 小于最低支付金额");
+        }
+        parameter.put("amount", amount.multiply(new BigDecimal(100)).intValue());
+        parameter.put("desc", wchatTransferObject.getDesc());
+    }
+
+    /**
+     * 企业打款到零钱
+     * @param parameter
+     * @param wchatTransferObject
+     */
+    private void transferSmallChangeParameter(Map<String, Object> parameter, WechatTransferSmallChangeParameter wchatTransferObject){
+        parameter.put("mchid", this.mchId);
+        parameter.put("mch_appid", this.appId);
+        parameter.put("check_name", "FORCE_CHECK");
+
+        parameter.put("partner_trade_no", wchatTransferObject.getPartner_trade_no());
+        parameter.put("openid", wchatTransferObject.getOpenid());
+        parameter.put("re_user_name", wchatTransferObject.getRe_user_name());
+        BigDecimal amount = wchatTransferObject.getAmount();
+        if (amount.compareTo(new BigDecimal("0.3")) < 0){
+            log.info(parameter.toString() + "---" + amount);
+            throw new PaymentException("支付金额错误, 小于最低支付金额");
+        }
+        parameter.put("amount", amount.multiply(new BigDecimal(100)).intValue());
+        parameter.put("desc", wchatTransferObject.getDesc());
+        parameter.put("spbill_create_ip", wchatTransferObject.getSpbill_create_ip());
+        parameter.put("device_info", wchatTransferObject.getDevice_info());
+    }
+
+    /**
+     * 红包转账
+     * @param parameter
+     * @param wchatTransferObject
+     */
+    private void transferParameter(Map<String, Object> parameter, WchatTransferParameter wchatTransferObject){
+        parameter.put("mch_billno", wchatTransferObject.getTransferNo());
+        parameter.put("mch_id", this.mchId);
+        parameter.put("wxappid", this.appId);
+        parameter.put("send_name", wchatTransferObject.getOrgName());
+        parameter.put("re_openid", wchatTransferObject.getChannelUserId());
+        parameter.put("total_amount", wchatTransferObject.getTotalFee());
+        parameter.put("total_num", 1);
+        RedpackInfo redpackInfo = wchatTransferObject.getRedpackInfo();
+        parameter.put("wishing", redpackInfo.getWishing());
+        parameter.put("client_ip", wchatTransferObject.getClientIp());
+        parameter.put("act_name", redpackInfo.getActivityName());
+        parameter.put("remark", wchatTransferObject.getDescription());
+        parameter.put("scene_id", wchatTransferObject.getSceneId());
+    }
+
+    @Override
+    public String findTransferOder(String orderNo) {
+        if (StringUtils.isEmpty(orderNo)) {
+            throw new PaymentException("不支持的参数");
+        }
+        Map<String, Object> parameter = new HashMap<>();
+        parameter.put("nonce_str", NumberUtils.getNonceString());
+        parameter.put("mch_billno", orderNo);
+        parameter.put("mch_id", this.mchId);
+        parameter.put("appid", this.appId);
+        parameter.put("bill_type", "MCHT");
+        parameter.put("sign", NumberUtils.getSign(parameter, apiKey));
+        String mapToXml = null;
+        try {
+            mapToXml = CommonUtil.mapToXml(parameter);
+        } catch (Exception ex) {
+            throw new PaymentException("支付参数错误", ex);
+        }
+
+        String result = sendSSLRequest(redpackQueryUrl, mapToXml);
+        JSONObject jsonObject = JSONObject.parseObject(result);
+        if (!jsonObject.get("return_code").toString().equals("SUCCESS") || !jsonObject.get("result_code").toString().equals("SUCCESS")) {
+            log.info(mapToXml + "-" + jsonObject.toJSONString());
+            throw new PaymentException("支付错误");
+        }
+        return result;
+    }
+
+    private String encryptionInfoData(String data){
+        Map<String, Object> parameter = new HashMap<>();
+        parameter.put("mch_id", this.mchId);
+        parameter.put("sign_type", "MD5");
+        parameter.put("nonce_str", NumberUtils.getNonceString());
+        parameter.put("sign", NumberUtils.getSign(parameter, apiKey));
+        String mapToXml;
+        try {
+            mapToXml = CommonUtil.mapToXml(parameter);
+        } catch (Exception ex) {
+            throw new PaymentException("支付参数错误", ex);
+        }
+        String result = sendSSLRequest("https://fraud.mch.weixin.qq.com/risk/getpublickey", mapToXml);
+        JSONObject jsonObject = JSONObject.parseObject(result);
+        if (!jsonObject.get("return_code").toString().equals("SUCCESS") || !jsonObject.get("result_code").toString().equals("SUCCESS")) {
+            log.info(mapToXml + "-" + jsonObject.toJSONString());
+            throw new PaymentException("获取公匙失败");
+        }
+        String pub_key = jsonObject.getString("pub_key");
+        log.info("\n\n");
+        log.info(pub_key);
+        log.info("\n\n");
+
+
+
+        return pub_key;
+    }
+
+
+    public static void main(String[] args){
+
+        //银行卡转账和到零钱
+        WechatPaymentHandler wechatPaymentHandler = new WechatPaymentHandler(
+                "wx45468204ffa9a9a0","1501370501","maibachuxing2018MAIBACHUXING2018",
+                "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",null);
+
+//        WechatTransferBankParameter wchatTransferObject = new WechatTransferBankParameter();
+//        wchatTransferObject.setPartner_trade_no("H100084h10000h192185");
+//        wchatTransferObject.setEnc_bank_no("6230540460117503676");
+//        wchatTransferObject.setEnc_true_name("刘毅");
+//        bank_code 明细参见: https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_4
+//        wchatTransferObject.setBank_code("1005");
+//        wchatTransferObject.setAmount(new BigDecimal("0.04"));
+//        wchatTransferObject.setDesc("test");
+
+//        WechatTransferSmallChangeParameter wchatTransferObject = new WechatTransferSmallChangeParameter();
+//        wchatTransferObject.setPartner_trade_no("H100084h10000h194125");
+//        wchatTransferObject.setOpenid("osWpr5alVrod6NkS7bGkJd23DcrQ");
+//        wchatTransferObject.setRe_user_name("冉泉");
+//        wchatTransferObject.setAmount(new BigDecimal("1"));
+//        wchatTransferObject.setDesc("test");
+//        wchatTransferObject.setSpbill_create_ip("118.113.206.83");
+//        wchatTransferObject.setDevice_info("sb_123456");
+
+//        //红包是公众号APP_ID
+//        WechatPaymentHandler wechatPaymentHandler = new WechatPaymentHandler(
+//                "wx043c9a9826176649","1501370501","maibachuxing2018MAIBACHUXING2018",
+//                "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",null);
+//        WchatTransferParameter wchatTransferObject = new WchatTransferParameter();
+//        wchatTransferObject.setOrgName("麦巴出行");
+//        wchatTransferObject.setChannelUserId("oV4Ih00eq70KvN3IIRAYJ43pW1No");
+//        wchatTransferObject.setDescription("余额提现");
+//        wchatTransferObject.setClientIp("118.113.206.83");
+//        RedpackInfo redpackInfo = new RedpackInfo();
+//        wchatTransferObject.setRedpackInfo(redpackInfo);
+//        redpackInfo.setActivityName("推广奖励TEST");
+//        redpackInfo.setWishing("多推广,多奖励TEST");
+//        wchatTransferObject.setTotalFee(new BigDecimal("1").multiply(BigDecimal.valueOf(100)).intValue());
+//        wchatTransferObject.setTransferNo("H100084h10000h202225");
+
+//        wechatPaymentHandler.transfer(wchatTransferObject);
+    }
+
+
+
+
+
+
+}