基于SDK的支付接口服务端——支付宝,微信

资源下载:
微信sdk:http://download.csdn.net/download/qq_29423883/9958549
支付宝sdk:http://download.csdn.net/download/qq_29423883/9958617
支付宝签名工具:http://download.csdn.net/download/qq_29423883/9958652

支付宝

准备:

1.创建应用,配置密钥(详见https://docs.open.alipay.com/291/105971);
2.jar包:alipay-sdk-java20170818173712.jar;commons-logging-1.1.1.jar

3.配置信息:appid;应用私钥;支付宝公钥(是支付宝公钥不是应用公钥);
4.基本步骤:
(1)获得初始化的AlipayClient
(2)创建API对应的request类
(3)设置业务参数
(4)通过alipayClient调用API,获得对应的response类
(5)根据response中的结果继续业务逻辑处理

官方示例

//1.交易查询
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
request.setBizContent("{" +
"   \"out_trade_no\":\"20150320010101001\"," +
"   \"trade_no\":\"2014112611001004680073956707\"" +
"  }");//设置业务参数
AlipayTradeQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API,获得对应的response类
System.out.print(response.getBody());
//根据response中的结果继续业务逻辑处理

再具体一点的示例

//创建支付宝配置类
public class AlipayConfig {
    public static String APP_ID_USER = "XXX";
    //应用私钥
    public static String PRIVATE_KEY = "XXX";
    //支付宝公钥
    public static String ALIPAY_PUBLIC_KEY = "XXX";
    public static String CHARSET = "utf-8";
    public static String URL = "https://openapi.alipay.com/gateway.do";
    public static String FORMAT = "json";
    public static String SIGN_TYPE = "RSA2";
   }
//申请退款
 public String refundRequest( String tradeNo, int refundMoney) {
   String TimeMillis=String.valueOf(System.currentTimeMillis());
        String responseStr = "退款失败";
            AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID_LAWYER, PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

            double money = refundMoney;
            money = money / 100;//单位是元
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"trade_no\":\"" + tradeNo + "\"," +
                    "\"out_request_no\":\"" + tradeNo + "\"," +
                    "\"refund_amount\":" + money + "" +
                    "  }");
            AlipayTradeRefundResponse response;
            try {
                response = alipayClient.execute(request);
                if (response.isSuccess()) {
                    responseStr = "退款成功";
                } else if(response != null){
                    responseStr = response.getSubMsg();
                }
            } catch (AlipayApiException e) {
                responseStr = "系统异常";
                }
    return responseStr; }       

沙箱环境

  //沙箱环境
    public static String APP_ID_TEST = "2016081900288218";
    // 应用的私钥
    public static String PRIVATE_KEY_TEST = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCEoj5tT+gt0CfUc1hgjZuFVgr8x7fBY4tJfOSfiTO0A3jyxNPjZz16nQ1k4xyTOKSxHmcdZopN5HZRI3J8+4U3a8C7tkTJ8o79qLbStVRqR9LIZA6FA4ToIb/3evoET5h2AH51JHO0ZiJAxsY5frbyqltfjEYVRK1h+HuQ5pXYRjHWfOxk0eOl+CEyV1CLcSoPTDaXRCy98/6BfG9DU5LjvXCep55J11ibwNC8mkbZTnZm5rGBXtS3NKUopfAHBBgga2nYO+duTjMTtLAt1BNhxLnBAH61tdLEafloWBcWwa/nerYnadkgiX0ibqs/eY+yj5rOfhUTTsF6oBZup2WjAgMBAAECggEABRHSgwkf3chsDVHPWflvrVwJlXnoyyqL42YzsulioYnUcKsXUkTa87nXDjkkGXh7yw1Xcac+uBV4dEd/k8llYSXsOwCPhoyP7KArRMiLjnhqVSCF8Y2d4eWQWdxIfCuyryf7rWyUQ5v3yTQP1ZjDU2kxjuhksWFroygFSReXOKoAG8AM7ZxflqYOi91bOX8bnxo2QBVIkQrWo1b1gGoo9q15YOBU5ZY4A79CNIkZlv1Uq3Zv+lVTr9UKcCbhPUF5Yc/y2j7BuI28APGwMOFzEaUqZnXlbf7opCbv+B0fx00NZ1nWWnreUl0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i5KdzAhdET5MECIr1mM3H+uG0J9MkEFwuATCyy0RjJ9r0sdrx/hpv4YgPutggLB9SxTfJr2Jo5hIgaVejyznf1FlbvGWM7gWdXv8oYWo0h+vK79vLRD3kTvVpuYdKoPAtE4UuRqwnYDUt9QujauXhKOKHQs8SRA0ngWVTVFA8O6C1eJMvP7U0zvrKHyktLekpRjN/JZEHOLuqBP9DzJgL1Nqcv045h2/b58PYsjutYSYfFwSDfcpKpEPVwZhDswIDAQAB";
    // 字符编码格式 目前支持 gbk 或 utf-8
    public static String CHARSET_TEST  = "utf-8";
    //退款接口url
    public static String URL_TEST = "https://openapi.alipaydev.com/gateway.do";

    public static String FORMAT_TEST="json";
    // 签名方式
    public static String SIGN_TYPE_TEST  = "RSA2";

微信

准备
1.创建应用,配置秘钥
2.安装

<dependency>
    <groupId>com.github.wxpay</groupId>
    <artifactId>wxpay-sdk</artifactId>
    <version>0.0.3</version>
</dependency>

3.需要的资源
appid
商户号 [微信支付分配的商户号]
商户平台设置的密钥key
商户证书 [pkcs12格式(apiclient_cert.p12);微信商户平台(pay.weixin.qq.com)–>账户中心–>账户设置–>API安全–>证书下载 ]
4.基本步骤
(1)创建配置类
(2)放入参数
(3)调用接口
(4)根据响应处理业务
官方示例:

//微信支付配置类
import com.github.wxpay.sdk.WXPayConfig;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class WXPayConfigImpl implements WXPayConfig {
    private String appId = "xxx";
    private String  mchId = "xxx";//商户号
    private String key = "xxx";//密钥key

    private byte[] certData;
    private static WXPayConfigImpl INSTANCE;

    private WXPayConfigImpl() throws Exception{
        String certPath = "src/resources/apiclient_cert.p12";//证书位置
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    public static WXPayConfigImpl getInstance() throws Exception{
        if (INSTANCE == null) {
            synchronized (WXPayConfigImpl.class) {
                if (INSTANCE == null) {
                    INSTANCE = new WXPayConfigImpl();
                }
            }
        }
        return INSTANCE;
    }

    public String getAppID() {
        return appId;
    }

    public String getMchID() {
        return mchId;
    }

    public String getKey() {
        return key;
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis;
        certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }


    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }
}
//支付测试类;包括下单操作,退款操作,对账单下载
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import java.util.HashMap;
import java.util.Map;

public class TestWXPay {

    private WXPay wxpay;
    private WXPayConfigImpl config;
    private String out_trade_no;
    private String total_fee;

    public TestWXPay() throws Exception {
        config = WXPayConfigImpl.getInstance();
        wxpay = new WXPay(config);
        total_fee = "1";
        // out_trade_no = "201701017496748980290321";
        out_trade_no = "201613091059590000003433-asd002";
    }

    /**
     * 扫码支付  下单
     */
    public void doUnifiedOrder() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", "腾讯充值中心-QQ会员充值");
        data.put("out_trade_no", out_trade_no);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://test.letiantian.me/wxpay/notify");
        data.put("trade_type", "NATIVE");
        data.put("product_id", "12");
        // data.put("time_expire", "20170112104120");

        try {
            Map<String, String> r = wxpay.unifiedOrder(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doOrderClose() {
        System.out.println("关闭订单");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
        try {
            Map<String, String> r = wxpay.closeOrder(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doOrderQuery() {
        System.out.println("查询订单");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
//        data.put("transaction_id", "4008852001201608221962061594");
        try {
            Map<String, String> r = wxpay.orderQuery(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doOrderReverse() {
        System.out.println("撤销");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
//        data.put("transaction_id", "4008852001201608221962061594");
        try {
            Map<String, String> r = wxpay.reverse(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 长链接转短链接
     * 测试成功
     */
    public void doShortUrl() {
        String long_url = "weixin://wxpay/bizpayurl?pr=etxB4DY";
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("long_url", long_url);
        try {
            Map<String, String> r = wxpay.shortUrl(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 退款
     * 已测试
     */
    public void doRefund() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
        data.put("out_refund_no", out_trade_no);
        data.put("total_fee", total_fee);
        data.put("refund_fee", total_fee);
        data.put("refund_fee_type", "CNY");
        data.put("op_user_id", config.getMchID());

        try {
            Map<String, String> r = wxpay.refund(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询退款
     * 已经测试
     */
    public void doRefundQuery() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_refund_no", out_trade_no);
        try {
            Map<String, String> r = wxpay.refundQuery(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对账单下载
     * 已测试
     */
    public void doDownloadBill() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("bill_date", "20161102");
        data.put("bill_type", "ALL");
        try {
            Map<String, String> r = wxpay.downloadBill(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doGetSandboxSignKey() throws Exception {
        WXPayConfigImpl config = WXPayConfigImpl.getInstance();
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        String sign = WXPayUtil.generateSignature(data, config.getKey());
        data.put("sign", sign);
        WXPay wxPay = new WXPay(config);
        String result = wxPay.requestWithoutCert("https://api.mch.weixin.qq.com/sandbox/pay/getsignkey", data, 10000, 10000);
        System.out.println(result);
    }

    public static void main(String[] args) throws Exception {

        TestWXPay dodo = new TestWXPay();
        dodo.doOrderQuery();
        dodo.doOrderReverse();
        dodo.doOrderQuery();
        dodo.doOrderReverse();
        dodo.doOrderQuery();
    }
}

开发示例

/**金额单位:分
*/
public String refundRequest(String tradeNo, int refundMoney, int totalMoney) {
        String responseStr = "退款失败";
try {
                WXPayConfigImpl config = WXPayConfigImpl.getInstance();
                WXPay wxpay = new WXPay(config);
                HashMap<String, String> data = new HashMap<>();
                data.put("transaction_id",""+ tradeNo+"");
                data.put("out_refund_no",""+ TimeMillis+"");
                data.put("total_fee",""+totalMoney+"");
                data.put("refund_fee",""+refundMoney+"");
                data.put("refund_fee_type", "CNY");
                data.put("mch_id", config.getMchID());
                Map<String, String> r = wxpay.refund(data);
                String err_code_des = r.get("err_code_des");
                if(err_code_des == null) {
                    responseStr ="退款成功";
                } else {
                    responseStr = err_code_des;
                }
            } catch (Exception e) {
                responseStr = "系统异常"; 
            }

        return responseStr;
        }

沙箱环境
微信支付api的链接,如:被扫支付官网的url为:https://api.mch.weixin.qq.com/pay/micropay增加sandbox路径,变更为https://api.mch.weixin.qq.com/sandbox/pay/micropay

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值