Jakarta ee PayPal REST API未执行付款。无法将付款对象的状态从';创建';至';批准';或';已完成';
我正在使用servlet生成HTML页面,这些页面旨在使用新的RESTAPI执行PayPal支付。我还无法生成状态为“已批准”或“已创建”的付款。我尝试了github页面上PaymentWithPayPalServlet.java示例的变体,并在下面列出了最接近的变体。我最不清楚哪个对象应该接收更新状态“已批准”或“已完成”以及何时接收 虽然我在下面包含了完整的代码,但这里是我的想法的一个快速分解。也许有人能纠正我的错误 我创建了一个具有所有适当属性集的付款对象Jakarta ee PayPal REST API未执行付款。无法将付款对象的状态从';创建';至';批准';或';已完成';,jakarta-ee,paypal,paypal-rest-sdk,Jakarta Ee,Paypal,Paypal Rest Sdk,我正在使用servlet生成HTML页面,这些页面旨在使用新的RESTAPI执行PayPal支付。我还无法生成状态为“已批准”或“已创建”的付款。我尝试了github页面上PaymentWithPayPalServlet.java示例的变体,并在下面列出了最接近的变体。我最不清楚哪个对象应该接收更新状态“已批准”或“已完成”以及何时接收 虽然我在下面包含了完整的代码,但这里是我的想法的一个快速分解。也许有人能纠正我的错误 我创建了一个具有所有适当属性集的付款对象 Payment payment
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
payment.setRedirectUrls(redirectUrls);
Payment createdPayment = payment.create(apiContext);
现在,createdPayment对象的状态为“已创建”。在我的代码结束时,我将用户重定向到payPal页面,我假设payPal会在执行之前批准付款。注意,这与示例文件有偏差,但我不理解为什么这不起作用
if (link.getRel().equalsIgnoreCase("approval_url"))
{
req.setAttribute("redirectURL", link.getHref());
resp.sendRedirect(link.getHref());
}
由于payPal无法通过HTTP协议更改我的局部变量createdPayment的状态,因此我希望payPal页面重定向回我的returnURL页面,并在URL后面附加paymentID和可能的授权令牌。使用这两种方法,我希望通过某种类型的静态函数调用从payPal服务器检索支付对象,如:
String authToken=req.getParameter("token");
String paymentID=req.getParameter("paymentID");
Payment approvedPayment=Payment.getPaymentObject(authToken,paymentID);
但是,URL没有附加任何paymentID。相反,这里有一个payerID。此外,我从payPal服务器检索状态为“已批准”或“已完成”的支付对象的所有尝试均失败。基本上,我尝试了以下方面的变化,但没有成功:
String authToken=req.getParameter("token");
String paymentID=req.getParameter("payerID");
Payment approvedPayment=Payment.get(authToken,payerID);
如果有人能告诉我我的推理哪里出了问题,那绝对会让人震惊。谢谢下面是我的servlet主页的完整代码。注意,returnURL会将您带回同一页面,在该页面中,它会找到payPal的HTTP请求中包含的PayRid,并正确地输入主if-else语句的“if”块,这会生成一些完全没有帮助的基本输出。还要注意,我已经将一些基本函数调用(如检索访问令牌和上下文)外包给了其他类,如AccessToken类
public class PaymentInfoServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
// private static final Logger LOGGER = Logger
// .getLogger(PaymentWithPayPalServlet.class);
Map<String, String> map = new HashMap<String, String>();
public void init(ServletConfig servletConfig) throws ServletException {
// ##Load Configuration
// Load SDK configuration for
// the resource. This intialization code can be
// done as Init Servlet.
InputStream is = PaymentInfoServlet2.class
.getResourceAsStream("/sdk_config.properties");
try {
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
// LOGGER.fatal(e.getMessage());
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing to create a Payment using PayPal
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ###AccessToken
// Retrieve the access token from
// OAuthTokenCredential by passing in
// ClientID and ClientSecret
APIContext apiContext = null;
String accessToken = null;
try {
AccessToken access=new AccessToken(PublicUtils.getUser(),PublicUtils.getPass(),req,resp);
accessToken = access.getToken();
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
apiContext = access.getContext();
// Use this variant if you want to pass in a request id
// that is meaningful in your application, ideally
// a order id.
/*
* String requestId = Long.toString(System.nanoTime(); APIContext
* apiContext = new APIContext(accessToken, requestId ));
*/
} catch (Exception e) {
req.setAttribute("error", e.getMessage());
}
if (req.getParameter("PayerID") != null) {
Payment payment = new Payment();
if (req.getParameter("guid") != null) {
payment.setId(map.get(req.getParameter("guid")));
}
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(req.getParameter("PayerID"));
try {
payment.execute(apiContext, paymentExecution);
req.setAttribute("response", Payment.getLastResponse());
} catch (PayPalRESTException e) {
req.setAttribute("error", e.getMessage());
}
PrintWriter out=resp.getWriter();
out.println("This is the returnURL page.");
out.println("paymentID="+payment.getId());
out.println("pamentState="+payment.getState());
out.println("executedPayerID="+paymentExecution.getPayerId());
// out.println("executedTransaction: "+paymentExecution.getTransactions().get(0).toString());
} else {
// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("1");
details.setSubtotal("5");
details.setTax("1");
// ###Amount
// Let's you specify a payment amount.
Amount amount = new Amount();
amount.setCurrency("USD");
// Total must be equal to sum of shipping, tax and subtotal.
amount.setTotal("7");
amount.setDetails(details);
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
// The Payment creation API requires a list of
// Transaction; add the created `Transaction`
// to a List
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
// ###Payer
// A resource representing a Payer that funds a payment
// Payment Method
// as 'paypal'
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
// ###Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
// ###Redirect URLs
RedirectUrls redirectUrls = new RedirectUrls();
String guid = UUID.randomUUID().toString().replaceAll("-", "");
redirectUrls.setCancelUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/CancelServlet?guid=" + guid);
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/PaymentInfoServlet2?guid=" + guid);
payment.setRedirectUrls(redirectUrls);
// Create a payment by posting to the APIService
// using a valid AccessToken
// The return object contains the status;
try {
Payment createdPayment = payment.create(apiContext);
// LOGGER.info("Created payment with id = "
// + createdPayment.getId() + " and status = "
// + createdPayment.getState());
// ###Payment Approval Url
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url")) {
req.setAttribute("redirectURL", link.getHref());
resp.sendRedirect(link.getHref());
}
}
req.setAttribute("response", Payment.getLastResponse());
map.put(guid, createdPayment.getId());
} catch (PayPalRESTException e) {
req.setAttribute("error", e.getMessage());
}
}
req.setAttribute("request", Payment.getLastRequest());
//req.getRequestDispatcher("response.jsp").forward(req, resp);
}
公共类PaymentInfoServlet2扩展了HttpServlet{
私有静态最终长serialVersionUID=1L;
//专用静态最终记录器=记录器
//.getLogger(PaymentWithPayPalServlet.class);
Map Map=newhashmap();
public void init(ServletConfig ServletConfig)抛出ServletException{
//##负载配置
//加载的SDK配置
//资源。此初始化代码可以是
//作为initservlet完成。
InputStream is=PaymentInfoServlet2.class
.getResourceAsStream(“/sdk_config.properties”);
试一试{
PayPalResource.initConfig(is);
}捕获(Paypalreste例外){
//LOGGER.fatal(如getMessage());
}
}
@凌驾
受保护的无效数据集(HttpServletRequest-req、HttpServletResponse-resp)
抛出ServletException、IOException{
doPost(请求、响应);
}
//##创建
//显示使用PayPal创建付款的示例
@凌驾
受保护的void doPost(HttpServletRequest-req、HttpServletResponse-resp)
抛出ServletException、IOException{
//####访问令牌
//从中检索访问令牌
//OAuthTokenCredential通过传入
//ClientID和ClientSecret
APIContext APIContext=null;
字符串accessToken=null;
试一试{
AccessToken access=新的AccessToken(PublicUtils.getUser(),PublicUtils.getPass(),req,resp);
accessToken=access.getToken();
//####Api上下文
//传入'ApiContext'对象以进行身份验证
//调用并发送唯一的请求id
//(这确保了幂等性)
//如果未显式传递请求id,则为请求id。
apiContext=access.getContext();
//如果要传入请求id,请使用此变量
//理想情况下,这在您的应用程序中是有意义的
//订单号。
/*
*字符串requestId=Long.toString(System.nanoTime();APIContext
*apiContext=新的apiContext(accessToken,requestId));
*/
}捕获(例外e){
setAttribute(“错误”,例如getMessage());
}
if(req.getParameter(“PayerID”)!=null){
付款=新付款();
if(req.getParameter(“guid”)!=null){
payment.setId(map.get(req.getParameter(“guid”));
}
PaymentExecution PaymentExecution=新的PaymentExecution();
paymentExecution.setPayerId(请求getParameter(“PayerID”);
试一试{
payment.execute(apiContext,paymentexecute);
req.setAttribute(“response”,Payment.getLastResponse());
}捕获(Paypalreste例外){
setAttribute(“错误”,例如getMessage());
}
PrintWriter out=resp.getWriter();
println(“这是returnURL页面”);
out.println(“paymentID=“+payment.getId());
out.println(“pamentState=“+payment.getState());
out.println(“executedPayerID=“+paymentExecution.getPayerId());
//出局,普林
public class SessionStore {
public static Map<String, HttpSession> map = new HashMap<String,HttpSession>();
}
and in my main servlet, called PaymentInfoServlet2, here is the relevant code that i execute before the servlet ends and the user is re-directed to the payPal pages:
HttpSession sess=req.getSession();
String sessID=sess.getId();
SessionStore.map.put(sessID, sess);
// append sessID to redirectURLs - the URLs that the payPal pages return back to
approveURL=req.getScheme() + "://"+ req.getServerName() + ":" +req.getServerPort()+ req.getContextPath() +"/ApproveServlet?sessID=" +sess.getId();
cancelURL=req.getScheme() + "://"+ req.getServerName() + ":" + req.getServerPort()+ req.getContextPath() +"/CancelServlet?sessID=" +sess.getId();
redirectUrls.setCancelUrl(cancelURL);
redirectUrls.setReturnUrl(approveURL);
payment.setRedirectUrls(redirectUrls);
// create the payment on the payPal server
Payment createdPayment = payment.create(access.getContext());
//add created Payment object to HttpSession object.
ArrayList<Payment> createdPayments=new ArrayList<Payment>();
createdPayments.add(createdPayment);
sess.setAttribute("createdPayments", createdPayments);
// redirect to payPal pages
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext())
{
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url"))
{
url=link.getHref();
resp.sendRedirect(url);
}
}
String sessID=req.getParameter("sessID");
HttpSession sess=SessionStore.map.get(sessID);
ArrayList<Payment> cPay=(ArrayList<Payment>)sess.getAttribute("createdPayments");
Payment payment=(Payment)cPay.get(0);
String accessToken = "Bearer Jfdd4h4VrmvLeATBNPsGOpp7pMosTppiy.Jq6xpwQ6E";
APIContext apiContext = new APIContext(accessToken);
apiContext.setConfigurationMap(sdkConfig);
Payment payment = new Payment("PAY-4AL22602580048540KKPBSNY");
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId("BKJ78SZZ8KJYY");
payment.execute(apiContext, paymentExecute);
String guid = UUID.randomUUID().toString().replaceAll("-", "");
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/paymentwithpaypal?guid=" + guid);
map.put(guid, createdPayment.getId());
payment.setId(map.get(req.getParameter("guid")));
{
"id": "PAY-50299450TD463315FK4MDBAI",
"intent": "sale",
"state": "created",
"payer": {
"payment_method": "paypal"
},
"transactions": [
{
"amount": {
"total": "7.00",
"currency": "USD",
"details": {
"subtotal": "5.00",
"tax": "1.00",
"shipping": "1.00"
}
},
"description": "This is the payment transaction description.",
"item_list": {
"items": [
{
"name": "Ground Coffee 40 oz",
"price": "5.00",
"currency": "USD",
"quantity": 1
}
]
},
"related_resources": []
}],
"create_time": "2016-04-21T01:44:32Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-50299450TD463315FK4MDBAI",
"rel": "self",
"method": "GET"
},
{
"href": "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-27C19584EL875221E",
"rel": "approval_url",
"method": "REDIRECT"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-50299450TD463315FK4MDBAI/execute",
"rel": "execute",
"method": "POST"
}]}