接入支付宝网页支付的个人记录

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35152037/article/details/86617526

实现支付宝支付,开发其实不难,主要是申请和配置一些秘钥麻烦

  1. 先申请一个应用,应用对应了不同的功能,需要进行审核才能通过。
  2. 在这里插入图片描述
    为了开放方便,我申请了一个沙箱应用
    在这里插入图片描述
    其中箭头所示的为这个应用的公钥 需要在代码中配置
    私钥的生成需要参考官方链接,下载到本地生成: https://docs.open.alipay.com/291/105971

下面进行开发的配置:
引入依赖

<!-- 实现支付宝支付接口-->
		<!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java -->
		<dependency>
			<groupId>com.alipay.sdk</groupId>
			<artifactId>alipay-sdk-java</artifactId>
			<version>3.4.27.ALL</version>
		</dependency>

配置支付的客户端 属性信息

#支付宝配置
#支付同步返回地址
ali_return_url =http://106.13xxxx251:8080/tr/send/r1eg3sister/code111  这是get请求的地址,在支付完成之后有支付宝在浏览器中跳转
#支付异步通知地址
ali_notify_url =http://106.13.zzzz1:8080/tr/send/register/code  这是post请求的地址由支付宝异步调用服务器程序,不要设置登录拦截的接口,这也是支付完成的一个确认接口,需要给支付宝返回一个success 字段,否则支付宝会分时间段不断请求接口。具体参考其他博客。 这里可以做一些业务处理
#产品码
product_no = FAST_INSTANT_TRADE_PAY
#超时时间
time_express = 15m
#支付网关
url =https://openapi.alipaydev.com/gateway.do   (沙箱网关)
#商户号
appid =201657142222  (这是应用的ID)
#私钥
private_key =MIIEvAIBADATQ==(此处的一堆秘钥,是生成在本地的秘钥)
#公钥
ali_public_key =MIIBIjANBgkqhkiG9w0QAB (这是一个应用对应的公钥,是上面截图箭头指示的内容)
#加密方式
sign_type = RSA2

/**
 * 支付操作业务
 * Created by huangch on 2019/1/20 19:33
 */
@Transactional
@Service
public class AlipayServiceImpl implements AlipayService {

    @Value("${ali_return_url}")
    private String ali_return_url;

    @Value("${ali_notify_url}")
    private String ali_notify_url;

    @Value("${product_no}")
    private String product_no;

    @Value("${time_express}")
    private String time_express;

    @Value("${url}")
    private String url;

    @Value("${appid}")
    private String appid;

    @Value("${private_key}")
    private String private_key;

    @Value("${ali_public_key}")
    private String ali_public_key;

    @Value("${sign_type}")
    private String sign_type;


    public static final String TRADE_SUCCESS = "TRADE_SUCCESS"; //支付成功标识
    public static final String TRADE_CLOSED = "TRADE_CLOSED";//交易关闭

    /**
     * 返回收钱码表单
     * @param map
     * @return
     */
    @Override
    public String alipay(Map<String,Object> map) {

        String orderId = (String) map.get("orderId");
        String orderName = (String) map.get("orderName");
        // 判断用户是否登录
        // 判断订单是否可以支付
        // 记录订单状态为 待支付状态
        // 判断
        if(true){

        }
        AlipayClient alipayClient = new DefaultAlipayClient(url, appid, private_key, "json", "utf-8", ali_public_key, sign_type); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(ali_return_url);
        alipayRequest.setNotifyUrl(ali_notify_url);         //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+orderId+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":88.88," +
                "    \"subject\":\""+orderName+"\"," +
                "    \"body\":\"Iphone6 16G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833117846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

    return form;
    }

    @Override
    public String synchronous(HttpServletRequest request) {

        Map<String, String> parameters = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        //log.info("支付宝同步参数", requestParams);
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            parameters.put(key, valueStr);
        }
        //记录日志
        String merchantOrderNo = request.getParameter("out_trade_no");//商户订单号
       // cashLogMapper.add(request.getParameter("out_trade_no"), "SYNCHRONOUS", JSON.toJSONString(parameters), new Date());
        return "<html>\n" +
                "<head>\n" +
                "<script type=\"text/javascript\"> function load() { window.close(); } </script>\n" +
                "</head>\n" +
                "<body \"" +
                "load()\"> </body>\n" +
                "</html>";
    }

    @Override
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        //接收参数进行校验
        Map<String, String> parameters = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            parameters.put(key, valueStr);
        }
        //log.info("parameters is [parameters={}]", parameters);
        String appId = request.getParameter("app_id");//appid
        String merchantOrderNo = request.getParameter("out_trade_no");//商户订单号

        String orderId = "123123"; //cashMapper.getCashByMerchantOrderNo(merchantOrderNo).getOrderId();
        if (orderId == null) {
            //log.error("orderId is null");
            //ReturnData.fail(ReturnCode.SERVER_EXCEPTION);
        }
        //log.info("orderId: {}", orderId);
        String payState = request.getParameter("trade_status");//交易状态
        String encodeOrderNum = null;
        //cashLogMapper.add(request.getParameter("out_trade_no"), "NOTIFY", JSON.toJSONString(parameters), new Date());
        try {
            encodeOrderNum = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
            //log.info("encodeOrderNum is [encodeOrderNum={}]", encodeOrderNum);

            boolean signVerified;
            signVerified = AlipaySignature.rsaCheckV1(parameters, ali_public_key, "UTF-8", sign_type);//验证签名
            //log.info("signVerified is [signVerified={}]", signVerified);
            if (signVerified) { //通过验证
                //log.info("payState: {}", payState);
                if (payState.equals(TRADE_SUCCESS)) {
                    //判断订单号与插入的订单号是否一样
                    if (merchantOrderNo.equals(encodeOrderNum) == false || appid.equals(appId) == false) {
                        //log.info("vali failure");
                        //cashMapper.update(merchantOrderNo, 4);

                        response.getOutputStream().print("failure");
                        return;
                    }
                    //cashMapper.update(merchantOrderNo, 3);
                    //orderMapper.afterPay(orderId);
                    response.getOutputStream().print("success");
                    return;
                } else if (payState.equals(TRADE_CLOSED)) { //交易关闭
                    //cashMapper.update(merchantOrderNo, 7);
                } else {
                    //cashMapper.update(merchantOrderNo, 4);
                    response.getOutputStream().print("failure");
                    return;
                }
            } else {
                //签名校验失败更状态
                //cashMapper.update(merchantOrderNo, 4);
                response.getOutputStream().print("failure");
                return;
            }
            //log.info("encodeOrderNum is [encodeOrderNum={}]", encodeOrderNum);
            //cashMapper.update(merchantOrderNo, 4);
            response.getOutputStream().print("failure");
            return;
        } catch (Exception e) {
            //log.error(e.getErrMsg());
            throw new RuntimeException("调用支付宝接口发生异常");
        }


    }

}
//1.申请付款
    @ApiOperation("申请付款")
    @AuthCheck("no")
    @RequestMapping(value = "/order/pay", method = RequestMethod.GET)
    public void alipay(String amount, String orderName, String orderId, HttpServletResponse httpResponse) throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("orderId",orderId);
        map.put("orderName",orderName);
        map.put("amount",amount);
        String form =  alipayService.alipay(map);
        httpResponse.setContentType("text/html;charset=" + "utf-8");
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

这里值做了一个支付接口的方法,以form表单的形式发送到前端支付,注意填写相关的订单信息和 业务逻辑,这里就不多说了
在异步请求的接口中,支付宝只能请求暴露在公网上的接口,本地debug一般无法进入接口。

随笔写的一点东西, 希望能帮到有些朋友,以下是我参考的一篇博客
https://blog.csdn.net/chire_jr/article/details/80051661

如果你喜欢那就扫一扫把,点个赞。
在这里插入图片描述

展开阅读全文

没有更多推荐了,返回首页