海外读书
This commit is contained in:
183
src/main/java/com/peanut/modules/pay/paypal/PaypalConfig.java
Normal file
183
src/main/java/com/peanut/modules/pay/paypal/PaypalConfig.java
Normal file
@@ -0,0 +1,183 @@
|
||||
package com.peanut.modules.pay.paypal;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class PaypalConfig {
|
||||
|
||||
//沙盒
|
||||
public static final String modeUrl = "https://api-m.sandbox.paypal.com";
|
||||
public static final String CLIENID ="Ab8SeEuhkLGp6Fts9V3Cti0UcXQhITRWZkiHDM3U1fDY9YrrRc5IOcYHPfV6qROhmh0hvgysqrfOCSUr";
|
||||
public static final String SECRET ="EF63FGWI9fd4q07Ndvc_h8P7jxiZcGOWn8Ul_y1_EKpluKJNFHOW8BP62Kf1wBDQ3XYIeqF8_kVrDF7C";
|
||||
public static final String WEBSCR ="https://www.sandbox.paypal.com/cgi-bin/webscr";//回调验证地址
|
||||
|
||||
//正式
|
||||
// public static final String modeUrl = "https://api-m.paypal.com";
|
||||
// public static final String CLIENID ="";
|
||||
// public static final String SECRET ="";
|
||||
// public static final String WEBSCR ="https://www.paypal.com/cgi-bin/webscr";
|
||||
|
||||
|
||||
public static final String accessTokenURL = "/v1/oauth2/token";
|
||||
public static final String createOrderURL = "/v2/checkout/orders";
|
||||
public static final String captureURL = "/v2/checkout/orders/%1s/capture";
|
||||
public static final String orderInfoURL = "/v2/checkout/orders/";
|
||||
public static final String refundURL = "/v2/payments/captures/%1s/refund";
|
||||
public static final String refundInfoURL = "/v2/payments/refunds/";
|
||||
|
||||
|
||||
|
||||
//回调验证
|
||||
public String receiveVerify(String verifyData) throws Exception{
|
||||
URL url = new URL(WEBSCR);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
||||
connection.setDoOutput(true);
|
||||
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
|
||||
writer.write(verifyData);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
connection.getOutputStream().close();
|
||||
InputStream responseStream = connection.getResponseCode() / 100 == 2
|
||||
? connection.getInputStream()
|
||||
: connection.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
System.out.println(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
//退款查询
|
||||
public JSONObject refundInfo(String refundId) throws Exception{
|
||||
URL url = new URL(modeUrl+refundInfoURL+refundId);
|
||||
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
|
||||
httpConn.setRequestMethod("GET");
|
||||
httpConn.setRequestProperty("Content-Type", "application/json");
|
||||
httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token"));
|
||||
|
||||
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
|
||||
? httpConn.getInputStream()
|
||||
: httpConn.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
System.out.println(response);
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
|
||||
//退款
|
||||
public JSONObject refund(String captureId) throws Exception{
|
||||
URL url = new URL(String.format(modeUrl+refundURL,captureId));
|
||||
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
|
||||
httpConn.setRequestMethod("POST");
|
||||
httpConn.setRequestProperty("Content-Type", "application/json");
|
||||
httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token"));
|
||||
httpConn.setRequestProperty("Prefer", "return=representation");
|
||||
httpConn.setDoOutput(true);
|
||||
|
||||
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
|
||||
? httpConn.getInputStream()
|
||||
: httpConn.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
System.out.println(response);
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
|
||||
//订单查询
|
||||
public JSONObject orderInfo(String paypalOrderId) throws Exception{
|
||||
URL url = new URL(modeUrl+orderInfoURL+paypalOrderId);
|
||||
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
|
||||
httpConn.setRequestMethod("GET");
|
||||
httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token"));
|
||||
|
||||
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
|
||||
? httpConn.getInputStream()
|
||||
: httpConn.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
System.out.println(response);
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
|
||||
//用户授权支付成功,进行扣款操作
|
||||
public JSONObject capture(String paypalOrderId) throws Exception{
|
||||
URL url = new URL(String.format(modeUrl+captureURL,paypalOrderId));
|
||||
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
|
||||
httpConn.setRequestMethod("POST");
|
||||
httpConn.setRequestProperty("Content-Type", "application/json");
|
||||
httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token"));
|
||||
|
||||
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
|
||||
? httpConn.getInputStream()
|
||||
: httpConn.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
|
||||
//下单
|
||||
public JSONObject createOrder(JSONObject jsonObject){
|
||||
try{
|
||||
URL u = new URL(modeUrl+createOrderURL);
|
||||
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token"));
|
||||
connection.setDoOutput(true);
|
||||
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
|
||||
writer.write(jsonObject.toString());
|
||||
writer.flush();
|
||||
writer.close();
|
||||
connection.getOutputStream().close();
|
||||
InputStream responseStream = connection.getResponseCode() / 100 == 2
|
||||
? connection.getInputStream()
|
||||
: connection.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
return JSONObject.parseObject(response);
|
||||
}catch (Exception e) {
|
||||
log.error(">>>>>>>>>>:PayPal创建订单网络连接失败 reason = {}", e.getMessage());
|
||||
e.printStackTrace();
|
||||
return JSONObject.parseObject("{'error':'PayPal创建订单网络连接失败,请联系管理员'}");
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject getAccessToken(){
|
||||
try {
|
||||
String credentials = CLIENID + ":" + SECRET;
|
||||
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
|
||||
URL url = new URL(modeUrl+accessTokenURL);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
|
||||
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
||||
connection.setDoOutput(true);
|
||||
String postParameters = "grant_type=client_credentials";
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
byte[] postParametersBytes = postParameters.getBytes();
|
||||
os.write(postParametersBytes);
|
||||
os.flush();
|
||||
}
|
||||
InputStream responseStream = connection.getResponseCode() / 100 == 2
|
||||
? connection.getInputStream()
|
||||
: connection.getErrorStream();
|
||||
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
|
||||
String response = s.hasNext() ? s.next() : "";
|
||||
return JSONObject.parseObject(response);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.peanut.modules.pay.paypal;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.peanut.common.utils.R;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* paypal支付
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/pay/paypal")
|
||||
@Slf4j
|
||||
public class PaypalController {
|
||||
//点击购买 ->去支付 ->跳转完成、取消页面
|
||||
// ->创建订单 ->(支付完成)确认付款,打款到商家账户 ->支付成功
|
||||
|
||||
@Autowired
|
||||
private PaypalConfig paypalConfig;
|
||||
|
||||
@RequestMapping("/getAccessToken")
|
||||
public R getAccessToken(){
|
||||
JSONObject res = paypalConfig.getAccessToken();
|
||||
return R.ok().put("res",res);
|
||||
}
|
||||
|
||||
@RequestMapping("/createOrder")
|
||||
public R createOrder(@RequestBody Map<String,Object> params){
|
||||
JSONArray purchase_units = new JSONArray();
|
||||
JSONObject purchaseUnit = new JSONObject();
|
||||
JSONObject amount = new JSONObject();
|
||||
amount.put("currency_code", "USD");//美元
|
||||
amount.put("value", params.get("amount"));// 金额
|
||||
purchaseUnit.put("custom_id",params.get("orderSn"));
|
||||
purchaseUnit.put("invoice_id",params.get("orderSn"));
|
||||
purchaseUnit.put("amount",amount);
|
||||
purchaseUnit.put("description", params.get("description"));
|
||||
purchase_units.add(purchaseUnit);
|
||||
//取消地址、返回地址设置
|
||||
JSONObject applicationContext = new JSONObject();
|
||||
applicationContext.put("user_action", "PAY_NOW");//付款按钮显示立即付款
|
||||
applicationContext.put("shipping_preference", "NO_SHIPPING");//从 PayPal 网站编辑送货地址。推荐用于数字商品。
|
||||
applicationContext.put("return_url", params.get("returnUrl"));//客户批准付款后重定向到客户的 URL
|
||||
applicationContext.put("cancel_url", params.get("cancelUrl"));//客户取消付款后,客户被重定向的 URL
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
// 用户付款了,商户立即收款
|
||||
jsonObject.put("intent","CAPTURE");
|
||||
jsonObject.put("purchase_units",purchase_units);
|
||||
jsonObject.put("application_context", applicationContext);
|
||||
JSONObject res = paypalConfig.createOrder(jsonObject);
|
||||
if (res.containsKey("links")&&res.containsKey("status")){
|
||||
if ("CREATED".equals(res.get("status").toString())){
|
||||
List<JSONObject> links = (List)res.get("links");
|
||||
for (JSONObject o:links) {
|
||||
if ("approve".equals(o.get("rel").toString())){
|
||||
return R.ok().put("res",o.get("href").toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return R.error(res.get("error").toString());
|
||||
}
|
||||
|
||||
@RequestMapping("/orderInfo")
|
||||
public R orderInfo(@RequestBody Map<String,Object> params) throws Exception{
|
||||
JSONObject res = paypalConfig.orderInfo(params.get("paypalId").toString());
|
||||
return R.ok().put("res",res);
|
||||
}
|
||||
|
||||
@RequestMapping("/capture")
|
||||
public R capture(@RequestBody Map<String,Object> params) throws Exception{
|
||||
JSONObject res = paypalConfig.capture(params.get("paypalId").toString());
|
||||
return R.ok().put("res",res);
|
||||
}
|
||||
|
||||
@RequestMapping("/refund")
|
||||
public R refund(@RequestBody Map<String,Object> params) throws Exception{
|
||||
JSONObject res = paypalConfig.refund(params.get("captureId").toString());
|
||||
return R.ok().put("res",res);
|
||||
}
|
||||
|
||||
@RequestMapping("/refundInfo")
|
||||
public R refundInfo(@RequestBody Map<String,Object> params) throws Exception{
|
||||
JSONObject res = paypalConfig.refundInfo(params.get("refundId").toString());
|
||||
return R.ok().put("res",res);
|
||||
}
|
||||
|
||||
@RequestMapping("/receivePaypalStatus")
|
||||
public void receivePaypalStatus(HttpServletRequest request, HttpServletResponse response) throws Exception{
|
||||
//获取paypal请求参数,并拼接验证参数
|
||||
Enumeration<String> en = request.getParameterNames();
|
||||
String str = "cmd=_notify-validate";
|
||||
while (en.hasMoreElements()) {
|
||||
String paramName = en.nextElement();
|
||||
String paramValue = request.getParameter(paramName);
|
||||
str = str + "&" + paramName + "=" + paramValue;
|
||||
}
|
||||
System.out.println(str);
|
||||
//发送给papal,确认回调信息的安全性
|
||||
String res = paypalConfig.receiveVerify(str);
|
||||
if ("VERIFIED".equals(res)){
|
||||
// 交易状态 Completed 代表交易成功
|
||||
String paymentStatus = request.getParameter("payment_status");
|
||||
// 交易时间
|
||||
String paymentDate = request.getParameter("payment_date");
|
||||
// 付款人email
|
||||
String payerEmail = request.getParameter("payer_email");
|
||||
// 付款人id
|
||||
String payerId = request.getParameter("payer_id");
|
||||
// 交易金额
|
||||
String mcGross = request.getParameter("mc_gross");
|
||||
// 手续费
|
||||
String paymentFee = request.getParameter("payment_fee");
|
||||
// 自定义字段,存放订单号
|
||||
String custom = request.getParameter("custom");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/receiveVerify")
|
||||
public R receiveVerify(@RequestBody Map<String,Object> params) throws Exception{
|
||||
String res = params.get("verifyData").toString();
|
||||
Map<String,Object> map = new HashMap<>();
|
||||
String[] items = res.split("&");
|
||||
for (String item : items) {
|
||||
String[] keyValues = item.split("=");
|
||||
if (keyValues.length>1){
|
||||
map.put(keyValues[0],keyValues[1]);
|
||||
}else {
|
||||
map.put(keyValues[0],"");
|
||||
}
|
||||
}
|
||||
|
||||
return R.ok().put("res",map);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user