常见支付宝、微信支付的使用流程

支付宝:https://open.alipay.com/platform/home.htm
微信:https://pay.weixin.qq.com/index.php/core/home/login?return_url=%2F
银联:https://open.unionpay.com/ajweb/help/qrcodeFormPage
各大银行:http://openhome.cmbchina.com/xcx/XCXDefault.aspx等等

支付宝支付

a.简介产品的类型

b.申请账号 必须是企业才可以申请 交易有手续费 0.6%配置秘钥

c.查看提供的API接口 https://docs.open.alipay.com/api_1
d.如何使用https://docs.open.alipay.com/270/105899/
使用步骤:
1.依赖jar

<!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java --> 
    <dependency>    
        <groupId>com.alipay.sdk</groupId>    
        <artifactId>alipay-sdk-java</artifactId>    
        <version>4.9.28.ALL</version> 
    </dependency>

2.客户端

AlipayClient alipayClient = new 
DefaultAlipayClient(URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

参数说明:alipayClient 只需要初始化一次,后续调用不同的 API 都可以使用同一个 alipayClient 对象。

3.封装工具类逐一调用对应的支付接口

public class AliPayUtil {    
    private static AlipayClient alipayClient ;    
    private static final String APP_ID="你的";    
    private static final String APP_PRIVATE_KEY="你的";
    private static final String ALIPAY_PUBLIC_KEY="你的";    
    static {
    	   AlipayClient alipayClient = new DefaultAlipayClient(
            "https://openapi.alipay.com/gateway.do",
            App_id,
            APP_PRIVATE_KEY,
            "json",
            "UTF-8",
            ALIPAY_PUBLIC_KEY,
            "RSA2");
}

/**
 * 统一收单下单并支付页面接口
 */
public static void pay(AliPayDto dto) throws AlipayApiException {
    AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
    //设置请求信息 对应的参数 要求必选参数必须提供
    request.setBizContent(JSON.toJSONString(dto));
    //执行请求 并 获取响应
    AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
    //验证是否成功
    if(response.isSuccess()){
        System.out.println("调用成功");
    } else {
        System.out.println("调用失败");
    }
}

//生成支付连接 主要通过二维码支付
public static  String createPrePay(AliPayDto dto) throws AlipayApiException {
    AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
    //设置请求信息 对应的参数 要求必选参数必须提供
    request.setBizContent(JSON.toJSONString(dto));
    //执行请求 并 获取响应
    AlipayTradePrecreateResponse response=alipayClient.execute(request);
    //验证是否成功
    if(response.isSuccess()){
        return response.getQrCode();
    } else {
        return null;
    }
}

/**
 * 查询订单的支付状态*/
public static String queryPayStatus(String oid) throws AlipayApiException {
    AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
    request.setBizContent("{\"out_trade_no\":\""+oid+"\"}");
    AlipayTradeQueryResponse response=alipayClient.execute(request);
    if(response.isSuccess()){
        return response.getTradeStatus();
    }else {
        return "支付宝暂时故障";
    }
}

/**
 * alipay.trade.cancel(统一收单交易撤销接口)*/
public static String cancelPay(String oid) throws AlipayApiException {
    AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
    request.setBizContent("{\"out_trade_no\":\""+oid+"\"}");
    AlipayTradeCancelResponse response = alipayClient.execute(request);
    if(response.isSuccess()){
        System.out.println("调用成功");
        return response.getAction();
    } else {
        System.out.println("调用失败");
        return null;
    }
}
/**
 * alipay.trade.refund(统一收单交易退款接口) */
public static String refundPay(String oid) throws AlipayApiException {
    AlipayTradeRefundRequest  request = new AlipayTradeRefundRequest ();
    request.setBizContent("{\"out_trade_no\":\""+oid+"\",\"refund_amount\":0.01}");
    AlipayTradeRefundResponse response = alipayClient.execute(request);
    if(response.isSuccess()){
        System.out.println("调用成功");
        return response.getPresentRefundBuyerAmount();
    } else {
        System.out.println("调用失败");
        return null;
    }
}
/**
 * alipay.trade.fastpay.refund.query(统一收单交易退款查询)*/
public static String queryRefundPay(String oid) throws AlipayApiException {
    AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
    request.setBizContent("{\"out_trade_no\":\""+oid+"\",\"out_request_no\":\""+oid+"\"}");
    AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
    if(response.isSuccess()){
        System.out.println("调用成功");
        return response.getRefundAmount();
    } else {
        System.out.println("调用失败");
        return null;
    }
}
}

a.alipay.trade.page.pay(统一收单下单并支付页面接口)
b.alipay.trade.precreate(统一收单线下交易预创建) 二维码支付
c.alipay.trade.query(统一收单线下交易查询) 查询订单的支付状态d.alipay.trade.cancel(统一收单交易撤销接口)
e.alipay.trade.fastpay.refund(统一收单交易退款接口) f.alipay.trade.fastpay.refund.query(统一收单交易退款查询)
支付宝支付代码:AlipayxxxxRequest 请求对象
设置json参数
AlipayxxxResponse 响应对象
获取响应参数

微信支付

1.微信支付
https://pay.weixin.qq.com/static/product/product_index.shtml
2.微信支付的产品服务端:

Native支付是指商户系统按微信支付协议生成支付二维码,用户再用微信“扫一扫”完成支付的模式。该模式 适用于PC网站、实体店单品或订单、媒体广告支付等场景
3.Native支付预览
https://pay.weixin.qq.com/wiki/doc/api/native.php
4.xml生成和解析常用方式:
1.Document2.Dom4J 3.Jdom 4.Sax5.Pull 5.微信支付实现

package com.wn.skill.pay;

import com.wn.skill.dto.WxPayDto;
import com.wn.skill.utils.HttpUtil;
import com.wn.skill.utils.MD5Util;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @author weining
 * @date 2020/2/28 14:02
 */
public class WxchatPayUtil {

    //秘钥信息  
    private static final String APPID="你的appid";
    private static final String MCHID="你的mchid";
    private static final String APPKEY="你的appkey";
    //回调接口  注意地址:必须是公网可以访问的
    private static final String CALL_URL="http://localhost:8901/api/pay/wxchatnotify.do";
    //微信支付常用接口
    //统一下单
    private static final String prepay="https://api.mch.weixin.qq.com/pay/unifiedorder";
    //查询订单支付接口
    private static final String querypay="https://api.mch.weixin.qq.com/pay/orderquery";
    //关闭订单接口
    private static final String closepay="https://api.mch.weixin.qq.com/pay/closeorder";
    /**
     * 生成签名
     */
    private static String createSign(TreeMap<String,Object> map){
        //1.设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),
        // 使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA
        StringBuffer buffer=new StringBuffer();
        for(String k:map.keySet()){
            Object o=map.get(k);
            if(o!=null){
                buffer.append(k+"="+o+"&");
            }
        }
        if(buffer.length()>0){
            buffer.delete(buffer.length()-1,buffer.length());
        }
        //2.,在stringA最后拼接上key得到stringSignTemp字符串,
        // 并对stringSignTemp进行MD5运算,
        // 再将得到的字符串所有字符转换为大写,
        // 得到sign值signValue。
        buffer.append("&key="+APPKEY);
        return MD5Util.MD5Encode(buffer.toString(),"UTF-8").toUpperCase();
    }

    //生成随机字符串
    public static String createNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    //Map-生成请求的xml
    public static String createXML(TreeMap<String,Object> map) throws IOException {
        //创建根节点
        Element root=new Element("xml");
        //创建文档对象
        Document document=new Document(root);
        //循环创建子节点 并添加
        for(String key:map.keySet()){
            Element child=new Element(key);
            child.setText(map.get(key).toString());
            document.getRootElement().addContent(child);
        }
        //创建xml输出器
        XMLOutputter xmlOutputter=new XMLOutputter();
        //创建输出内存流
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        //把内容写出到内存流
        xmlOutputter.output(document,baos);
        return baos.toString();
    }

    //解析xml格式---Map
    public static HashMap<String,Object> parseXml(String xml) throws Exception {
        HashMap<String,Object>  map=new HashMap<>();
        //转换数据
        ByteArrayInputStream bais=new ByteArrayInputStream(xml.getBytes());
        //创建解析器
        SAXBuilder builder=new SAXBuilder();
        //创建文档对象
        Document document=builder.build(bais);
        //获取根节点
        Element root=document.getRootElement();
        //遍历子节点
        List<Element> childs=root.getChildren();
        for(Element c:childs){
            map.put(c.getName(),c.getValue());
        }
        return map;
    }

    private static TreeMap<String,Object> createParam(){
        TreeMap<String,Object> map=new TreeMap<>();
        map.put("appid",APPID);
        map.put("mch_id",MCHID);
        map.put("nonce_str",createNonceStr());
        return map;
    }
    //统一下单
    public static String createPay(WxPayDto dto){
        TreeMap<String,Object> map=createParam();
        map.put("trade_type","NATIVE");
        map.put("notify_url",CALL_URL);
        map.put("body",dto.getBody());
        map.put("out_trade_no",dto.getOut_trade_no());
        map.put("total_fee",dto.getTotal_fee());
        map.put("spbill_create_ip","127.0.0.1");
        map.put("sign",createSign(map));
        try {
            //生成请求的xml
            String requestXml=createXML(map);
            String responseXml=HttpUtil.postData(prepay,requestXml);
            if(responseXml!=null){
                HashMap<String,Object> resMap=parseXml(responseXml);
                if(resMap.containsKey("code_url")){
                    return resMap.get("code_url").toString();
                }else {
                    System.out.println(resMap.get("return_msg").toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询微信支付的支付状态
     */
    public static String queryPay(String oid) throws IOException {
        TreeMap<String, Object> map = createParam();
        map.put("out_trade_no",oid);
        map.put("sign",createSign(map));
        try{
            //生成请求的xml
            String xml = createXML(map);
            String s = HttpUtil.postData(querypay, xml);
            if (s!=null){
                HashMap<String, Object> hashMap = parseXml(s);
                if (hashMap.containsKey("trade_state")){
                    return hashMap.get("trade_state").toString();
                }else {
                    System.out.println(hashMap.get("return_msg").toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取消微信支付
     */
    public static String closePay(String oid){
        TreeMap<String,Object> map=createParam();
        map.put("out_trade_no",oid);
        map.put("sign",createSign(map));
        try {
            //生成请求的xml
            String requestXml=createXML(map);
            String responseXml=HttpUtil.postData(closepay,requestXml);
            if(responseXml!=null){
                HashMap<String,Object> resMap=parseXml(responseXml);
                if(resMap.containsKey("result_code")){
                    return resMap.get("result_code").toString();
                }else {
                    System.out.println(resMap.get("return_msg"+"123").toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        WxPayDto dto=new WxPayDto();
        dto.setBody("测试数据");
        dto.setOut_trade_no("2020010100011");
        dto.setTotal_fee(1);
        System.out.println(dto.toString());
        System.out.println("预支付链接"+createPay(dto));
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值