小程序之微信退款

需要些的文章有点多,时间太少,我就先随便写写,后面有空闲在优化。

开始 小程序js 页面我就不放了 就一个按钮自己写测试


//申请退款

  sqtk: function (e) {

    var that = this;

    var that = this;

    var outRefundNo = "1165166525";

    var openId = "o7Rrj5M-METpuTV8mNxv6_6gn1sw";

    var tradeNo = "85511613375";

    var amount = "0.01";

    console.log('申请退款' + e.currentTarget.dataset.wmddid)

    wx.showModal({

      title: '提示',

      content: '申请退款么',

      success: function (res) {

        if (res.confirm) {

          wx.request({

            url: 'http://**/app/refund',

            method: 'POST',

            data: {

              openId: openId,

              tradeNo: tradeNo,

              amount: amount,

              outRefundNo: outRefundNo,

              refundAmount: amount

            },    //参数为键值对字符串

            header: {

              //设置参数内容类型为x-www-form-urlencoded

              "Accept": "*/*", 'Content-Type': 'application/json'

            },

            success: function (e) {

              var data = e.data.wxPayResponse;

            }

          })

        } else if (res.cancel) {

          console.log('用户点击取消')

        }

      }

    })

  }

服务端接口

AppWxPayController.java

退款申请+回调

    @PostMapping("refund")

    @ApiOperation("微信退款申请")

    public R refund(@RequestBody PayParam payParam){

    WxPayEntity wxPayEntity=wxPayService.refund(payParam);

    return R.ok().put("wxPayResponse", wxPayEntity);

    }

    @PostMapping("refundNotifyUrl")

    @ApiOperation("微信退款回调")

    public String refundNotifyUrl(HttpServletRequest request){

    String xmlString = WxPayUtils.getXmlString(request);

        logger.info("----微信退款回调接收到的数据如下:---" + xmlString);

    return wxPayService.refundAsyncNotify(xmlString);

    }

service+实现类 WxPayService.java

/** 微信申请退款

* <p>Title: refund</p> 

* <p>Description: </p> 

* @return 

*/ 

WxPayEntity refund(PayParam payParam);

/**

    * 微信退款异步通知

    * @param notifyData 异步通知内容

    * @return

    */

String refundAsyncNotify(String notifyData);

WxPayServiceImpl.java


/* (non-Javadoc)

* <p>Title: refund</p> 

* <p>Description: 退款申请</p> 

* @param payParam

* @return 

* @see com.alpha.modules.wxpay.service.WxPayService#refund(com.alpha.modules.wxpay.form.PayParam) 

*/

@Override

public WxPayEntity refund(PayParam payParam) {

WxRefundResponse response = null;

        try {

            //组请求参数

        WxRefundRequest request = new WxRefundRequest();

            request.setAppid(WxConfigure.getAppID());

            request.setMchId(WxConfigure.getMch_id());

            request.setNonceStr(WxPayUtils.getRandomStr(32));

            request.setSignType("MD5");

            request.setOutTradeNo(payParam.getTradeNo());

            request.setOutRefundNo(payParam.getOutRefundNo());

            request.setTotalFee(WxPayUtils.yuanToFen(payParam.getAmount()));

            request.setRefundFee(WxPayUtils.yuanToFen(payParam.getRefundAmount()));

            request.setNotifyUrl(WxConfigure.getRefundNotifyUrl());

            request.setSign(WxPayUtils.signByMD5(request, WxConfigure.getKey()));

            Retrofit retrofit=null;

            try {

            OkHttpClient client=initCert();// 加载证书

              retrofit = new Retrofit.Builder()

                    .baseUrl("https://api.mch.weixin.qq.com")

                    .addConverterFactory(SimpleXmlConverterFactory.create())

                    .client(client)

                    .build();

            } catch (Exception e) {

                e.printStackTrace();

            }

            String xml = WxPayUtils.objToXML(request);

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);

            Call<WxRefundResponse> call = retrofit.create(WxPayApi.class).REFUND_RESPONSE_CALL(requestBody);

            Response<WxRefundResponse> retrofitResponse = call.execute();

            response = retrofitResponse.body();

            if(!response.getReturnCode().equals("SUCCESS")) {

                throw new RuntimeException("【微信退款】发起退款, returnCode != SUCCESS, returnMsg = " + response.getReturnMsg());

            }

            if (!response.getResultCode().equals("SUCCESS")) {

                throw new RuntimeException("【微信退款】发起退款, resultCode != SUCCESS, err_code = " + response.getErrCode() + " err_code_des=" + response.getErrCodeDes());

            }

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

return buildWxRefundResponse(response);

}

/**

    * 加载证书

    *

    */

private static OkHttpClient initCert() throws Exception {

        // 证书密码,默认为商户ID

        String key = WxConfigure.getMch_id();

        // 证书的路径

        String path = WxConfigure.getCertPath();

        // 指定读取证书格式为PKCS12

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        // 读取本机存放的PKCS12证书文件

        FileInputStream instream = new FileInputStream(new File(path));

        try {

            // 指定PKCS12的密码(商户ID)

            keyStore.load(instream, key.toCharArray());

        } finally {

            instream.close();

        }

        SSLContext sslcontext = SSLContexts

                .custom()

                .loadKeyMaterial(keyStore, key.toCharArray())

                .build();

        // 设置OkHttpClient的SSLSocketFactory

        return  new OkHttpClient.Builder()

                .addInterceptor(chain -> {

                    // 请求头

                    Request request = chain.request().newBuilder()

                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") 

                    .addHeader("Accept-Encoding", "gzip, deflate") 

                    .addHeader("Connection", "keep-alive") 

                    .addHeader("Accept", "*/*") 

                            .build();

                    return chain.proceed(request);

                })

                // 超时时间

                .readTimeout(5, TimeUnit.MINUTES)

                .connectTimeout(5, TimeUnit.MINUTES)

                // HTTPS

                .sslSocketFactory(sslcontext.getSocketFactory())

                // Hostname domain.com not verified

                .hostnameVerifier((s, sslSession) -> true)

                .build();

    }

private WxPayEntity buildWxRefundResponse(WxRefundResponse wxRefundResponse) {

        String timeStamps = String.valueOf(System.currentTimeMillis() / 1000L); //微信接口时间戳为10位字符串

        WxPayEntity wxPayEntity = new WxPayEntity();

        try {

            wxPayEntity.setTimeStamp(timeStamps);

            wxPayEntity.setNonceStr(WxPayUtils.getRandomStr(32));

            wxPayEntity.setAppid(WxConfigure.getAppID());

            wxPayEntity.setSignType("MD5");

        } catch (Exception e) {

            e.printStackTrace();

        }

        logger.info("【微信退款】退款申请通知:"+wxPayEntity.getOutTradeNo()+"退款申请成功");

        return wxPayEntity;

    }

/* (non-Javadoc) 

* <p>Title: refundAsyncNotify</p> 

* <p>Description: 退款回调通知</p> 

* @param notifyData

* @return 

* @see com.alpha.modules.wxpay.service.WxPayService#refundAsyncNotify(java.lang.String) 

*/

@Override

public String refundAsyncNotify(String notifyData) {

WxRefundNotifyResponse wxRefundNotifyResponse = (WxRefundNotifyResponse) WxPayUtils.xmlToObj(notifyData, WxRefundNotifyResponse.class);

        try {

        if(!wxRefundNotifyResponse.getReturnCode().equals("SUCCESS")) {

                throw new RuntimeException("【微信退款】退款成功通知, returnCode != SUCCESS, returnMsg = " + wxRefundNotifyResponse.getReturnMsg());

            }

        if(StringUtils.isNoneBlank(wxRefundNotifyResponse.getReqInfo())){

        String reqInfo=AESUtils.decode(notifyData, WxConfigure.getKey());

        WxRefundNotifyReqinfo  wxRefundNotifyReqinfo= (WxRefundNotifyReqinfo) WxPayUtils.xmlToObj(reqInfo,WxRefundNotifyReqinfo.class);

        if(wxRefundNotifyReqinfo.getRefundStatus().equals("SUCCESS")){

        //查询transaction_id 是否为空  为空就修改订单状态

        }

        logger.info("【微信退款】退款成功通知:"+wxRefundNotifyReqinfo.getOutTradeNo()+"退款成功");

        }

        } catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    return  WxPayUtils.returnXML(wxRefundNotifyResponse.getReturnCode());

}

这里有个坑,就是解码是256位的,而正常的是128位,需要替换2个jre的jar包

问题还没完,因为某些国家的进口管制限制,Java发布的运行环境包中的加解密有一定的限制。比如默认不允许256位密钥的AES加解密,解决方法就是修改策略文件, 从官方网站下载JCE无限制权限策略文件,注意自己JDK的版本别下错了。将local_policy.jar和US_export_policy.jar这两个文件替换%JRE_HOME%\lib\security和%JDK_HOME%\jre\lib\security下原来的文件,注意先备份原文件。

官方网站提供了JCE无限制权限策略文件的下载:

JDK6的下载地址:

http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

JDK7的下载地址:

http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

JDK8的下载地址:

http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt。

然后后面一篇放实体类吧 我就不文字描述了。
下一篇:[微信支付实体类补发]
(https://www.jianshu.com/p/fd73ea49040e)

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

推荐阅读更多精彩内容