为PayPal添加定时任务
This commit is contained in:
@@ -1,159 +0,0 @@
|
||||
package com.ai.da.service.impl;
|
||||
|
||||
import com.ai.da.common.config.PayPalClient;
|
||||
import com.ai.da.common.constant.PayPalCheckoutConstant;
|
||||
import com.ai.da.common.utils.paypalRequest.WebhookVerifyRequest;
|
||||
import com.ai.da.service.CallBackService;
|
||||
import com.ai.da.service.PayPalCheckoutService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.paypal.api.payments.Event;
|
||||
import com.paypal.base.Constants;
|
||||
import com.paypal.base.SDKUtil;
|
||||
import com.paypal.base.rest.APIContext;
|
||||
import com.paypal.base.rest.PayPalRESTException;
|
||||
import com.paypal.http.HttpResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SignatureException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.ai.da.common.constant.PayPalCheckoutConstant.MODE;
|
||||
|
||||
// #Validate Webhook Sample
|
||||
//
|
||||
// This sample code demonstrates how to validate a webhook received on your
|
||||
// web server. This sample assumes that you use the java servlet, which returns
|
||||
// the HttpServletRequest object. However, you can modify this code to
|
||||
// your specific case.
|
||||
//
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CallBackServiceImpl implements CallBackService {
|
||||
|
||||
@Value("${paypal.client-id}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${paypal.client-secret}")
|
||||
private String clientSecret;
|
||||
|
||||
@Resource
|
||||
private PayPalClient payPalClient;
|
||||
|
||||
@Resource
|
||||
private PayPalCheckoutService payPalCheckoutService;
|
||||
|
||||
@Override
|
||||
public Boolean doGet(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws ServletException, IOException {
|
||||
return doPost(req, resp);
|
||||
}
|
||||
|
||||
// ##Validate Webhook
|
||||
protected Boolean doPost(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String body = getBody(req);
|
||||
Map webhookEvent = new ObjectMapper().readValue(body, Map.class);
|
||||
|
||||
HashMap<String, Object> webhookRequest = new HashMap<>();
|
||||
webhookRequest.put("auth_algo",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-AUTH-ALGO"));
|
||||
webhookRequest.put("cert_url",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-CERT-URL"));
|
||||
webhookRequest.put("transmission_id",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-ID"));
|
||||
webhookRequest.put("transmission_sig",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-SIG"));
|
||||
webhookRequest.put("transmission_time",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-TIME"));
|
||||
webhookRequest.put("webhook_id",PayPalCheckoutConstant.WEBHOOK_ID);
|
||||
webhookRequest.put("webhook_event",webhookEvent);
|
||||
|
||||
WebhookVerifyRequest webhookVerifyRequest = new WebhookVerifyRequest();
|
||||
webhookVerifyRequest.authorization(payPalCheckoutService.getOAuth());
|
||||
webhookVerifyRequest.requestBody(webhookRequest);
|
||||
// 验签
|
||||
HttpResponse<HashMap> verified = payPalClient.client(MODE, clientId, clientSecret).execute(webhookVerifyRequest);
|
||||
boolean verifyResult = verified.result().get("verification_status").toString().equals("SUCCESS");
|
||||
if (verifyResult){
|
||||
// ### Api Context
|
||||
APIContext apiContext = new APIContext(clientId, clientSecret, PayPalCheckoutConstant.MODE);
|
||||
|
||||
// Set the webhookId that you received when you created this webhook.
|
||||
apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, PayPalCheckoutConstant.WEBHOOK_ID);
|
||||
Boolean result = Event.validateReceivedEvent(apiContext, getHeadersInfo(
|
||||
req), body);
|
||||
log.info("Webhook Validated: " + result);
|
||||
|
||||
if (result){
|
||||
// 处理订单数据
|
||||
LinkedHashMap<String,LinkedHashMap<String,String>> webhookEventMap = (LinkedHashMap<String,LinkedHashMap<String,String>>) webhookEvent;
|
||||
String orderId = webhookEventMap.get("resource").get("id");
|
||||
payPalCheckoutService.processOrder(orderId);
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
}
|
||||
} catch (PayPalRESTException | InvalidKeyException | NoSuchAlgorithmException | SignatureException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
// Simple helper method to help you extract the headers from HttpServletRequest object.
|
||||
private static Map<String, String> getHeadersInfo(HttpServletRequest request) {
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
@SuppressWarnings("rawtypes")
|
||||
Enumeration headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = (String) headerNames.nextElement();
|
||||
String value = request.getHeader(key);
|
||||
map.put(key, value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// Simple helper method to fetch request data as a string from HttpServletRequest object.
|
||||
private static String getBody(HttpServletRequest request) throws IOException {
|
||||
String body;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
InputStream inputStream = request.getInputStream();
|
||||
if (inputStream != null) {
|
||||
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
char[] charBuffer = new char[128];
|
||||
int bytesRead = -1;
|
||||
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
|
||||
stringBuilder.append(charBuffer, 0, bytesRead);
|
||||
}
|
||||
} else {
|
||||
stringBuilder.append("");
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
throw ex;
|
||||
} finally {
|
||||
if (bufferedReader != null) {
|
||||
try {
|
||||
bufferedReader.close();
|
||||
} catch (IOException ex) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
body = stringBuilder.toString();
|
||||
log.info("回调参数 ===> {}", body);
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.ai.da.service.impl;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import com.ai.da.common.config.PayPalClient;
|
||||
import com.ai.da.common.config.exception.BusinessException;
|
||||
import com.ai.da.common.constant.PayPalCheckoutConstant;
|
||||
import com.ai.da.common.enums.*;
|
||||
import com.ai.da.common.utils.RedisUtil;
|
||||
import com.ai.da.common.utils.paypalRequest.AuthenticationRequest;
|
||||
@@ -27,7 +26,6 @@ import com.paypal.payments.CapturesRefundRequest;
|
||||
import com.paypal.payments.RefundRequest;
|
||||
import com.paypal.payments.RefundsGetRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -329,7 +327,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
* @return
|
||||
* @throws SerializeException
|
||||
*/
|
||||
public String queryOrder(String orderNo) throws SerializeException {
|
||||
public Order queryOrder(String orderNo) throws SerializeException {
|
||||
OrdersGetRequest request = new OrdersGetRequest(orderNo);
|
||||
|
||||
HttpResponse<Order> response = null;
|
||||
@@ -337,33 +335,31 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
response = payPalClient.client(mode, clientId, clientSecret).execute(request);
|
||||
} catch (Exception e) {
|
||||
log.error("paypal订单查询失败,失败原因 ===> {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
System.out.println("Status Code: " + response.statusCode());
|
||||
System.out.println("Status: " + response.result().status());
|
||||
System.out.println("Order id: " + response.result().id());
|
||||
log.debug("Status Code: " + response.statusCode() + "\tStatus: " + response.result().status() + "\tOrder id: " + response.result().id());
|
||||
if (response.result().purchaseUnits().get(0).payments() != null) {
|
||||
List<Capture> captures = response.result().purchaseUnits().get(0).payments().captures();
|
||||
if (captures != null) {
|
||||
for (Capture capture : captures) {
|
||||
System.out.println("\t订单编号= " + capture.invoiceId() + "\tCapture Id= " + capture.id() + "\tCapture status= " + capture.status() + "\tCapture amount= " + capture.amount().currencyCode() + ":" + capture.amount().value());
|
||||
log.debug("\t订单编号= " + capture.invoiceId() + "\tCapture Id= " + capture.id() + "\tCapture status= " + capture.status() + "\tCapture amount= " + capture.amount().currencyCode() + ":" + capture.amount().value());
|
||||
}
|
||||
}
|
||||
List<Refund> refunds = response.result().purchaseUnits().get(0).payments().refunds();
|
||||
if (refunds != null) {
|
||||
for (Refund refund : refunds) {
|
||||
System.out.println("\t售后编号= " + refund.invoiceId() + "\tRefund Id= " + refund.id() + "\tRefund status= " + refund.status() + "\tRefund amount= " + refund.amount().currencyCode() + ":" + refund.amount().value());
|
||||
log.debug("\t售后编号= " + refund.invoiceId() + "\tRefund Id= " + refund.id() + "\tRefund status= " + refund.status() + "\tRefund amount= " + refund.amount().currencyCode() + ":" + refund.amount().value());
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("Links: ");
|
||||
for (com.paypal.orders.LinkDescription link : response.result().links()) {
|
||||
System.out.println("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
|
||||
log.debug("Links: \t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
|
||||
}
|
||||
|
||||
System.out.println("Full response body:");
|
||||
|
||||
String json = new JSONObject(new Json().serialize(response.result())).toString(4);
|
||||
System.out.println(json);
|
||||
return null;
|
||||
log.info("Full response body: {}", json);
|
||||
return response.result();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -598,6 +594,49 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
creditsService.buyCredits(orderInfo.getAccountId(), orderInfo.getTotalFee() / Integer.parseInt(CreditsEventsEnum.PRICE.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkOrderStatus(String orderNo) throws SerializeException {
|
||||
|
||||
log.warn("根据订单号核实订单状态 ===> {}", orderNo);
|
||||
|
||||
Order result = this.queryOrder(orderNo);
|
||||
|
||||
// 订单未创建 | 订单异常 | 订单创建过但未支付
|
||||
if(result == null || PayPalOrderStatusEnum.CREATED.getStatus().equals(result.status())){
|
||||
log.warn("核实订单未创建 ===> {}", orderNo);
|
||||
//更新本地订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.TIMEOUT_CLOSED);
|
||||
return ;
|
||||
}
|
||||
|
||||
// 解析查单响应结果
|
||||
String tradeStatus = result.status();
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
|
||||
// 支付了,但还没完成
|
||||
if(PayPalOrderStatusEnum.APPROVED.getStatus().equals(tradeStatus)){
|
||||
log.warn("核实订单未支付 ===> {}", orderNo);
|
||||
// 更新商户端订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.ORDER_PROCESSING);
|
||||
}
|
||||
|
||||
if(PayPalOrderStatusEnum.COMPLETED.getStatus().equals(tradeStatus)){
|
||||
log.warn("核实订单已支付 ===> {}", orderNo);
|
||||
//如果订单已支付,则更新商户端订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
//并记录支付日志
|
||||
paymentInfoService.createPaymentInfoForPayPal(result);
|
||||
// 添加积分变更记录
|
||||
creditsService.insertToCreditsDetail(orderByOrderNo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--Paypal",
|
||||
CreditsEventsEnum.BUY_CREDITS.getValue(),
|
||||
"positive");
|
||||
// 更新积分
|
||||
creditsService.buyCredits(orderByOrderNo.getAccountId(),orderByOrderNo.getTotalFee() / Integer.parseInt(CreditsEventsEnum.PRICE.getValue()));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user