-
Notifications
You must be signed in to change notification settings - Fork 238
/
PayPalApiController.cs
194 lines (170 loc) · 8.8 KB
/
PayPalApiController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Merchello.Core.Gateways.Payment;
using Merchello.Web.Workflow;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using Merchello.Core;
using Merchello.Core.Services;
using Merchello.Plugin.Payments.PayPal.Provider;
using System.Text;
namespace Merchello.Plugin.Payments.PayPal.Controllers
{
/// <summary>
/// The PayPal API controller.
/// </summary>
[PluginController("MerchelloPayPal")]
public class PayPalApiController : UmbracoApiController
{
/// <summary>
/// Merchello context
/// </summary>
private readonly IMerchelloContext _merchelloContext;
/// <summary>
/// The PayPal payment processor.
/// </summary>
private readonly PayPalPaymentProcessor _processor;
/// <summary>
/// Initializes a new instance of the <see cref="PayPalApiController"/> class.
/// </summary>
public PayPalApiController(): this(MerchelloContext.Current)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PayPalApiController"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
public PayPalApiController(IMerchelloContext merchelloContext)
{
if (merchelloContext == null) throw new ArgumentNullException("merchelloContext");
var providerKey = new Guid(Constants.PayPalPaymentGatewayProviderKey);
var provider = (PayPalPaymentGatewayProvider)merchelloContext.Gateways.Payment.GetProviderByKey(providerKey);
if (provider == null)
{
var ex = new NullReferenceException("The PayPalPaymentGatewayProvider could not be resolved. The provider must be activiated");
LogHelper.Error<PayPalApiController>("PayPalPaymentGatewayProvider not activated.", ex);
throw ex;
}
_merchelloContext = merchelloContext;
_processor = new PayPalPaymentProcessor(provider.ExtendedData.GetProcessorSettings());
}
/// <summary>
/// Authorize payment
/// </summary>
/// <param name="invoiceKey"></param>
/// <param name="paymentKey"></param>
/// <param name="token"></param>
/// <param name="payerId"></param>
/// <returns></returns>
/// <example>/umbraco/MerchelloPayPal/PayPalApi/SuccessPayment?InvoiceKey=3daeee31-da2c-41d0-a650-52bafaa16dc1&PaymentKey=562e3108-2c68-4f8e-8818-b5685e3df160&token=EC-0NN997417U7730318&PayerID=UBDNS4GA4TB7Y</example>
[HttpGet]
public HttpResponseMessage SuccessPayment(Guid invoiceKey, Guid paymentKey, string token, string payerId)
{
var invoice = _merchelloContext.Services.InvoiceService.GetByKey(invoiceKey);
var payment = _merchelloContext.Services.PaymentService.GetByKey(paymentKey);
if (invoice == null || payment == null || String.IsNullOrEmpty(token) || String.IsNullOrEmpty(payerId))
{
var ex = new NullReferenceException(string.Format("Invalid argument exception. Arguments: invoiceKey={0}, paymentKey={1}, token={2}, payerId={3}.", invoiceKey, paymentKey, token, payerId));
LogHelper.Error<PayPalApiController>("Payment is not authorized.", ex);
throw ex;
}
var providerKeyGuid = new Guid(Constants.PayPalPaymentGatewayProviderKey);
var paymentGatewayMethod = _merchelloContext.Gateways.Payment
.GetPaymentGatewayMethods()
.First(item => item.PaymentMethod.ProviderKey == providerKeyGuid);
//var paymentGatewayMethod = _merchelloContext.Gateways.Payment.GetPaymentGatewayMethodByKey(providerKeyGuid);
// Authorize
var authorizeResult = _processor.AuthorizePayment(invoice, payment, token, payerId);
/*
var authorizePaymentProcArgs = new ProcessorArgumentCollection();
authorizePaymentProcArgs[Constants.ProcessorArgumentsKeys.internalTokenKey] = token;
authorizePaymentProcArgs[Constants.ProcessorArgumentsKeys.internalPayerIDKey] = payerId;
authorizePaymentProcArgs[Constants.ProcessorArgumentsKeys.internalPaymentKeyKey] = payment.Key.ToString();
var authorizeResult = paymentGatewayMethod.AuthorizeCapturePayment(invoice, payment.Amount, authorizePaymentProcArgs);
*/
_merchelloContext.Services.GatewayProviderService.Save(payment);
if (!authorizeResult.Payment.Success)
{
LogHelper.Error<PayPalApiController>("Payment is not authorized.", authorizeResult.Payment.Exception);
_merchelloContext.Services.GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, "PayPal: request capture authorization error: " + authorizeResult.Payment.Exception.Message, 0);
return ShowError(authorizeResult.Payment.Exception.Message);
}
_merchelloContext.Services.GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, "PayPal: capture authorized", 0);
// The basket can be empty
var customerContext = new Merchello.Web.CustomerContext(this.UmbracoContext);
var currentCustomer = customerContext.CurrentCustomer;
if (currentCustomer != null) {
var basket = Merchello.Web.Workflow.Basket.GetBasket(currentCustomer);
basket.Empty();
}
// Capture
var captureResult = paymentGatewayMethod.CapturePayment(invoice, payment, payment.Amount, null);
if (!captureResult.Payment.Success)
{
LogHelper.Error<PayPalApiController>("Payment is not captured.", captureResult.Payment.Exception);
return ShowError(captureResult.Payment.Exception.Message);
}
// redirect to Site
var returnUrl = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.ReturnUrl);
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri(returnUrl.Replace("%INVOICE%", invoice.Key.ToString().EncryptWithMachineKey()));
return response;
}
/// <summary>
/// Abort payment
/// </summary>
/// <param name="invoiceKey"></param>
/// <param name="paymentKey"></param>
/// <param name="token"></param>
/// <param name="payerId"></param>
/// <returns></returns>
/// <example>/umbraco/MerchelloPayPal/PayPalApi/AbortPayment?InvoiceKey=3daeee31-da2c-41d0-a650-52bafaa16dc1&PaymentKey=562e3108-2c68-4f8e-8818-b5685e3df160&token=EC-0NN997417U7730318&PayerID=UBDNS4GA4TB7Y</example>
[HttpGet]
public HttpResponseMessage AbortPayment(Guid invoiceKey, Guid paymentKey, string token, string payerId = null)
{
var invoiceService = _merchelloContext.Services.InvoiceService;
var paymentService = _merchelloContext.Services.PaymentService;
var invoice = invoiceService.GetByKey(invoiceKey);
var payment = paymentService.GetByKey(paymentKey);
if (invoice == null || payment == null || String.IsNullOrEmpty(token))
{
var ex = new NullReferenceException(string.Format("Invalid argument exception. Arguments: invoiceKey={0}, paymentKey={1}, token={2}, payerId={3}.", invoiceKey, paymentKey, token, payerId));
LogHelper.Error<PayPalApiController>("Payment is not authorized.", ex);
return ShowError(ex.Message);
}
// Delete invoice
invoiceService.Delete(invoice);
// Return to CancelUrl
var cancelUrl = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CancelUrl);
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri(cancelUrl);
return response;
}
/*
// for test
[HttpGet]
public string RefundPayment(Guid invoiceKey, Guid paymentKey)
{
var invoice = _merchelloContext.Services.InvoiceService.GetByKey(invoiceKey);
var payment = _merchelloContext.Services.PaymentService.GetByKey(paymentKey);
if (invoice == null || payment == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
var result = _processor.RefundPayment(invoice, payment, 0);
return "";
}
*/
// TODO: add link to Error page
private HttpResponseMessage ShowError(string message)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent("Error: " + message, Encoding.UTF8, "text/plain");
return resp;
}
}
}