第二篇:Spring Boot 集成支付宝支付接口 |电脑支付(沙箱环境)

 

1 :引入  支付 jar包

  <dependency>
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>3.7.4.ALL</version>
        </dependency>

 

 2 引入 配置 修改  参数

app_id  merchant_private_key   alipay_public_key  

app_id  秘钥 可以参考 上篇文章   (https://blog.csdn.net/qq_34789780/article/details/103985710

package com.vue.vueapp.config;

import java.io.FileWriter;
import java.io.IOException;


public class AlipayConfig {

	public static String app_id = "******";
	
	// 商户私钥,您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCfMO+MVK+InioezbMcb3CIWf10qMze+PtxmJRgB4hhdiy/gN5f/Nsp+OKsghkq4PUocBR3SypKjHCUBpbvGj4gORSARL41JFZcPJVEcBFjf9Oi/DfvMzetBpfPNdN5VYZpLCeDRxV1mGFNK5R9cqGqxjkI9yAYuVEO49u3SApeDuKaZXyRsXWc+ZO1v+WLhumcEkJQHeUm0Zq8LHbF8hiXBazmShh6ZHEDPXeP2mVRIUsgcqjnWRp5Y9mHvBpOstj+l174OQFYZ23mGJXCip1BKglGen0ek1z50SbhJa4SGSR05zgBYHxh+4GyQlUjED2MJyP6REUel0+FOFCg62DZAgMBAAECggEAf5yC60OX0zS3HypWQp0y4JsDCtmmIbgGGPHvP2vKcBaDmKB9owTXy7WwQAmqkyzyWhA+18JxjIE4XfFKXTH0S3B2dryknYUblaUbI1mTFugJh8YYMLAmGZYHbBwCAmoE7ZpvslTxZutYVLxytH2IC5YLcpxoJmmoCP+vyiT96pdMGge9kFMXom6qvXy3G14db7zkp+4eA7J3IA+PARP5U69iZ0jkXSHOVuX3muHIRYC+jD6fToxWDxgwrBBEQf+HAYzwmyxeRsvu0+AsBP+1DEUmGbqrWLM0bVnNqE/av07LOl3PIEPB5gfqBMLDaCuSDL9rOemckrt66okCmAvoAQKBgQDt3I+NMw/+/FUEtMX9kj/o6lXFFuuZlfKBGT6P3nH/plyZTIuWoJ9vchAD6f7UdMY5ZzAY9JZL0FGoQncgGDE1jowMBfKe9fpGFWidPJAJBdjpANK3sok1SWKtjA919O9cnBp/mf/FbrRkcAUqq05CcO4O7c6Fqsktq0pbVabsOQKBgQCrVJo3IvvdW/ahlA+Y4JNnsoEsx0Z1lJyK8nXq4J/5P6zUBq9dN2pGuBmx3DtexXfHoc5gUznCoxOE3jHB3yqfuqNYrSJbbhxHHop4SKQG+khr3X1VSoWCthe4+yBq85mcJDnxXfgJChLqhPREaoIxuD0O//Y+Fhcelh6Lc1lZoQKBgQCzk571FSXwdgShxvDrXazOZYxXfdRlYaVx/eMTrvcV8T1bp0SDdcSo2M5qhhCTyY2V7OeND6sglafwhi11l44fRv1IXn0rsb0/iA4xF3YOudFnJ+3uLeYUytCrAWDyxvanTltbFqLZJZkfcssTyb0NwECaGMOgeq3jwrwidGnPUQKBgQCNioE018P3pcfkyKryA2YDnya0VZTSAoopCBF+jz/Z7E7dgwBRJDy6W9FubKDntH81/2i9j0QCljLD68Rzg+h0uP3FfpMJsbfO0V5X7LsFwLMf2YV3du9Bgymp+l1XvhPDOPJdguIspZPnBxu9gbg5VxmqUK+fryQ+coqdbhf8wQKBgQDAnkedw7NGtZ0O6g8EdSpoKwArIMz6GodPJ5a2A0XuJ4p1gl0WJjQSJdnCny0XEGUwRjSy88+R/UAJ1wnXk6UVEWLZ0BHDnQ6STIMJ8U9nVSNVIl/J0mKkfLI5TaU5pI0t0CAm+CqFOBLpsxdu8rXI5KKa9FgjKnxZmSWkfxHfkg==";
	
	// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk6q00fXHYHOyV34dP9tn5HQvS3BIWIznmVgRQptJIJIFZKi92bvKrSlOjLamt6wO5nlJDDcObPusR/i1k9nmbdhAjLX1N/oID2uFL/hUYNADh+b6qKHlg/UIcE24kf/svCBfuV7AdOrZ/d2IN5rivs6YFYDEofX3jvwevi4u97pv1RwCNdv5McpdAOtKwiKnxs0YptoLdMFoKWDIDmqrXNBnxfX0aJNJw/VAvk5Pj9qZ49vozralNkfagSn3Xc0Co7nrwfoxDhoD8C36ZW6d9ebl03rEgqtzABDO8aWNzfud4ue/6vDW1GfrSC67mvrQwG5A/zUzaSxWofz5TpIAJQIDAQAB";

	// 服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String notify_url = "http://182.92.97.65:8081/notify_url.view";

	// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String return_url = "http://182.92.97.65:8081/return_url.view";

	// 签名方式
	public static String sign_type = "RSA2";
	
	// 字符编码格式
	public static String charset = "utf-8";
	
	// 支付宝网关
	public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
	
	// 支付宝网关
	public static String log_path = "C:\\";


//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    /** 
     * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
     * @param sWord 要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3 编写 控制器  PayController 

package com.vue.vueapp.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.vue.vueapp.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;


@Controller
public class PayController {





    @RequestMapping(value = "pay")
    public void pay(HttpServletRequest req, ModelAndView  modelAndView, HttpServletResponse rep) throws AlipayApiException, IOException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号,商户网站订单系统中唯一订单号,必填
        String out_trade_no = UUID.randomUUID().toString().replace("-","");
        //付款金额,必填  (随机生成 0-1000)
        String total_amount =String.valueOf(Math.floor(Math.random() * 1000+1));
        //订单名称,必填
        String subject = "订单名称";
        //商品描述,可空
        String body = "特价苹果";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        rep.setContentType("text/html;charset=" + AlipayConfig.charset);
        rep.getWriter().write(result);//直接将完整的表单html输出到页面
        rep.getWriter().flush();
        rep.getWriter().close();

    }



    /**
     * 回调路径return_url
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws
     */
    @RequestMapping("return_url.view")
    @ResponseBody
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, UnsupportedEncodingException, UnsupportedEncodingException {

        System.out.println("调用 同步 回调");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决,这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            request.setAttribute("out_trade_no", out_trade_no);
            request.setAttribute("trade_no", trade_no);
            request.setAttribute("total_amount", total_amount);


            System.out.println("订单处理:系统订单号" + out_trade_no + "支付宝交易号:" + trade_no);
            //系统处理根据支付宝回调更改订单状态或者其他关联表的数据
          /*  OrderInfo order = payService.findOneByTradeCode(out_trade_no);
            if(order == null){
                signVerified = false;
                request.setAttribute("signVerified", signVerified);
                request.setAttribute("reason", "商户订单号不存在");
                System.out.println("系统订单:"+ out_trade_no + "不存在。");
            }else{
                if(!order.getMoney().toString().equals(total_amount)){
                    signVerified = false;
                    request.setAttribute("signVerified", signVerified);
                    request.setAttribute("reason", "付款金额不对");
                    return "notify_url";
                }


                if(order.getTradeStatus() == 1){//判断当前订单是否已处理,避免重复处理
                    log.info("系统订单:"+ out_trade_no + "无需重复处理。");
                }else{
                    order.setTradeStatus(1);//修改订单状态为已支付
                    Date payedAt = new Date();
                    order.setTransactionId(trade_no);
                    order.setPayedAt(payedAt);
                    payService.payOrder(order);
                    System.out.println("系统订单:"+ out_trade_no + "成功支付。");
                }

            }
*/
        }else{
            request.setAttribute("reason", "验签失败");
        }
        request.setAttribute("signVerified", signVerified);
        return "return_url";
    }


    /**
     * 异步回调路径 notify_url
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws
     */
    @RequestMapping("notify_url.view")
    public void notify_url(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        System.out.println("调用 异步 回调");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决,这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            request.setAttribute("out_trade_no", out_trade_no);
            request.setAttribute("trade_no", trade_no);
            request.setAttribute("total_amount", total_amount);


            System.out.println("订单处理:系统订单号" + out_trade_no + "支付宝交易号:" + trade_no);
            //系统处理根据支付宝回调更改订单状态或者其他关联表的数据
          /*  OrderInfo order = payService.findOneByTradeCode(out_trade_no);
            if(order == null){
                signVerified = false;
                request.setAttribute("signVerified", signVerified);
                request.setAttribute("reason", "商户订单号不存在");
                System.out.println("系统订单:"+ out_trade_no + "不存在。");
            }else{
                if(!order.getMoney().toString().equals(total_amount)){
                    signVerified = false;
                    request.setAttribute("signVerified", signVerified);
                    request.setAttribute("reason", "付款金额不对");
                    return "notify_url";
                }


                if(order.getTradeStatus() == 1){//判断当前订单是否已处理,避免重复处理
                    log.info("系统订单:"+ out_trade_no + "无需重复处理。");
                }else{
                    order.setTradeStatus(1);//修改订单状态为已支付
                    Date payedAt = new Date();
                    order.setTransactionId(trade_no);
                    order.setPayedAt(payedAt);
                    payService.payOrder(order);
                    System.out.println("系统订单:"+ out_trade_no + "成功支付。");
                }

            }
*/
        }else{
            request.setAttribute("reason", "验签失败");
        }
        request.setAttribute("signVerified", signVerified);


        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write("success");//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();




    }



}

 4 启动服务  访问  localhost:8080/pay   会直接支付宝支付页面  

然后使用 沙箱版支付宝  登录买家账号 进行扫码支付  下载连接  https://openhome.alipay.com/platform/appDaily.htm?tab=info

Appid  买家账号 可以参考 上篇文章 进行申请 (https://blog.csdn.net/qq_34789780/article/details/103985710

 

 支付成功后  会自动调用  同步和异步 回调接口

  异步回调接口 必须外网可以访问  否则不会调用   在 AlipayConfig 中进行配置

 

发布了20 篇原创文章 · 获赞 1 · 访问量 300
展开阅读全文

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

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览