PayPal支付接口方式(checkout)集成


1.簡述

  PayPal是倍受全球億萬用戶追捧的國際貿易支付工具,即時支付,即時到賬,全中文操作界面,能通過中國的本地銀行輕松提現,解決外貿收款難題,助您成功開展海外業務,決勝全球。注冊PayPal后就可立即開始接受信用卡付款。作為在線付款服務商,PayPal是您向全世界近2.54億的用戶敞開大門的最快捷的方式。 最大的好處是,注冊完全免費!集國際流行的信用卡,借記卡,電子支票等支付方式於一身。幫助買賣雙方解決各種交易過程中的支付難題。PayPal是名副其實的全球化支付平台, 服務范圍超過200個市場, 支持的幣種超過100個。在跨國交易中, 將近70%的在線跨境買家更喜歡用PayPal支付海外購物款項。

  PayPal提供了多種支付方式

  • 標准支付
  • 快速支付
  • 其中標准支付譽為最佳實踐。

  注意:paypal支付國內賬號不能付款給國內賬號

2.PayPal的相關URL

  正式網址https://www.paypal.com/ 

  沙箱(開發者)網址https://developer.paypal.com/

  沙箱(測試用戶)登錄地址https://www.sandbox.paypal.com/

  demo地址https://demo.paypal.com/c2/demo/code_samples

  webHooks驗證(調用API)https://developer.paypal.com/docs/api/webhooks/v1#verify-webhook-signature

官方文檔

3.PayPal Checkout集成步驟

  1、整合Smart Payment Buttons(PayPal智能付款按鈕)到頁面

  2、用戶點擊支付按鈕

  3、按鈕調用PayPal Orders API來創建交易

  4、進入PayPal支付頁面

  5、用戶登錄后確認支付

  6、按鈕調用PayPal Orders API來完成交易

  7、顯示支付成功信息

4.PayPal Checkout集成步驟實現

(1)注冊賬號

  在PayPal正式網站https://www.paypal.com中注冊一個賬號,如果公司沒有給你相關信息的話,先注冊一個個人賬號也是一樣的。

(2)進入開發者界面創建相關信息

  1、在開發者平台https://developer.paypal.com/,登錄剛創建的賬號

 

  2、登錄成功后,選擇:SANBOX下的Accounts標簽

 

  3、創建個人賬號和商家賬號用於測試沙箱環境

 

  4、創建APP獲取client id和secret

 

  點擊Create app創建

 

 

 

(3)示例代碼

  控制器代碼如下

@Controller
@RequestMapping("/paypalC")
public class PaypalC {

    @Autowired
    private PaypalS paypalS;

    @RequestMapping(method = RequestMethod.GET)
    public String index(){
        return "index";
    }
    
    /**創建訂單
     */
    @RequestMapping(method = RequestMethod.POST, value = "createOrder")
    public void createOrder(HttpServletRequest req, HttpServletResponse resp){
        paypalS.createOrder(req, resp);
    }

    /**執行付款
     */
    @RequestMapping(method = RequestMethod.POST, value = "executePayment")
    public void executePayment(HttpServletRequest req, HttpServletResponse resp){
        paypalS.executePayment(req, resp);
    }

    /**交易取消
     */
    @RequestMapping(method = RequestMethod.GET, value = "cancel")
    public String cancel(){
        return "cancel";
    }

    /**交易成功返回頁面
     */
    @RequestMapping(method = RequestMethod.GET, value = "success")
    public String success(HttpServletRequest req, HttpServletResponse resp, String orderId){
        req.setAttribute("orderId", orderId);
        return "success";
    }
    
    /**查詢交易詳情
     */
    @RequestMapping(method = RequestMethod.POST, value = "paymentDetails")
    public void paymentDetails(HttpServletRequest req, HttpServletResponse resp, String orderId){
        paypalS.paymentDetails(req, resp, orderId);
    }
}
View Code

  業務層代碼如下

/**Paypal支付service類
 */
@Service
public class PaypalS {
    /**創建訂單
     */
    public void createOrder(HttpServletRequest req, HttpServletResponse resp){
        //1.獲取paypal的token
        String accessToken = PaypalUtils.getAccessToken();
        //2.提交交易到paypal
        String BaseUrl = req.getScheme() + "://"+ req.getServerName() + ((req.getServerPort() == 80) ? "" : ":" + req.getServerPort()) + req.getContextPath();
        String result = PaypalUtils.createOrder(req, accessToken, BaseUrl);
        resp.setContentType("application/json");
        try {
            PrintWriter out = resp.getWriter();
            out.print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**執行付款
     */
    public void executePayment(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("application/json");
        try {
            String jsonFromHtml = readInputStreamForData(req); // holding the json from request
            JSONObject json = JSONObject.parseObject(jsonFromHtml);
            String orderId = json.getString("orderId");//付款id
            String accessToken = PaypalUtils.getAccessToken();
            String result = PaypalUtils.executePayment(req, accessToken, orderId);
            PrintWriter out = resp.getWriter();
            out.print(result);
        }catch(Exception e) {
            e.printStackTrace();
            try {
                PrintWriter out = resp.getWriter();
                out.print(new AjaxDto(0, "支付失敗,請聯系管理員...", req).toJson());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    /**查詢交易詳情
     */
    public void paymentDetails(HttpServletRequest req, HttpServletResponse resp,String orderId){
        try {
            String accessToken = PaypalUtils.getAccessToken();
            JSONObject dataFromGetPaymentsAPI = PaypalUtils.getPaymentDetails(req, accessToken, orderId);
            resp.setContentType("application/json");
            resp.setStatus(200);
            PrintWriter out = resp.getWriter();
            out.print(dataFromGetPaymentsAPI);
        } catch (Exception e) {
            resp.setStatus(500);
            resp.setContentType("application/json");
            try {
                PrintWriter out = resp.getWriter();
                Map<String, String> error = new HashMap<String, String>();
                error.put("error", "獲取交易詳情失敗,請聯系管理員!!!");
                out.print(error);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    /**獲取req傳遞參數
     */
    private String readInputStreamForData(HttpServletRequest req) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        String json = "";
        if(br != null) {
            json = br.readLine();
        }
        return json;
    }
}
View Code

  PayPal工具類如下

public class PaypalUtils {
    private static Log log = LogFactory.getLog(PaypalUtils.class);
    /**true表示測試環境(沙盒),false:正式環境
     */
    private static boolean IS_APPLICATION_IN_SANDBOX = true;
    //TODO 測試環境使用
    /**沙盒帳戶詳細信息-賣方
     */
    private static String SELLAR_SANDBOX_EMAIL = "";//郵箱
    private static String SELLAR_SANDBOX_PASSWORD = "";//密碼
    private static String SELLAR_SANDBOX_SIGNATURE = "";//標簽
    /**App Client ID 和 SECRET
     */
    private static String CLIENT_ID = "";//Client ID
    private static String SECRET = "";//SECRET
    
    private static String ACCESS_TOKEN_URL = "https://api.sandbox.paypal.com/v1/oauth2/token";//獲取token接口
    private static String CREATE_PAYMENT_URL = "https://api.sandbox.paypal.com/v2/checkout/orders";
    private static String EXECUTE_PAYMENT_URL = "https://api.sandbox.paypal.com/v2/checkout/orders/{id}/capture";
    private static String GET_PAYMENT_DETAILS = "https://api.sandbox.paypal.com/v2/checkout/orders/{id}";
    
    
    //TODO 正式環境使用
    /**真實帳戶詳細信息-賣方
     */
    private static String SELLAR_LIVE_EMAIL = "";//郵箱
    private static String SELLAR_LIVE_PASSWORD = "";//密碼
    private static String SELLAR_LIVE_SIGNATURE = "";//標簽
    /**App Client ID 和 SECRET
     */
    private static String CLIENT_ID_LIVE = "";//Client ID
    private static String SECRET_LIVE = "";//SECRET
    
    private static String ACCESS_TOKEN_URL_LIVE = "https://api.paypal.com/v1/oauth2/token";//獲取token接口
    private static String CREATE_PAYMENT_URL_LIVE = "https://api.paypal.com/v2/checkout/orders";
    private static String EXECUTE_PAYMENT_URL_LIVE = "https://api.paypal.com/v2/checkout/orders/{id}/capture";
    private static String GET_PAYMENT_DETAILS_LIVE = "https://api.paypal.com/v2/checkout/orders/{id}";
    
    private static String CANCEL_URL= "paypalC/cancel";//交易失敗頁面
    private static String RETURN_URL= "paypalC/success";//交易成功頁面
    
    /**初始化配置實體
     */
    public static PaypalConfigBean paypalConfigBean = new PaypalConfigBean();
    static{
        if(IS_APPLICATION_IN_SANDBOX) {
            // load all properties for sandbox
            paypalConfigBean.setAccessTokenUrl(ACCESS_TOKEN_URL);
            paypalConfigBean.setClientId(CLIENT_ID);
            paypalConfigBean.setCreatePaymentsUrl(CREATE_PAYMENT_URL);
            paypalConfigBean.setExecutePaymentsUrl(EXECUTE_PAYMENT_URL);
            paypalConfigBean.setGetPaymentsDetailsUrl(GET_PAYMENT_DETAILS);
            paypalConfigBean.setSecret(SECRET);
        }else {
            // load all properties for live
            paypalConfigBean.setAccessTokenUrl(ACCESS_TOKEN_URL_LIVE);
            paypalConfigBean.setClientId(CLIENT_ID_LIVE);
            paypalConfigBean.setCreatePaymentsUrl(CREATE_PAYMENT_URL_LIVE);
            paypalConfigBean.setExecutePaymentsUrl(EXECUTE_PAYMENT_URL_LIVE);
            paypalConfigBean.setGetPaymentsDetailsUrl(GET_PAYMENT_DETAILS_LIVE);
            paypalConfigBean.setSecret(SECRET_LIVE);
        }
        paypalConfigBean.setCancelUrl(CANCEL_URL);
        paypalConfigBean.setReturnUrl(RETURN_URL);
    }
    
    
    //TODO paypal請求處理
    /**獲取paypal的Token
     */
    public static String getAccessToken() {
        Map<String, String> headers = new HashMap<String, String>();
        String token = getBasicBearerToken(paypalConfigBean.getClientId(), paypalConfigBean.getSecret());
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("accept-language", "en_US");
        headers.put("Authorization", token);
        String param = "grant_type=client_credentials";
        try {
            Map<String, String> data = HttpsUtils.doPost(headers, param, paypalConfigBean.getAccessTokenUrl());
            if(!OUtils.isEmpty(data.get("statusCode")) && data.get("statusCode").startsWith("2")){
                JSONObject jsonObj = JSONObject.parseObject(data.get("data"));
                return jsonObj.getString("access_token");
            }else{
                log.error("paypal的token獲取失敗,參數:"+token+",返回結果:"+data);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }
    
    /**創建訂單
     */
    public static String createOrder(HttpServletRequest req, String accessToken, String BaseUrl){
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("accept-language", "en_US");
        headers.put("authorization", "Bearer "+accessToken);
        
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//訂單信息
        Map<String, Object> order = new HashMap<String, Object>();
        Map<String, String> orderInfo = new HashMap<String, String>();
        orderInfo.put("currency_code", "USD");//支付貨幣
        orderInfo.put("value", "100.00");//支付金額
        order.put("reference_id","PUHF");//訂單編號,多個訂單時使用
        order.put("amount", orderInfo);
        list.add(order);
        
        Map<String, String> redirects = new HashMap<String, String>();
        redirects.put("return_url", BaseUrl+"/"+paypalConfigBean.getReturnUrl());//付款成功返回地址
        redirects.put("cancel_url", BaseUrl+"/"+paypalConfigBean.getCancelUrl());//付款失敗返回地址
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("intent", "CAPTURE");//創建付款
        params.put("purchase_units", list);//訂單信息
        params.put("application_context", redirects);//返回地址,無效的地址
        
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String param = JSONObject.toJSONString(params);
            Map<String, String> data = HttpsUtils.doPost(headers, param, paypalConfigBean.getCreatePaymentsUrl());
            if(!OUtils.isEmpty(data.get("statusCode")) && data.get("statusCode").startsWith("2")){
                JSONObject jsonObj = JSONObject.parseObject(data.get("data"));
                result.put("id", jsonObj.getString("id"));
            }else{
                log.error("paypal創建訂單失敗,token:"+accessToken+",參數:"+param+",返回結果:"+data);
                return new AjaxDto(0, "創建訂單失敗,請聯系管理員...", req).toJson();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return new AjaxDto(1, null, result).toJson();
    }
    
    /**執行paypal付款
     */
    public static String executePayment(HttpServletRequest req, String accessToken,  String orderId) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer "+accessToken);
        String url = paypalConfigBean.getExecutePaymentsUrl().trim();
        url = url.replace("{id}", orderId);
        
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, String> data = HttpsUtils.doPost(headers, null, url);
            if(!OUtils.isEmpty(data.get("statusCode")) && data.get("statusCode").startsWith("2")){
                JSONObject jsonObj = JSONObject.parseObject(data.get("data"));
                result.put("id", jsonObj.getString("id"));
            }else{
                log.error("paypal支付失敗,token:"+accessToken+",返回結果:"+data);
                return new AjaxDto(0, "支付失敗,請聯系管理員...", req).toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDto(1, null, result).toJson();
    }
    
    /**獲取付款詳情
     */
    public static JSONObject getPaymentDetails(HttpServletRequest req, String accessToken, String orderId) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer "+accessToken);
        String url = paypalConfigBean.getGetPaymentsDetailsUrl().trim();
        url = url.replace("{id}", orderId);
        String data = HttpsUtils.doGet(headers, url);
        if(!OUtils.isEmpty(data)){
            JSONObject jsonObj = JSONObject.parseObject(data);
            return jsonObj;
        }
        return null;
    }
    
    /**把paypal的clientId、secret轉為Base64
     */
    private static String getBasicBearerToken(String clientId, String secret) {
        String token = clientId.toString().trim() +":"+secret.toString().trim();
        token = token.replace("\"", "");
        Base64 b = new Base64();
        String accessToken = b.encodeAsString(new String(token).getBytes());
        return "Basic "+ accessToken;
    }
    
    /**paypal返回的錯誤
     */
    private static String getPaypalError(String statusCode,String errorCode){
        return "";
    }
}
View Code

  HttpUtils工具類(httpclient-4.5.jar、httpcore-4.4.1.jar)如下

public class HttpsUtils {
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;
    static {
        try {
            builder = new SSLContextBuilder();
            // 全部信任 不做身份鑒定
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);// max connection
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * httpClient post請求
     * 
     * @param url
     *            請求url
     * @param header
     *            頭部信息
     * @param param
     *            請求參數 form提交適用
     * @param entity
     *            請求實體 json/xml提交適用
     * @return 可能為空 需要處理
     * @throws Exception
     * 
     */
    public static String doGet(String url) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 設置請求和傳輸超時時間
            httpGet.setConfig(requestConfig);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                readHttpResponse(httpResponse);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }

    /**
     * httpClient post請求
     * 
     * @param url
     *            請求url
     * @param header
     *            頭部信息
     * @param param
     *            請求參數 form提交適用
     * @param entity
     *            請求實體 json/xml提交適用
     * @return 可能為空 需要處理
     * @throws Exception
     * 
     */
    public static String doPost(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // 設置頭信息
            if (MapUtils.isNotEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 設置請求參數
            if (MapUtils.isNotEmpty(param)) {
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    // 給參數賦值
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 設置實體 優先級高
            if (entity != null) {
                httpPost.setEntity(entity);
            }
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                readHttpResponse(httpResponse);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }
    
    public static String doGet(Map<String, String> header, String url) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpGet httpGet = new HttpGet(url);
            if (MapUtils.isNotEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// ��������ʹ��䳬ʱʱ��
            httpGet.setConfig(requestConfig);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                readHttpResponse(httpResponse);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }
    
    public static Map<String, String> doPost(Map<String, String> header, String param, String url) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            if (MapUtils.isNotEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            if (!OUtils.isEmpty(param)) {
                httpPost.setEntity(new StringEntity(param));
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity resEntity = httpResponse.getEntity();
            data.put("statusCode", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
            data.put("data", EntityUtils.toString(resEntity));
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return data;
    }

    public static CloseableHttpClient getHttpClient() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true).build();

        return httpClient;
    }

    public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
        StringBuilder builder = new StringBuilder();
        // 獲取響應消息實體
        HttpEntity entity = httpResponse.getEntity();
        // 響應狀態
        builder.append("status:" + httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            builder.append("\t" + iterator.next());
        }
        // 判斷響應實體是否為空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:" + responseString.length());
            builder.append("response content:" + responseString.replace("\r\n", ""));
        }
        return builder.toString();
    }
}
View Code

  cancel.html代碼如下

<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <h1>用戶取消支付...</h1>
</body>
</html>
View Code

  index.html代碼如下:

<div style="width:20px;" id="paypal-button-container"></div>
<script src="https://www.paypal.com/sdk/js?client-id=sb&commit=false"></script><!-- client-id正式環境需要改,測試環境才用sb -->
 
<script>
 
paypal.Buttons({
 
    env: 'sandbox', /* sandbox | production */
    style: {
                layout: 'horizontal',   // 布局方式:vertical: 垂直,horizontal:水平,
                size:   'responsive',   /* medium | large | responsive*/
                shape:  'pill',         /* pill | rect*/
                color:  'gold',         /* gold | blue | silver | black*/
                label: 'paypal'
            }, 
     commit: false, // Show a 'Pay Now' button
      /* createOrder() is called when the button is clicked */
 
    createOrder: function() {
        /* Set up a url on your server to create the order */
        var CREATE_URL = '<%=request.getContextPath() %>/paypalC/createOrder';
        /* Make a call to your server to set up the payment */
        return fetch(CREATE_URL,{
            method: 'post'
         }).then(function(res) {
          return res.json();
         }).then(function(data) {
          if(data.result == 1)
              return data.obj.id;
          else{
              alert(data.msg);
          }
         });
 
    },
    /* onApprove() is called when the buyer approves the payment */
    onApprove: function(data, actions) {
        /* Set up a url on your server to execute the payment */
        var EXECUTE_URL = '<%=request.getContextPath() %>/paypalC/executePayment';
        /* Set up the data you need to pass to your server */
        /* Make a call to your server to execute the payment */
        return fetch(EXECUTE_URL, {
         method: 'post',
         body: JSON.stringify({
          orderId: data.orderID
         })
        }).then(function(res) {
         return res.json();
        }).then(function(data) {
            if(data.result == 1)
                window.location.href='<%=request.getContextPath() %>/paypalC/success?orderId='+data.obj.id;
            else{
                  alert(data.msg);
            }
        });
 
    },onCancel: function() {
        return window.location.href='<%=request.getContextPath() %>/paypalC/cancel';
    }
 
}).render('#paypal-button-container');
 
</script>
View Code

  success.html代碼如下

<html>
  <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>PayPal Credit</title>
      <!--Including Bootstrap style files-->
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
      <style>
          /* http://angrytools.com/gradient/ */
          .bg-color {
              color: white;
              background: -moz-linear-gradient(0deg, #004094 0%, #0096D9 50%, #004094 100%); /* ff3.6+ */
              background: -webkit-gradient(linear, left top, right top, color-stop(0%, #004094), color-stop(50%, #0096D9), color-stop(100%, #004094)); /* safari4+,chrome */
              background: -webkit-linear-gradient(0deg, #004094 0%, #0096D9 50%, #004094 100%); /* safari5.1+,chrome10+ */
              background: -o-linear-gradient(0deg, #004094 0%, #0096D9 50%, #004094 100%); /* opera 11.10+ */
              background: -ms-linear-gradient(0deg, #004094 0%, #0096D9 50%, #004094 100%); /* ie10+ */
              background: linear-gradient(90deg, #004094 0%, #0096D9 50%, #004094 100%); /* w3c */
              filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#004094', endColorstr='#004094',GradientType=1 ); /* ie6-9 */
          }
          .mark{
              max-width: 45%;
          }
          .mark-input-field{
              height:30px !important;
          }
      </style>
  </head>
  <body>
      <div class="container-fluid">
          <div class="row">
                 <div class="col-md-4 col-md-offset-4">
                            <div class="loader" style="margin-top:10px; margin-left:80px">付款成功</div>
                            <!-- Display the Transaction Details-->
                            <div id="show_transactions">
                                <h4> 
                                    <div id="firstName"></div>
                                    <div id="lastName"></div>謝謝您的訂單 
                                </h4>
                                <div><strong>訂單編號:</strong> <span id="transactionId"></span> </div>
                                <div><strong>交易類型:</strong><span id="transactionType"></span> </div>
                                <div><strong>總金額:</strong><span id="amt"></span>  </div>
                                <div><strong>貨幣代碼:</strong><span id="currencyCode"></span>  </div>
                                <div><strong>支付狀態:</strong><span id="paymentStatus"></dispanv>  </div>
                            </div>
                        
                </div> 
            </div>
        </div>  <!--Container-Fluid ends here -->
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://code.jquery.com/jquery.js"></script>
        
        <script> 
            $( document ).ready(function() {
                // set back url 
                var url = location.pathname.split("/")[1]; url = '/'+url+'/'
                $('#go_back').attr('href',url);
                function qs(key) {
                    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
                    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
                    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
                }
                var orderId = qs("orderId");
                $.post('<%=request.getContextPath() %>/paypalC/paymentDetails?orderId='+orderId, function( data ) {
                        $("#transactionId").html(data.id);
                        $("#transactionType").html(data.intent);
                        $("#amt").html(data.purchase_units[0].amount.value);
                        $("#currencyCode").html(data.purchase_units[0].amount.currency_code);
                        $("#paymentStatus").html("COMPLETED" == data.status ? "交易完成" : "交易失敗");
                });
            });
        </script> 
    </body>
</html>
View Code


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM