The latest version of the PayPal quick integration method (personal experience record)

First, register a merchant account. This is a non-technical process. Just follow the steps. I won't go into details.

First you need to create an application

https://developer.paypal.com/developer/applications/

Create an app here and get

clientId and clientSecret , which will be used below, the next step is to create a test account, which will also be used below

https://developer.paypal.com/developer/accounts/

Let's talk about PayPal's code embedding:

There are three ways

1.Server Side Express Checkout using REST

2.Client Side Express Checkout using REST

3.Express Checkout using Braintree SDK

Because we have an existing payment system and just want to additionally support PayPal as a payment method, we adopted the first method

Let's talk about the implementation of the page part first

<!DOCTYPE html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>

  </head>
  
  <body>
    <div id="paypal-button-container"></div>

    <script>
        paypal.Button.render({

            env: 'sandbox', // sandbox | production

            // Show the buyer a 'Pay Now' button in the checkout flow
            commit: true,

            // payment() is called when the button is clicked
            payment: function() {

                // 你自己的订单生成地址,在这个接口里面 调用PayPal接口生成订单 同时 生成自己系统的订单
                var CREATE_URL = 'XXX/wapi/pay/paypalCreate';

                // Make a call to your server to set up the payment
                return paypal.request.post(CREATE_URL)
                    .then(function(res) {
                    	//这里是生成 PayPal订单后  PayPal的接口 返回的PayPal的 订单id
                        return res.paymentID;
                    });
            },

            // onAuthorize() is called when the buyer approves the payment
            onAuthorize: function(data, actions) {

                // 用户在PayPal确认付款后的回调地址  换成自己的接口 订单执行(完成)接口 这里要调用 PayPal的 订单确认接口,同时把自己系统的订单变成支付完成状态
                //这里只讲 快速集成,不讲 如何保证数据的一致性 各个系统自己实现
                var EXECUTE_URL = 'XXXX/wapi/pay/paypalExecute';

                // Set up the data you need to pass to your server
                var data = {
                    paymentID: data.paymentID,//订单id
                    payerID: data.payerID//支付用户id
                };

                // Make a call to your server to execute the payment
                return paypal.request.post(EXECUTE_URL, data)
                    .then(function (res) {
                        window.alert('Payment Complete!');
                    });
            }

        }, '#paypal-button-container');
    </script>
  </body>
</html>

The implementation of this page is completed, and other business logic can be supplemented by yourself.

Next is the implementation of the two interfaces used on the page

First, you need to download the jar package file used: https://github.com/paypal/PayPal-Java-SDK/wiki/Installation The latest file download address, I use

<dependency>
	<groupId>com.paypal.sdk</groupId>
	<artifactId>rest-api-sdk</artifactId>
	<version>LATEST</version>
</dependency>

Next are two interfaces, where the clientId and clientSecret obtained at the beginning are used here

     /**
	 * paypal订单生成
	 * @return
	 */
	@RequestMapping(value = "/paypalCreate",produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String paypalCreate(HttpServletRequest request, HttpServletResponse response) {
		APIContext apiContext = new APIContext(clientId, clientSecret, "sandbox");//上线记得改为正
    式环境
		Payment payment = new Payment();//交易对象
		Payer payr = new Payer();//支付信息
		payr.setPaymentMethod("paypal");//支付方式
		payment.setPayer(payr);
		payment.setIntent("sale");//交易类型
		RedirectUrls redirectUrls = new RedirectUrls();//回跳信息
		redirectUrls.setCancelUrl("url");//交易取消回跳地址
		redirectUrls.setReturnUrl("url");//交易成功回跳地址
		payment.setRedirectUrls(redirectUrls );
		
		List<Transaction> transactions = new ArrayList<Transaction>(); //商品信息
		Transaction transaction = new Transaction();
		Amount amount = new Amount();//总计费用
		amount.setTotal("3.00");
		amount.setCurrency("USD");
		transaction.setAmount(amount );
		transaction.setDescription("测试订单");
		transaction.setInvoiceNumber("自己系统的订单号");
		transactions.add(transaction);
		payment.setTransactions(transactions);
		String payId = null;
		try {
			Payment pay = payment.create(apiContext);
			payId = pay.getId();
		} catch (PayPalRESTException e) {
			logger.error("paypal完成支付出现异常,异常信息:" + e.getMessage());
		}
		Map result = new HashMap();
		result.put("paymentID", payId);
		return JSON.toJSONString(result);
	}

    /**
	 * paypal订单执行
	 * @return
	 */
    @RequestMapping(value = "/paypalExecute")
	@ResponseBody
	public String paypalExecute(HttpServletRequest request, HttpServletResponse response) {
		String payId = request.getParameter("paymentID");
		String payerId = request.getParameter("payerID");
		APIContext apiContext = new APIContext(clientId, clientSecret, "sandbox");
		PaymentExecution paymentExecution = new PaymentExecution();
		paymentExecution.setPayerId(payerId);//付款人
		
		Payment pymnt = new Payment();
		pymnt.setId(payId);
		String result = "failed";
		try {
			Payment executedPayment = pymnt.execute(apiContext, paymentExecution);
			if("approved".equals(executedPayment.getState())){
				result = "success";
			}
		} catch (PayPalRESTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map resultM = new HashMap();
		resultM.put("result", result);
		return JSON.toJSONString(resultM);
	}

The above is the logic of PayPal to complete the payment. These two interfaces should be supplemented with the logic code of their own system, which is directly omitted.

It’s done here. The quick integration of PayPal. If you want your payment security, you must also consider the data consistency problem and the rollback of payment failure. This is the logic of the free payment system. It has nothing to do with embedding PayPal, not here. talk more

The above is the personal embedding process, please correct me if I am wrong

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324401717&siteId=291194637