public void AgreementUpdateTest()
        {
            // Get the agreement to be used for verifying the update functionality
            var apiContext  = TestingUtil.GetApiContext();
            var agreementId = "I-HP4H4YJFCN07";
            var agreement   = Agreement.Get(apiContext, agreementId);

            // Create an update for the agreement
            var updatedDescription = Guid.NewGuid().ToString();
            var patch = new Patch();

            patch.op    = "replace";
            patch.path  = "/";
            patch.value = new Agreement()
            {
                description = updatedDescription
            };
            var patchRequest = new PatchRequest();

            patchRequest.Add(patch);

            // Update the agreement
            agreement.Update(apiContext, patchRequest);

            // Verify the agreement was successfully updated
            var updatedAgreement = Agreement.Get(apiContext, agreementId);

            Assert.AreEqual(agreementId, updatedAgreement.id);
            Assert.AreEqual(updatedDescription, updatedAgreement.description);
        }
Exemple #2
0
        protected override void RunSample()
        {
            // ### 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.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // ### Retrieve the Billing Agreement
            // The billing agreement being retrieved is one that was previously created and executed using a PayPal account as the funding source.
            var agreementId = "I-6STR72E7JNP8";

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest(title: "Get billing agreement", description: "ID: " + agreementId);
            //--------------------
            #endregion

            // Use `Agreement.Get()` to retrieve the billing agreement details.
            var agreement = Agreement.Get(apiContext, agreementId);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(agreement);
            //--------------------
            #endregion

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Exemple #3
0
        public ActionResult Details(string id)
        {
            var apiContext = PayPalApiHelperService.GetApiContext();

            var agreement = Agreement.Get(apiContext, id);

            return(View(agreement));
        }
Exemple #4
0
        public ActionResult Details(string id)
        {
            var apiContext = GetApiContext();

            var agreement = Agreement.Get(apiContext, id);

            return(View(agreement));
        }
        public void AgreementGetTest()
        {
            var agreement = Agreement.Get(UnitTestUtil.GetApiContext(), "I-ASXCM9U5MJJV");

            Assert.AreEqual("I-ASXCM9U5MJJV", agreement.id);
            Assert.AreEqual("Agreement for T-Shirt of the Month Club Plan", agreement.description);
            Assert.AreEqual("2015-02-19T08:00:00Z", agreement.start_date);
            Assert.IsNotNull(agreement.plan);
        }
        public void AgreementGetTest()
        {
            var agreementId = "I-RDJKRLEBYWYH";
            var agreement   = Agreement.Get(TestingUtil.GetApiContext(), agreementId);

            Assert.AreEqual(agreementId, agreement.id);
            Assert.AreEqual("Agreement for T-Shirt of the Month Club", agreement.description);
            Assert.AreEqual("2016-02-19T08:00:00Z", agreement.start_date);
            Assert.IsNotNull(agreement.plan);
        }
        public void AgreementCancelTest()
        {
            var apiContext  = TestingUtil.GetApiContext();
            var agreementId = "";
            var agreement   = Agreement.Get(apiContext, agreementId);

            var agreementStateDescriptor = new AgreementStateDescriptor();

            agreementStateDescriptor.note = "Canceling the agreement.";
            agreement.Cancel(apiContext, agreementStateDescriptor);

            var canceledAgreement = Agreement.Get(apiContext, agreementId);
        }
        public void AgreementReactivateTest()
        {
            var apiContext  = TestingUtil.GetApiContext();
            var agreementId = "";
            var agreement   = Agreement.Get(apiContext, agreementId);

            var agreementStateDescriptor = new AgreementStateDescriptor();

            agreementStateDescriptor.note = "Re-activating the agreement.";
            agreement.ReActivate(apiContext, agreementStateDescriptor);

            var reactivatedAgreement = Agreement.Get(apiContext, agreementId);
        }
        public void AgreementSuspendTest()
        {
            var apiContext  = TestingUtil.GetApiContext();
            var agreementId = "";
            var agreement   = Agreement.Get(apiContext, agreementId);

            var agreementStateDescriptor = new AgreementStateDescriptor();

            agreementStateDescriptor.note = "Suspending the agreement.";
            agreement.Suspend(apiContext, agreementStateDescriptor);

            var suspendedAgreement = Agreement.Get(apiContext, agreementId);
        }
        public void AgreementGetTest()
        {
            var apiContext = TestingUtil.GetApiContext();
            var agreement  = new Agreement()
            {
                token = "EC-2CD33889A9699491E"
            };
            var executedAgreement  = agreement.Execute(apiContext);
            var agreementId        = executedAgreement.id;
            var retrievedAgreement = Agreement.Get(apiContext, agreementId);

            Assert.AreEqual(agreementId, retrievedAgreement.id);
            Assert.AreEqual("-6514356286402072739", retrievedAgreement.description);
            Assert.AreEqual("2015-02-19T08:00:00Z", retrievedAgreement.start_date);
            Assert.IsNotNull(retrievedAgreement.plan);
        }
        /// <summary>
        /// Cancels a recurring payment
        /// </summary>
        /// <param name="cancelPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
        {
            var result = new CancelRecurringPaymentResult();

            try
            {
                var apiContext   = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings);
                var subscription = Agreement.Get(apiContext, cancelPaymentRequest.Order.SubscriptionTransactionId);
                var reason       = new AgreementStateDescriptor
                {
                    note = string.Format("Cancel subscription {0}", cancelPaymentRequest.Order.OrderGuid)
                };
                subscription.Cancel(apiContext, reason);
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                }

                //if there are not the specific errors add exception message
                if (result.Success)
                {
                    result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }
            }

            return(result);
        }
        public ActionResult WebhookEventsHandler()
        {
            var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var payPalDirectPaymentSettings = _settingService.LoadSetting <PayPalDirectPaymentSettings>(storeScope);

            try
            {
                var requestBody = string.Empty;
                using (var stream = new StreamReader(Request.InputStream))
                {
                    requestBody = stream.ReadToEnd();
                }
                var apiContext = PaypalHelper.GetApiContext(payPalDirectPaymentSettings);

                //validate request
                if (!WebhookEvent.ValidateReceivedEvent(apiContext, Request.Headers, requestBody, payPalDirectPaymentSettings.WebhookId))
                {
                    _logger.Error("PayPal error: webhook event was not validated");
                    return(new HttpStatusCodeResult(HttpStatusCode.OK));
                }

                var webhook = JsonFormatter.ConvertFromJson <WebhookEvent>(requestBody);

                //recurring payment
                if (webhook.resource_type.ToLowerInvariant().Equals("sale"))
                {
                    var sale = JsonFormatter.ConvertFromJson <Sale>(webhook.resource.ToString());
                    if (!string.IsNullOrEmpty(sale.billing_agreement_id))
                    {
                        //get agreement
                        var agreement    = Agreement.Get(apiContext, sale.billing_agreement_id);
                        var initialOrder = _orderService.GetOrderByGuid(new Guid(agreement.description));
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            if (recurringPayment != null)
                            {
                                if (sale.state.ToLowerInvariant().Equals("completed"))
                                {
                                    if (recurringPayment.RecurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        initialOrder.PaymentStatus        = PaymentStatus.Paid;
                                        initialOrder.CaptureTransactionId = sale.id;
                                        _orderService.UpdateOrder(initialOrder);

                                        recurringPayment.RecurringPaymentHistory.Add(new RecurringPaymentHistory
                                        {
                                            RecurringPaymentId = recurringPayment.Id,
                                            OrderId            = initialOrder.Id,
                                            CreatedOnUtc       = DateTime.UtcNow
                                        });
                                        _orderService.UpdateRecurringPayment(recurringPayment);
                                    }
                                    else
                                    {
                                        //next payments
                                        var orders = _orderService.GetOrdersByIds(recurringPayment.RecurringPaymentHistory.Select(order => order.OrderId).ToArray());
                                        if (!orders.Any(order => !string.IsNullOrEmpty(order.CaptureTransactionId) &&
                                                        order.CaptureTransactionId.Equals(sale.id, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            var processPaymentResult = new ProcessPaymentResult
                                            {
                                                NewPaymentStatus     = PaymentStatus.Paid,
                                                CaptureTransactionId = sale.id
                                            };
                                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, processPaymentResult);
                                        }
                                    }
                                }
                                else
                                {
                                    _logger.Error(string.Format("PayPal error: Sale is {0} for the order #{1}", sale.state, initialOrder.Id));
                                }
                            }
                        }
                    }
                }

                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        _logger.Error(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => _logger.Error(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                    else
                    {
                        _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                    }
                }
                else
                {
                    _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }

                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
        }
Exemple #13
0
        public IActionResult WebhookEventsHandler()
        {
            var storeScope = _storeContext.ActiveStoreScopeConfiguration;
            var payPalDirectPaymentSettings = _settingService.LoadSetting <PayPalDirectPaymentSettings>(storeScope);

            try
            {
                var requestBody = string.Empty;
                using (var stream = new StreamReader(this.Request.Body, Encoding.UTF8))
                {
                    requestBody = stream.ReadToEnd();
                }
                var apiContext = PaypalHelper.GetApiContext(payPalDirectPaymentSettings);

                //validate request
                var headers = new NameValueCollection();
                this.Request.Headers.ToList().ForEach(header => headers.Add(header.Key, header.Value));
                if (!WebhookEvent.ValidateReceivedEvent(apiContext, headers, requestBody, payPalDirectPaymentSettings.WebhookId))
                {
                    _logger.Error("PayPal error: webhook event was not validated");
                    return(Ok());
                }

                var webhook = JsonFormatter.ConvertFromJson <WebhookEvent>(requestBody);

                if (webhook.resource_type.ToLowerInvariant().Equals("sale"))
                {
                    var sale = JsonFormatter.ConvertFromJson <Sale>(webhook.resource.ToString());

                    //recurring payment
                    if (!string.IsNullOrEmpty(sale.billing_agreement_id))
                    {
                        //get agreement
                        var agreement    = Agreement.Get(apiContext, sale.billing_agreement_id);
                        var initialOrder = _orderService.GetOrderByGuid(new Guid(agreement.description));
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            if (recurringPayment != null)
                            {
                                if (sale.state.ToLowerInvariant().Equals("completed"))
                                {
                                    if (recurringPayment.RecurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        initialOrder.PaymentStatus        = PaymentStatus.Paid;
                                        initialOrder.CaptureTransactionId = sale.id;
                                        _orderService.UpdateOrder(initialOrder);

                                        recurringPayment.RecurringPaymentHistory.Add(new RecurringPaymentHistory
                                        {
                                            RecurringPaymentId = recurringPayment.Id,
                                            OrderId            = initialOrder.Id,
                                            CreatedOnUtc       = DateTime.UtcNow
                                        });
                                        _orderService.UpdateRecurringPayment(recurringPayment);
                                    }
                                    else
                                    {
                                        //next payments
                                        var orders = _orderService.GetOrdersByIds(recurringPayment.RecurringPaymentHistory.Select(order => order.OrderId).ToArray());
                                        if (!orders.Any(order => !string.IsNullOrEmpty(order.CaptureTransactionId) &&
                                                        order.CaptureTransactionId.Equals(sale.id, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            var processPaymentResult = new ProcessPaymentResult
                                            {
                                                NewPaymentStatus     = PaymentStatus.Paid,
                                                CaptureTransactionId = sale.id,
                                                AvsResult            = sale.processor_response?.avs_code ?? string.Empty,
                                                Cvv2Result           = sale.processor_response?.cvv_code ?? string.Empty
                                            };
                                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, processPaymentResult);
                                        }
                                    }
                                }
                                else if (sale.state.ToLowerInvariant().Equals("denied"))
                                {
                                    //payment denied
                                    _orderProcessingService.ProcessNextRecurringPayment(recurringPayment,
                                                                                        new ProcessPaymentResult {
                                        Errors = new[] { webhook.summary }, RecurringPaymentFailed = true
                                    });
                                }
                                else
                                {
                                    _logger.Error(
                                        $"PayPal error: Sale is {sale.state} for the order #{initialOrder.Id}");
                                }
                            }
                        }
                    }
                    else
                    //standard payment
                    {
                        var order = _orderService.GetOrderByGuid(new Guid(sale.invoice_number));
                        if (order != null)
                        {
                            if (sale.state.ToLowerInvariant().Equals("completed"))
                            {
                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                {
                                    order.CaptureTransactionId     = sale.id;
                                    order.CaptureTransactionResult = sale.state;
                                    _orderService.UpdateOrder(order);
                                    _orderProcessingService.MarkOrderAsPaid(order);
                                }
                            }
                            if (sale.state.ToLowerInvariant().Equals("denied"))
                            {
                                var reason =
                                    $"Payment is denied. {(sale.fmf_details != null ? $"Based on fraud filter: {sale.fmf_details.name}. {sale.fmf_details.description}" : string.Empty)}";
                                order.OrderNotes.Add(new OrderNote
                                {
                                    Note = reason,
                                    DisplayToCustomer = false,
                                    CreatedOnUtc      = DateTime.UtcNow
                                });
                                _logger.Error($"PayPal error: {reason}");
                            }
                        }
                        else
                        {
                            _logger.Error($"PayPal error: Order with GUID {sale.invoice_number} was not found");
                        }
                    }
                }

                return(Ok());
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        _logger.Error($"PayPal error: {error.message} ({error.name})");
                        if (error.details != null)
                        {
                            error.details.ForEach(x => _logger.Error($"{x.field} {x.issue}"));
                        }
                    }
                    else
                    {
                        _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                    }
                }
                else
                {
                    _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }

                return(Ok());
            }
        }