微信支付(退款为例)

微信支付退款的官方文档

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4

导入证书

微信退款是需要证书的
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3

以在windows为例,解压之后的文件

双击.p12结尾的文件,导入证书,会要求输入密码,密码就是商户ID,注意一定要是在自己的商户平台上下载的证书,不然会提示密码错误。


导入成功

Java代码

封装了一个RefundVo对象,字段设定根据官方文档

public class RefundVo {

    private String appid;
    private String mchId;
    private String deviceInfo;
    private String nonceStr;
    private String sign;
    private String signType;
    private String transactionId;
    private String outTradeNo;
    private String outRefundNo;
    private int totalFee;
    private int refundFee;
    private String refundFeeType;
    private String opUserId;
    private String refundAccount;
    //省略get set方法
}

设置各个参数

String key = "xxxxxxx";
RefundVo vo = new RefundVo();
vo.setOutTradeNo("2016006092770333");//商户订单号(微信订单号二选一即可)
vo.setAppid("appid");
vo.setMchId("mchid");
vo.setOutRefundNo("2016006092770333");//某付款的定单号
vo.setTotalFee(1);//订单金额
vo.setRefundFee(1);退款金额
vo.setOpUserId("1410417402");//默认商户号
String certificatePath = "E:/工作/cert/apiclient_cert.p12";//证书的绝对路径
refund(key ,vo,certificatePath );

封装退款的结果

public class RefundResult {

    private String returnCode;
    private String returnMsg;
    private String resultCode;
    private String errCode;
    private String errCodeDes;
    private String appid;
    private String mchId;
    private String deviceInfo;
    private String nonceStr;
    private String sign;
    private String transactionId;
    private String outTradeNo;
    private String outRefundNo;
    private String refundId;
    /**
     * ORIGINAL—原路退款
     * BALANCE—退回到余额
     */
    private String refundChannel;
    /**
     * 申请退款金额
     */
    private int refundFee;
    /**
     * 退款金额
     */
    private int settlementRefundFee;
    private int totalFee;
    private int settlementTotalFee;
    private String feeType;
    private int cashFee;
    private int cashRefundFee;
 //省略set get方法
}

退款的方法

public RefundResult refund(String key,RefundVo vo,String certificatePath){
    RefundResult refundResult = new RefundResult();
    vo.setNonceStr(RandomUtil.wechatRandomString());//设置随机字符串
    vo.setSign(new RefundBuilder().build(vo));//设置签名
    check(vo);//检查参数
    //将参数放入Map中
    Map<String,String> params=new RefundBuilder().getParams(vo);
    //转成Xml形式的String
    String xml=XmlParseUtils.assembleXml(params);
    /**
        <xml>
           <appid>wx2421b1c4370ec43b</appid>
           <mch_id>10000100</mch_id>
           <nonce_str>6cefdb308e1e2e8aabd48cf79e546a02</nonce_str>
           <op_user_id>10000100</op_user_id>
           <out_refund_no>1415701182</out_refund_no>
           <out_trade_no>1415757673</out_trade_no>
           <refund_fee>1</refund_fee>
           <total_fee>1</total_fee>
           <transaction_id></transaction_id>
           <sign>FE56DD4AA85C0EECA82C35595A69E153</sign>
        </xml>
    **/
    //调用微信接口
    String  result = HttpClientUtils.executeBySslPost(refundURL,xml,vo.getCertificatePath(),vo.getRefundVo().getMchId());//发送http请求
    //接收xml解析的结果
    Map<String, String> map = new HashMap<String,String>();
    //返回结果为xml形式,转成map然后封装成refundResult即可
    map = XmlParseUtils.parseXml(result);
    refundResult = new RefundResultBuilder().build(map);
}

参数检查

private void check(RefundVo vo){
       
        if (VerifyUtils.isEmpty(vo.getAppid())) {
             throw new PayException("申请退款参数为空——appid");
        }
        if (VerifyUtils.isEmpty(vo.getMchId())) {
            throw new PayException("申请退款参数为空——mch_id");
        }
        if (VerifyUtils.isEmpty(vo.getNonceStr())) {
            throw new PayException("申请退款参数为空——nonce_str");
        }
        if (VerifyUtils.isEmpty(vo.getSign())) {
            throw new PayException("申请退款参数为空——sign");
        }
        if (VerifyUtils.isEmpty(vo.getTransactionId()) && VerifyUtils.isEmpty(vo.getOutTradeNo())) {
            throw new PayException("申请退款参数为空——transaction_id或者out_trade_no");
        }
        if (VerifyUtils.isEmpty(vo.getOutRefundNo())) {
            throw new PayException("申请退款参数为空——out_refund_no");
        }
        if (VerifyUtils.isEmpty(vo.getTotalFee())) {
            throw new PayException("申请退款参数为空——total_fee");
        }
        if (VerifyUtils.isEmpty(vo.getRefundFee())) {
            throw new PayException("申请退款参数为空——refund_fee");
        }
        if (VerifyUtils.isEmpty(vo.getOpUserId())) {
            throw new PayException("申请退款参数为空——op_user_id");
        }
    }

Map构建

    public class RefundBuilder extends SignBuilder {

    @Override
    public Map<String, String> getParams(Refund vo) {
        
        Map<String,String> params = new HashMap<String, String>();
        if(VerifyUtils.isNotEmpty(vo.getAppid())){
            params.put("appid",vo.getAppid());
        }
        if (VerifyUtils.isNotEmpty(vo.getMchId())) {
            params.put("mch_id", vo.getMchId());
        }
        if (VerifyUtils.isNotEmpty(vo.getDeviceInfo())) {
            params.put("device_info", vo.getDeviceInfo());
        }
        if(VerifyUtils.isNotEmpty(vo.getNonceStr())){
            params.put("nonce_str",vo.getNonceStr());
        }
        if (VerifyUtils.isNotEmpty(vo.getSign())) {
            params.put("sign", vo.getSign());
        }
        if (VerifyUtils.isNotEmpty(vo.getSignType())) {
            params.put("sign_type", vo.getSignType());
        }
        if (VerifyUtils.isNotEmpty(vo.getTransactionId())) {
            params.put("transaction_id", vo.getTransactionId());
        }
        if (VerifyUtils.isNotEmpty(vo.getOutTradeNo())) {
            params.put("out_trade_no", vo.getOutTradeNo());
        }
        if (VerifyUtils.isNotEmpty(vo.getOutRefundNo())) {
            params.put("out_refund_no", vo.getOutRefundNo());
        }
        if (VerifyUtils.isNotEmpty(vo.getTotalFee())) {
            params.put("total_fee",Integer.toString(vo.getTotalFee()));
        }
        if (VerifyUtils.isNotEmpty(vo.getRefundFee())) {
            params.put("refund_fee", Integer.toString(vo.getRefundFee()));
        }
        if (VerifyUtils.isNotEmpty(vo.getRefundFeeType())) {
            params.put("refund_fee_type",vo.getRefundFeeType());
        }
        if (VerifyUtils.isNotEmpty(vo.getOpUserId())) {
            params.put("op_user_id",vo.getOpUserId());
        }
        if (VerifyUtils.isNotEmpty(vo.getRefundAccount())) {
            params.put("refund_account",vo.getRefundAccount());
        }
        return params;
    }

}

http执行的方法

public static String executeBySslPost(String url, String body,String certificatePath,String password) throws Exception {
        String result = "";
        //商户id
        //指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(new File(certificatePath));
        try {
            //指定PKCS12的密码(商户ID)
            keyStore.load(instream, password.toCharArray());
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
        //指定TLS版本
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        //设置httpclient的SSLSocketFactory
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            HttpPost httppost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(body, "UTF-8");
            httppost.setEntity(reqEntity);

            System.out.println("Executing request: " + httppost.getRequestLine());
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("请求失败", e);
                throw new RuntimeException(e);
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求失败", e);
            throw new RuntimeException(e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

最终的返回结果

System.out.println(JSON.toJSONString(result,true));

欢迎大家讨论~我的博客地址 http://blog.doublez.cc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容