我正在使用servlet生成HTML页面,这些页面旨在使用新的REST api执行PayPal付款。我还无法生成状态为已批准或已创建的付款。我在github页面上尝试过PaymentWithPayPalServlet.java示例的变体,并且我在下面列出了最接近的变体。我最不清楚哪个对象应该获得已批准的更新状态'或者'已完成'什么时候。
虽然我已经包含了下面的完整代码,但这是我的想法的快速细分。也许有人可以在我出错的地方纠正我......
我创建了一个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页面,其中包含paymentID,并且可能还有一个附加到URL的授权令牌。使用这两件事,我希望通过某种类型的静态函数调用从payPal服务器检索一个支付对象,如:
String authToken=req.getParameter("token");
String paymentID=req.getParameter("paymentID");
Payment approvedPayment=Payment.getPaymentObject(authToken,paymentID);
但是,该URL没有附加任何paymentID。相反,有一个payerID。此外,我尝试从payPal服务器检索支付对象的状态为“已批准”#39;或者'已完成'失败了。基本上,我尝试了下面的变化无济于事:
String authToken=req.getParameter("token");
String paymentID=req.getParameter("payerID");
Payment approvedPayment=Payment.get(authToken,payerID);
如果有人可以向我提示我的推理出错的地方,那绝对是摇滚乐。谢谢!这是我的主servlet页面的完整代码。注意,returnURL会将您带回到同一页面,在该页面中,它会从payPal中找到包含在HTTP请求中的payerID,并正确输入' if'主if-else语句的块,它生成一些完全无用的基本输出。另请注意,我已将一些基本函数调用(如检索访问令牌和上下文)外包给其他类,如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);
}
}
在回复我下面的第一位评论者Yozha Karlov时,我添加了以下内容:
嗯,我想我对此有几点反应。首先,谢谢。其次,我想也许我对我的问题不够清楚。我并不知道如何检索旧的Payment对象,名为&#39; createdPayment&#39;以上。在我上面复制的完整代码中,我使用了您引用的完全相同的guid代码。这样做的一个问题是它不会做任何事情,只是将createdPayment对象的ID复制到一个新的空白Payment对象中。新对象的状态仍为空白,其所有其他属性也是如此。它是一个带有ID的空白对象,就是这样。几乎一文不值,所以我要么缺少一些东西,要么示例servlet是完全错误的。实际上,我的初始方法是创建一个静态类,其中包含静态映射,以将sessionID映射到HttpSession对象。我将为用户的浏览器会话生成一个sessionID,并将该sessID附加到paymentURL中的cancelURL和returnURL以及payment.create()方法的redirectURL中。然后,我确保将相关的Payment对象附加到用户的HttpSession对象,以便以后在returnURL servlet中进行检索。
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);
}
}
然后,当payPal页面将我返回到我之前的returnURL页面时,我会调用以下相关代码片段:
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);
已检索到具有所有相同属性和所有内容的旧付款对象。这似乎比仅仅将旧的支付ID复制到其他空白的支付对象更有用。但是,旧的“createdPayment”仍然处于“已创建”状态,而非“已批准”或“已完成”状态。我不知道如何从创建上面概述的对象到执行相同的Payment对象。事实上,我甚至不了解使用method ='paypal'的付款是否应该使用相同的付款对象创建和执行。正如我在原帖中所描述的那样,对我来说这应该是这样的。我创建了一个付款对象,payPal发回一个approval_URL等,让我将用户重定向到批准。这会将用户从我的Web应用程序中移出并进入payPal服务器。由于payPal无法修改我的本地'createdPayment'变量,因此payPal无法更改其状态。此外,似乎我需要一个状态为“已批准”的付款对象才能执行付款。因此,我得出结论,payPal必须向我发送一个新的Payment对象,其中包含许多与我的'createdPayment'对象相同的信息,但是具有已更新的已批准状态,并且可能是一个特殊的令牌/密码,表明已批准的状态以防止某人只是将一堆付款变成了批准的状态,这很容易做到。我看到我正在获得一个令牌,正如预期的那样,但我没有像我预期的那样得到一个paymentID。我收到了付款人ID。有没有办法将返回的令牌和payerID转换为状态为“已批准”的新付款对象,或者我只是完全遗漏了什么?
答案 0 :(得分:2)
你是对的,在从PayPal网站页面重定向后,'payerId'将被追加为请求参数,而不是支付ID。但是你也需要支付ID来执行它。以下是来自payPal interactive tool的代码。
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);
因此,棘手的部分是如何在请求之间保留支付ID,因为HTTP并不像我们所知的那样保持任何状态。您可以在所引用的示例中看到它是如何实现的:
所以他们生成了uuid:
String guid = UUID.randomUUID().toString().replaceAll("-", "");
在重定向网址中添加guid参数:
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/paymentwithpaypal?guid=" + guid);
并将此guid参数与已创建付款的ID相关联:
map.put(guid, createdPayment.getId());
以便稍后使用
payment.setId(map.get(req.getParameter("guid")));
希望这会有所帮助
答案 1 :(得分:0)
根据paypal开发人员门户网站,返回的对象如下所示:
{
"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"
}]}
因此,您可能会看到字段状态&#34;已创建&#34;。您还有字段“创建时间”。
我希望它有所帮助。