天天看點

Java手把手教你學會支付寶APP支付

1,阿裡的APP支付相對來微信來說很簡單,第一步我們需要擷取以下幾個參數

    // 商戶appid-----h5支付的ID

    public static String        APPID             = "APPID";

    // 私鑰 pkcs8格式的

    public static String        RSA_PRIVATE_KEY   =""

    // 伺服器異步通知頁面路徑 需http://或者https://格式的完整路徑,不能加?id=123這類自定義參數,必須外網可以正常通路

    public static String        notify_url        = "https://此處域名/faint-service/f/ali/alipayRechargeGoldNotify";

    // 頁面跳轉同步通知頁面路徑 需http://或者https://格式的完整路徑,不能加?id=123這類自定義參數,必須外網可以正常通路       商戶可以自定義同步跳轉位址

    public static String        return_url        = "https://此處域名/faint-service/static/h5/app/successh5.html";

    // 請求網關位址

    public static String        URL               = "https://openapi.alipay.com/gateway.do";

    // 編碼

    public static String        CHARSET           = "UTF-8";

    // 傳回格式

    public static String        FORMAT            = "json";

    // 支付寶公鑰

    public static String        ALIPAY_PUBLIC_KEY = ""

    // RSA2

    public static String        SIGNTYPE          = "RSA2";

APPID:怎樣申請支付寶支付的整個流程我就不一一細說了,APPID在你申請APP支付的時候就可以得到此資料

RSA_PRIVATE_KEY 和ALIPAY_PUBLIC_KEY   :公鑰私鑰也是你申請APP支付會設定的資料

notify_url        :支付寶支付成功回調到伺服器的位址,獲得成功資料

return_url        如果是H5支付的話,需要填寫,APP支付不需要,支付成功傳回的頁面.

URL              :此URL是把資料打包到支付寶  喚醒支付寶支付的位址

CHARSET            FORMAT            SIGNTYPE          :這三個是固定死的,填就完事

2,開始寫代碼了,前端請求支付,後端處理資料,打包到支付寶伺服器

 @ResponseBody

    @RequestMapping(value = "openForAPP", method = RequestMethod.POST)

    public Result<T> openForAPP(MdAppertain mdAppertain) {

        logger.info("AliController.openForAPP=======start");

        Result<T> result = new Result<T>();

        try {

            //執行個體化用戶端

            AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APPIDFORAPP, AliPayConfig.RSA_PRIVATE_KEY, "json", AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, "RSA2");

            //執行個體化具體API對應的request類,類名稱和接口名稱對應,目前調用接口名稱:alipay.trade.app.pay

            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

            //SDK已經封裝掉了公共參數,這裡隻需要傳入業務參數。以下方法為sdk的model入參方式(model和biz_content同時存在的情況下取biz_content)。

            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

            String reaMoney = Constant.MDAPPERTAIN_PRICE.toString();

            model.setBody("付費認證");//商品名稱

            model.setSubject("付費認證");//商品類型

            model.setOutTradeNo(str); //訂單号

            model.setTimeoutExpress("30m");

            model.setTotalAmount(reaMoney); //真實金額

            model.setProductCode("QUICK_MSECURITY_PAY"); //表示APP支付

            request.setBizModel(model);

            request.setNotifyUrl(AliPayConfig.notify_appestationAttUrl);

            //這裡和普通的接口調用不同,使用的是sdkExecute

            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);

            Map<String, Object> payMap = new HashMap<String, Object>();

            payMap.put("orderStr", response.getBody());

            result.setMap(payMap);

            result.setCode(Constant.RETRUN_SUCCESS);

            result.setMsg(Constant.RETRUN_SUCCESS_MSG);

            //System.out.println(response.getBody());//就是orderString 可以直接給用戶端請求,無需再做處理。

        } catch (AlipayApiException e) {

            logger.error("CreatPayOrderForAPP", e);

            result.setCode(Constant.RETRUN_FAIL);

            result.setMsg(Constant.RETRUN_FAIL_MSG);

        }

        return result;

    }

3支付寶支付成功後傳回伺服器跟用戶端資料

@ResponseBody

    @RequestMapping(value = "openForAPPNotify", method = RequestMethod.POST)

    public String openForAPPNotify(HttpServletRequest request, HttpServletResponse response) {

        logger.info("AliController.openForAPPNotify=======start");

        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)

        try {

            boolean flag = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, "RSA2");

            if (flag) {

                if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {

                    String orderId = params.get("out_trade_no"); //商家訂單号

                    String moneyNumber = params.get("total_amount"); //實際支付金額

                    BigDecimal amountPay = new BigDecimal(moneyNumber);//将分轉化為元的對象

                    Double rmb = amountPay.doubleValue();

                    //此處處理自己的業務邏輯

                }

                response.getWriter().print("success");

                logger.info("flag簽名驗證成功");

            } else {

                // 驗證失敗

                response.getWriter().print("failure");

            }

        } catch (Exception e) {

            logger.error("openForAPPNotify", e);

            logger.info("flag簽名擷取訂單資訊異常");

        }

        logger.info("AliController.getNotify=======end");

        return null;

    }

支付寶支付到此成功了,有什麼問題可以給我留言,