做全球性的支付,選用paypal!為什么選擇paypal? 因為paypal是目前全球最大的在線支付工具,就像國內的支付寶一樣,是一個基於買賣雙方的第三方平台。買家只需知道你的paypal賬號,即可在線直接把錢匯入你的賬戶,即時到賬,簡單方便快捷。
在集成paypal支付接口之前,首先要有一系列的准備,開發者賬號啊、sdk、測試環境等等先要有,然后再碼代碼。集成的步驟如下:
一、環境准備
-
注冊paypal賬號
-
注冊paypal開發者賬號
-
創建兩個測試用戶
-
創建應用,生成用於測試的clientID 和 密鑰
二、代碼集成
-
springboot環境
-
pom引進paypal-sdk的jar包
-
碼代碼
-
測試
-
后言
現在開始
- 注冊paypal賬號
(1)在瀏覽器輸入“https://www.paypal.com” 跳轉到如下界面,點擊右上角的注冊
(2)選擇,”創建商家用戶”,根據要求填寫信息,一分鍾的事,注冊完得去郵箱激活
- 注冊paypal開發者賬號
(1)在瀏覽器輸入“https://developer.paypal.com”,點擊右上角的“Log into Dashboard”,用上一步創建好的賬號登錄
- 創建兩個測試用戶
(1)登錄成功后,在左邊的導航欄中點擊 Sandbox 下的 Accounts
(2)進入Acccouts界面后,可以看到系統有兩個已經生成好的測試賬號,但是我們不要用系統給的測試賬號,很卡的,自己創建兩個
(3)點擊右上角的“Create Account”,創建測試用戶
<1> 先創建一個“ PERSONAL”類型的用戶,國家一定要選“China”,賬戶余額自己填寫
<2> 接着創建一個“BUSINESS”類型的用戶,國家一定要選“China”,賬戶余額自己填寫
<3>創建好之后可以點擊測試賬號下的”Profile“,可以查看信息,如果沒加載出來,刷新
<4>用測試賬號登錄測試網站查看,注意!這跟paypal官網不同!不是同一個地址,在瀏覽器輸入:https://www.sandbox.paypal.com 在這里登陸測試賬戶
- 創建應用,生成用於測試的clientID 和 密鑰
(1)點擊左邊導航欄Dashboard下的My Apps & Credentials,創建一個Live賬號,下圖是我已經創建好的
(2)然后再到下邊創建App
這是我創建好的“Test”App
(3)點擊剛剛創建好的App“Test”,注意看到”ClientID“ 和”Secret“(Secret如果沒顯示,點擊下面的show就會看到,點擊后show變為hide)
- springboot環境搭建
(1)新建幾個包,和目錄,項目結構如下
- pom引進paypal-sdk的jar包
(1)pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.masasdani</groupId> <artifactId>paypal-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>paypal-springboot</name> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>http://repo.spring.io/libs-milestone</url> </repository> <repository> <id>jcenter-snapshots</id> <name>jcenter</name> <url>https://jcenter.bintray.com/</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>http://repo.spring.io/libs-milestone</url> </pluginRepository> </pluginRepositories> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.paypal.sdk</groupId> <artifactId>rest-api-sdk</artifactId> <version>1.4.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>
- 碼代碼
(1)Application.java
package com.masasdani.paypal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @EnableAutoConfiguration @Configuration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
(2)PaypalConfig.java
package com.masasdani.paypal.config; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.paypal.base.rest.APIContext; import com.paypal.base.rest.OAuthTokenCredential; import com.paypal.base.rest.PayPalRESTException; @Configuration public class PaypalConfig { @Value("${paypal.client.app}") private String clientId; @Value("${paypal.client.secret}") private String clientSecret; @Value("${paypal.mode}") private String mode; @Bean public Map<String, String> paypalSdkConfig(){ Map<String, String> sdkConfig = new HashMap<>(); sdkConfig.put("mode", mode); return sdkConfig; } @Bean public OAuthTokenCredential authTokenCredential(){ return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig()); } @Bean public APIContext apiContext() throws PayPalRESTException{ APIContext apiContext = new APIContext(authTokenCredential().getAccessToken()); apiContext.setConfigurationMap(paypalSdkConfig()); return apiContext; } }
(3)PaypalPaymentIntent.java
package com.masasdani.paypal.config; public enum PaypalPaymentIntent { sale, authorize, order }
(4)PaypalPaymentMethod.java
package com.masasdani.paypal.config; public enum PaypalPaymentMethod { credit_card, paypal }
(5)PaymentController.java
package com.masasdani.paypal.controller; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.masasdani.paypal.config.PaypalPaymentIntent; import com.masasdani.paypal.config.PaypalPaymentMethod; import com.masasdani.paypal.service.PaypalService; import com.masasdani.paypal.util.URLUtils; import com.paypal.api.payments.Links; import com.paypal.api.payments.Payment; import com.paypal.base.rest.PayPalRESTException; @Controller @RequestMapping("/") public class PaymentController { public static final String PAYPAL_SUCCESS_URL = "pay/success"; public static final String PAYPAL_CANCEL_URL = "pay/cancel"; private Logger log = LoggerFactory.getLogger(getClass()); @Autowired private PaypalService paypalService; @RequestMapping(method = RequestMethod.GET) public String index(){ return "index"; } @RequestMapping(method = RequestMethod.POST, value = "pay") public String pay(HttpServletRequest request){ String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL; String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL; try { Payment payment = paypalService.createPayment( 500.00, "USD", PaypalPaymentMethod.paypal, PaypalPaymentIntent.sale, "payment description", cancelUrl, successUrl); for(Links links : payment.getLinks()){ if(links.getRel().equals("approval_url")){ return "redirect:" + links.getHref(); } } } catch (PayPalRESTException e) { log.error(e.getMessage()); } return "redirect:/"; } @RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL) public String cancelPay(){ return "cancel"; } @RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL) public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){ try { Payment payment = paypalService.executePayment(paymentId, payerId); if(payment.getState().equals("approved")){ return "success"; } } catch (PayPalRESTException e) { log.error(e.getMessage()); } return "redirect:/"; } }
(6)PaypalService.java
package com.masasdani.paypal.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.masasdani.paypal.config.PaypalPaymentIntent; import com.masasdani.paypal.config.PaypalPaymentMethod; import com.paypal.api.payments.Amount; import com.paypal.api.payments.Payer; import com.paypal.api.payments.Payment; import com.paypal.api.payments.PaymentExecution; import com.paypal.api.payments.RedirectUrls; import com.paypal.api.payments.Transaction; import com.paypal.base.rest.APIContext; import com.paypal.base.rest.PayPalRESTException; @Service public class PaypalService { @Autowired private APIContext apiContext; public Payment createPayment( Double total, String currency, PaypalPaymentMethod method, PaypalPaymentIntent intent, String description, String cancelUrl, String successUrl) throws PayPalRESTException{ Amount amount = new Amount(); amount.setCurrency(currency); amount.setTotal(String.format("%.2f", total)); Transaction transaction = new Transaction(); transaction.setDescription(description); transaction.setAmount(amount); List<Transaction> transactions = new ArrayList<>(); transactions.add(transaction); Payer payer = new Payer(); payer.setPaymentMethod(method.toString()); Payment payment = new Payment(); payment.setIntent(intent.toString()); payment.setPayer(payer); payment.setTransactions(transactions); RedirectUrls redirectUrls = new RedirectUrls(); redirectUrls.setCancelUrl(cancelUrl); redirectUrls.setReturnUrl(successUrl); payment.setRedirectUrls(redirectUrls); return payment.create(apiContext); } public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{ Payment payment = new Payment(); payment.setId(paymentId); PaymentExecution paymentExecute = new PaymentExecution(); paymentExecute.setPayerId(payerId); return payment.execute(apiContext, paymentExecute); } }
(7)URLUtils.java
package com.masasdani.paypal.util; import javax.servlet.http.HttpServletRequest; public class URLUtils { public static String getBaseURl(HttpServletRequest request) { String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); StringBuffer url = new StringBuffer(); url.append(scheme).append("://").append(serverName); if ((serverPort != 80) && (serverPort != 443)) { url.append(":").append(serverPort); } url.append(contextPath); if(url.toString().endsWith("/")){ url.append("/"); } return url.toString(); } }
(8)cancel.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1>Canceled by user</h1> </body> </html>
(9)index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <form method="post" th:action="@{/pay}"> <button type="submit"><img src="images/paypal.jpg" width="100px;" height="30px;"/></button> </form> </body> </html>
(10)success.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1>Payment Success</h1> </body> </html>
(11)最重要的!application.properties,paypal.client.app是App的CilentID, paypal.client.secret是Secret
server.port: 8088 spring.thymeleaf.cache=false paypal.mode=sandbox paypal.client.app=AeVqmY_pxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxKYniPwzfL1jGR paypal.client.secret=ELibZhExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxUsWOA
- 測試
(1)啟動項目
(2)在瀏覽器輸入localhost:8088
(3)點擊paypal后,會跳到paypal的登錄界面,登錄測試賬號(PRESONAL)后點擊繼續即可扣費,扣500$(具體數額可在controller中自定義)
Payment payment = paypalService.createPayment( 500.00, "USD", PaypalPaymentMethod.paypal, PaypalPaymentIntent.sale, "payment description", cancelUrl, successUrl);
(4)到https://www.sandbox.paypal.com 登錄測試賬號看看余額有沒有變化
http://blog.csdn.net/change_on/article/details/73881791