1. 程式人生 > 實用技巧 >穀粒商城整合支付寶(四十五)

穀粒商城整合支付寶(四十五)

304-309

主要對支付寶的開放平臺對接的使用,驗簽收單有了一定的連線。

視訊中的nginx配置:

我沒有動這塊,還是走的阿里雲:

程式碼具體如下:

@ConfigurationProperties(prefix = "alipay")
@Component
public class AlipayTemplate {

    // 應用ID,您的APPID,收款賬號既是您的APPID對應支付寶賬號
    public static String app_id = "2021000116667682";

    // 商戶私鑰,您的PKCS8格式RSA2私鑰
    public static String merchant_private_key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQClo7YKk8lnuHsKe4aOLmNd/vCRZ5ia8kpxvSR9iy1REkpfVV1cV1TqQlSj3OZ62PtoHDNbCbgp01gUxe/96PwObjpWudxtVklf8YifTFWPafed0q0blEBayzXt26tX8H/Uxd0oKFmdh+VYLDJ6or3qPfrhd8f298v1Ijrc1ituAgTsHybQ946WpnE+JhTAmCinzxeDrXAOZ96WDyaZB7hxPKu+AvLEU/RJIxKLXyVN51rEeI+kYDNQvscs/8WVXN0Qldkd1bXnB5RpOeEl7D7Q7ZasK4Q9vRnSw1Yu1vtWv5HlUgopfCweix+wkIWK/dFTfF5i5KW0etXJc38vCLw9AgMBAAECggEAOCtcABo9oj6c+uEIsA5rA+UAD07iISkotYk+ZpRbubJKJin8juPOl+IGccrnHaGXH6bwg164ZPaWV/UHfUMUtpAKmH5OkYVBPJfbjKmGGiwFHC/lJAUSDbf7gb2MTTXxI2Y1qPiF6zW6QDw8ofmuDVEXUn4cAVPmhiola930vEjGdCFvY1vTOFw64fECAnE8/zkEF98byluE3DqSFZmUQfMeuu0LYwMcVCiv+qXmBH/I5ojOfXCHkbzUPYCE0OIg4Agu1QMlkA6YXn0d4KW7nrME1BUC2UJTNFsJwP5wg5hWiNOEab8vlsYKIIiFPlO0+VFUWAXPz6IaEFjSMaFewQKBgQDmmZvrLP3QFF3HeE74yKymvM5OOjP1ovKde7jko2fZPUmJst6ef4/VI39BHLTWS/IHc9OpufPfFrObgf2vbaLvc+xzQcz5EeuH+haYYIF6PFLAvhpl6+nv8BNh8nlZjr7GCqOqKR+gfPfJHakA2q1H2if1c4HLsyTgUc2VurxcOwKBgQC34l05vgSK2vDlgj9haWohtJBSZl+iHuMb9+Df6Dhc81ugUKx1QjQApyYTAaxUDGWY6NxQ7NSWjO4qcXM5KDL/GJhFRRC5qZDNERQ2jPpieqIq0BiYWYGOn57V3wNOFU8xk8rKMVhiGATcHpPG9bHP6a7uQ65TlX7DTuImhfNZ5wKBgQCPtEBXQXV2m4qJiO7l2ODHE7gZReoldINvIq/pQ++ukKPoPODAs0vmDjX6VLJZLYDJpiPMjIZuiw4opcx6637zbDF47hOXT9SQq4gzM0jc7QTA+ncm9uqVTO43Rszaw7sdXXn6y5/a+qXL3kD4uE3uDgSC0JWdZKlhZXkRiwphCwKBgQC2GYii9yc+b0Vis5KaoC8HQ+4se883GIlmGBrtAeZXPnS9lUbENJSVFPJiniSPc1tliy0rQu3gTZ5KD+HAd6vQ7gVVi+jdRCvuuHwg7YnD3pgb98pzjSf9GtvMBrcaK4YqnaaUhzt0oT6m0e0cehHlyRCASiwoAALx3XueFMcCfwKBgQCrFBEOO04bWDX0pTrA2OU8FtvoXAUl2ji3FOXC4sUxgFnT9dFw/PlpGtx9DjYcspvHC+cNAYkxAUepePXkZbj8SSOgHjsdKouSM+Nwo9+93DGN29YUO6l6AIt6IPxXvSGUTQUCPlBQ2A1y4YFEjg5uxu85u3AYqa6a4qYTVMFKeQ==";
    // 支付寶公鑰,檢視地址:https://openhome.alipay.com/platform/keyManage.htm 對應APPID下的支付寶公鑰。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkTof8EkrceHNaJcuqPx7aAUFPJ1X3WBwf9wDgPlQ2U/lnNCd6z196azAYpR9WJSqZv9iJY9TFVBIr+XHr4hFsdIgyb3ZkH6MIs3x2yahMij+3msUY34NQkrz3S90Fb1FfTFYoANOxwhP2Q7QyfNyJkZgcVvCnf66lsGt/E1eXxUP8xpVcHUgWVHp+orGlMXkGsC8XuHcTTFCAdhA+NHHjDCPLOJ1cWcqDjmSk8WqH+FGEvGt+HwiNxZvImoa4+4CIwlwAv+CayRgjvpqk6H50KNkTP54AVgR1DYCs6nqvoGuj6V+mlEisT9U1Rl5XJxX6JPg0ddGq1rDdFh+wGRM/wIDAQAB";
    // 伺服器非同步通知頁面路徑  需http://格式的完整路徑,不能加?id=123這類自定義引數,必須外網可以正常訪問
    public static String notify_url = "http://47.110.91.150/payed/notify";

    // 頁面跳轉同步通知頁面路徑 需http://格式的完整路徑,不能加?id=123這類自定義引數,必須外網可以正常訪問
    public static String return_url = "http://member.gulimall.com/memberOrder.html";

    // 簽名方式
    public static String sign_type = "RSA2";

    // 字元編碼格式
    public  static String charset = "utf-8";

    // 支付寶閘道器
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    public  String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根據支付寶的配置生成一個支付客戶端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、建立一個支付請求 //設定請求引數
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商戶訂單號,商戶網站訂單系統中唯一訂單號,必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金額,必填
        String total_amount = vo.getTotal_amount();
        //訂單名稱,必填
        String subject = vo.getSubject();
        //商品描述,可空
        String body = vo.getBody();

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

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //會收到支付寶的響應,響應的是一個頁面,只要瀏覽器顯示這個頁面,就會自動來到支付寶的收銀臺頁面
        System.out.println("支付寶的響應:"+result);

        return result;

    }
}

進行驗籤:

/**
 * @author WGR
 * @create 2020/8/13 -- 0:03
 */
@RestController
public class OrderPayedListener {

    @Autowired
    OrderService orderService;


    @PostMapping("/payed/notify")
    @SneakyThrows
    public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request){
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        for (String key : parameterMap.keySet()){
//            String value = request.getParameter(key);
//            System.out.println("引數名:"+key+"==>引數值:"+value);
//        }
        //獲取支付寶GET過來反饋資訊
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> 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);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayTemplate.alipay_public_key, AlipayTemplate.charset, AlipayTemplate.sign_type); //呼叫SDK驗證簽名

        //——請在這裡編寫您的程式(以下程式碼僅作參考)——
        if(signVerified) {
            System.out.println("驗籤成功");
            String reuslt =  orderService.handlePayResult(vo);
            return reuslt;
        }else {
            System.out.println("驗籤失敗");
            return "error";
        }

    }
}

需要放行:

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/order/status/**", uri);
        boolean match1 = antPathMatcher.match("/payed/notify", uri);
        if(match || match1){
            return true;
        }

        MemberRespVo attribute = (MemberRespVo)request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute !=null){
            loginUser.set(attribute);
            return true;
        }else{
            request.getSession().setAttribute("msg","請先進行登入");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
   @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1.儲存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //2.修改訂單的狀態資訊
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId() ).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }