Ejemplo n.º 1
0
        public string GetPayerId(string guid, string paymentId, string token, string PayerID)
        {
            APIContext apiContext     = PayPalConfiguration.GetAPIContext();
            var        executePayment = ExecutePayment(apiContext, PayerID, paymentId);

            return(PayerID);
        }
Ejemplo n.º 2
0
        public static Plan CreateBillingPlan(string name, string description, string baseUrl)
        {
            var returnUrl = baseUrl + "/Home/SubscribeSuccess";
            var cancelUrl = baseUrl + "/Home/SubscribeCancel";

            // Plan Details
            var plan = CreatePlanObject("Test Plan", "Plan for Tuts+", returnUrl, cancelUrl,
                                        PlanInterval.Month, 1, (decimal)19.90, trial: true, trialLength: 1, trialPrice: 0);

            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Create plan
            plan = plan.Create(apiContext);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan()
                    {
                        state = "ACTIVE"
                    }
                }
            };

            plan.Update(apiContext, patchRequest);

            return(plan);
        }
Ejemplo n.º 3
0
        public static Payment CreatePayment(string baseUrl, string intent)
        {
            // ### 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.
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Payment Resource
            var payment = new Payment()
            {
                intent = intent,        // `sale` or `authorize`
                payer  = new Payer()
                {
                    payment_method = "paypal"
                },
                transactions  = GetTransactionsList(),
                redirect_urls = GetReturnUrls(baseUrl, intent)
            };

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);

            return(createdPayment);
        }
Ejemplo n.º 4
0
        public void CreateAndExecutePayment()
        {
            AppSettingsReader appSettingsReader = new AppSettingsReader();
            string            clientId          = (string)appSettingsReader.GetValue("clientId", typeof(string));
            string            clientSecret      = (string)appSettingsReader.GetValue("clientSecret", typeof(string));
            var apicontext = PayPalConfiguration.GetAPIContext(clientId, clientSecret);

            PaymentController controller = new PaymentController();
            var          guid            = Convert.ToString((new Random()).Next(100000));
            string       baseURI         = "http://localhost:37256/Paypal/PayWithPayPal?guid=" + guid;
            BouquetOrder bouquet         = new BouquetOrder(1, 1, new Bouquet(6, "gardenia", 2.00, 0));
            var          payment         = controller.CreatePayment(apicontext, baseURI, bouquet);

            var context = new Mock.MockHttpContext();

            context.m_request.m_queryString.Add("PayerID", guid);
            context.m_request.m_queryString.Add("guid", guid);
            context.Session.Add(guid, payment.id);

            controller.ControllerContext = new ControllerContext {
                HttpContext = context, RouteData = new RouteData()
            };
            var result = controller.ExecutePayment(apicontext, guid, payment.id);

            Assert.IsNotNull(apicontext, "PayPal API context is null");
            Assert.IsNotNull(payment.id, "Fail to create payment");
            //must be failed because the data are fake.
            Assert.IsTrue(result.state.ToLower() != "approved", result.state.ToLower());
        }
Ejemplo n.º 5
0
        public static Agreement CreateBillingAgreement(string planId, ShippingAddress shippingAddress,
                                                       string name, string description, DateTime startDate)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                name        = name,
                description = description,
                start_date  = startDate.ToString("yyyy-MM-ddTHH:mm:ss") + "Z",
                payer       = new Payer()
                {
                    payment_method = "paypal"
                },
                plan = new Plan()
                {
                    id = planId
                },
                shipping_address = shippingAddress
            };

            var createdAgreement = agreement.Create(apiContext);

            return(createdAgreement);
        }
Ejemplo n.º 6
0
        public ActionResult PaymentWithPayPal()
        {
            if (System.Web.HttpContext.Current.Request.Cookies["UserEMail"] != null)
            {
                APIContext apiContext = PayPalConfiguration.GetAPIContext();
                try
                {
                    //string payerId = Request.Cookies["UserID"].Value;
                    string payerId = Request.Params["PayerID"];
                    if (string.IsNullOrEmpty(payerId))
                    {
                        string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Store/PaymentWithPayPal?";
                        //string baseURI = "http://localhost:5696/Store/ShoppingCart/PaymentWithPayPal?";
                        var guid           = Convert.ToString((new Random()).Next(100000));
                        var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                        var    links             = createdPayment.links.GetEnumerator();
                        string paypalRedirectUrl = string.Empty;

                        while (links.MoveNext())
                        {
                            Links link = links.Current;
                            if (link.rel.ToLower().Trim().Equals("approval_url"))
                            {
                                paypalRedirectUrl = link.href;
                            }
                        }
                        Session.Add(guid, createdPayment.id);
                        return(Redirect(paypalRedirectUrl));
                    }
                    else
                    {
                        var guid            = Request.Params["guid"];
                        var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                        if (executedPayment.state.ToLower() != "approved")
                        {
                            return(View("Failure"));
                        }
                    }
                }
                catch (Exception)
                {
                    return(View("Failure"));
                }


                CreateOrder();

                Session["cart"]  = null;
                Session["count"] = null;


                return(View("Success"));
            }

            ViewBag.Message = "U moet ingelogd zijn om de producten te kunnen afrekenen.";
            return(View("ShoppingCart"));
        }
Ejemplo n.º 7
0
        public static void ExecuteBillingAgreement(string token)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                token = token
            };
            var executedAgreement = agreement.Execute(apiContext);
        }
Ejemplo n.º 8
0
        // GET: Payment
        public ActionResult PaymantWithPayPal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Payment/PaymentAndOrderInfo?";
                    var guid = Convert.ToString((new Random().Next(1000000)));
                    //var GUID = Guid.NewGuid();
                    var createPayment = this.CreatePayment(apiContext, baseUri + "guid=" + guid);
                    var links         = createPayment.links.GetEnumerator();

                    string payPalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            payPalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createPayment.id);
                    return(Redirect(payPalRedirectUrl));
                }

                else
                {
                    var guid          = Request.Params["guid"];
                    var excutePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (excutePayment.ToString().ToLower() != "approved")
                    {
                        return(View("FalureView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("FalureView"));
            }


            return(View("SuccessView"));
        }
Ejemplo n.º 9
0
        public static void CancelBillingAgreement(string agreementId)
        {
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                id = agreementId
            };

            agreement.Cancel(apiContext, new AgreementStateDescriptor()
            {
                note = "Cancelling the agreement"
            });
        }
Ejemplo n.º 10
0
        public static void ReactivateBillingAgreement(string agreementId)
        {
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                id = agreementId
            };

            agreement.ReActivate(apiContext, new AgreementStateDescriptor()
            {
                note = "Reactivating the agreement"
            });
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Buy a product
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="price"></param>
        /// <param name="shipping"></param>
        /// <param name="tax"></param>
        /// <returns></returns>
        public ActionResult CreateOrder(int id, string name, double price, double shipping, double tax)
        {
            var        bouquet    = new Bouquet(id, name, price, shipping);
            var        order      = new BouquetOrder(1, tax, bouquet);
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            if (apiContext == null)
            {
                var error = new ErrorMessage();
                error.Message = "Configuration error";
                return(View("FailureView", error));
            }
            return(Payment(apiContext, order));
        }
Ejemplo n.º 12
0
        // GET: Payment
        public ActionResult PaymentWithPaypal(string Cancel = null)
        {
            APIContext aPIContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerId"];
                if (string.IsNullOrEmpty(payerId) && payerId != null)
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "PaymentWithPaypal/PaymentWithPaypal?";

                    var guid          = Convert.ToString((new Random()).Next(1000000000));
                    var createPayment = this.CreatePayment(aPIContext, baseUri + "guid=" + guid);

                    var links = createPayment.links.GetEnumerator();

                    string paypalRedirectURL = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;

                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }
                }
                else
                {
                    var guid = Request.Params["guid"];

                    var excecutedPayment = ExecutePayment(aPIContext, payerId, Session[guid] as string);

                    if (excecutedPayment.ToString().ToLower() != "approved")
                    {
                        return(View("PaymentFailurView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("PaymentFailurView"));
                //throw;
            }

            return(View("PaymentSuccessView"));
        }
        public ActionResult PaymentWithPayPal(string Cancel = null)
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerID = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerID))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Payment/PaymentWithPayPal?";
                    var    guid    = Convert.ToString((new Random()).Next(100000));
                    Console.WriteLine(baseURI);
                    Console.WriteLine(guid);
                    var    createdPayment    = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectURL = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;

                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectURL));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception: ", exception);
                return(View("Failure"));
            }

            Session.Clear();
            return(View("Success"));
        }
Ejemplo n.º 14
0
        //GET: Payment
        public ActionResult PaymentWithPaypal()
        {
            APIContext ApiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string PayerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(PayerId))
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Payment/PaymentWithPaypal?";
                    var    guid              = Convert.ToString((new Random()).Next(100000000));
                    var    createPayment     = CreatePayment(ApiContext, baseUri + "guid=" + guid);
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(ApiContext, PayerId, Session[guid] as string);

                    if (executePayment.state.ToLower() != "approved")
                    {
                        Session.Remove("Cart");
                        return(View("failureView"));
                    }
                }
            }
            //for better debugging exception sending directly to failure View
            catch (Exception e)
            {
                Session.Remove("Cart");
                return(View("failureView", e));
            }

            Session.Remove("Cart");
            return(View("successView"));
        }
Ejemplo n.º 15
0
        // GET: Payment
        public ActionResult PaymentWithPaypal()
        {
            APIContext apicontext = PayPalConfiguration.GetAPIContext();

            try
            {
                string PayerID = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(PayerID))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "PaymentWithPaypal/PaymentWithPaypal?";

                    var Guid = Convert.ToString((new Random()).Next(100000000));

                    var createPayment = this.CreatePayment(apicontext, baseURI + "guid=" + Guid);

                    var links = createPayment.links.GetEnumerator();

                    string paypalRedirect = null;

                    while (links.MoveNext())
                    {
                        Links ink = links.Current;

                        if (ink.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirect = ink.href;
                        }
                    }
                }
                else
                {
                    var guid = Request.Params["guid"];

                    var exectePayment = ExecutePayment(apicontext, PayerID, Session[guid] as string);

                    if (exectePayment.ToString().ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
Ejemplo n.º 16
0
        public PaymentHistory GetPaymentHistory(PayPalObjectInfo objPayPalobject)
        {
            var apiContext     = PayPalConfiguration.GetAPIContext();
            var paymentHistory = new PaymentHistory();

            try
            {
                paymentHistory = Payment.List(apiContext, objPayPalobject.Count, objPayPalobject.StartID, objPayPalobject.StartIndex, objPayPalobject.StartTime, objPayPalobject.EndTime, objPayPalobject.StartDate, objPayPalobject.EndTime, objPayPalobject.PayeeEmail, objPayPalobject.PayeeID, objPayPalobject.SortBy, objPayPalobject.SortOrder);
            }
            catch (PaymentsException ex)
            {
                throw new Exception("Sorry there is an error getting the payment history. " + ex.Response);
            }
            return(paymentHistory);
        }
        public ActionResult PaymentWithPaypal()
        {
            if (AuthorizationHelper.GetUserInfo() is null)
            {
                return(RedirectToAction("Login", "Account"));
            }
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURL           = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?";
                    var    guid              = Convert.ToString((new Random()).Next(100000));
                    var    createPayment     = CreatePayment(apiContext, baseURL + "guid=" + guid);
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(RedirectToAction("Error", "Home"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Error", "Home"));
                //PaypalLogger.Log("Error: " + ex.Message);
            }

            return(RedirectToAction("OrderData", "Cart", PaymentMethod.Paypal));
        }
Ejemplo n.º 18
0
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI           = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?";
                    var    guid              = Convert.ToString(new Random().Next(100000));
                    var    createdPayment    = CreatePayment(apiContext, baseURI + "guid=" + guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (!executedPayment.state.ToLower().Equals("approved"))
                    {
                        Session["cart"] = null;
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception)
            {
                Session["cart"] = null;
                return(View("Failure"));
            }
            AcceptOrder();
            Session["cart"] = null;
            return(View("Success"));
        }
Ejemplo n.º 19
0
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = HttpContext.Request.Query["PayerId"].ToString();
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI           = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value + "/Cart/PaymentWithPaypal?";
                    var    guid              = Guid.NewGuid().ToString();
                    var    createdPayment    = CreatePayment(apiContext, baseURI + "guid=" + guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    HttpContext.Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = HttpContext.Request.Query["guid"].ToString();
                    var executedPayment = ExecutePayment(apiContext, payerId, HttpContext.Session.Get <string>(guid));
                    if (!executedPayment.state.ToLower().Equals("approved"))
                    {
                        HttpContext.Session.Add <List <Product> >("cart", null);
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception)
            {
                HttpContext.Session.Add <List <Product> >("cart", null);
                return(View("Failure"));
            }
            AcceptOrder();
            HttpContext.Session.Add <List <Product> >("cart", null);
            return(View("Success"));
        }
Ejemplo n.º 20
0
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerId"];
                if (string.IsNullOrEmpty(payerId))
                {
                    var    guid              = Convert.ToString((new Random()).Next(100000));
                    var    createPayment     = CreatePayment(apiContext, "http://localhost:64366/Home/GetPayerId?guid=" + guid);
                    string paypalREdirectUrl = string.Empty;
                    var    links             = createPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalREdirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalREdirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() == "approved")
                    {
                        Console.WriteLine("EEE");
                    }
                    return(Redirect("https://google.com"));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return(View());
            }
        }
Ejemplo n.º 21
0
        public IActionResult Webhook()
        {
            // The APIContext object can contain an optional override for the trusted certificate.
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Get the received request's headers
            var requestheaders = HttpContext.Request.Headers;

            // Get the received request's body
            var requestBody = string.Empty;

            using (var reader = new System.IO.StreamReader(HttpContext.Request.Body))
            {
                requestBody = reader.ReadToEnd();
            }

            dynamic jsonBody  = JObject.Parse(requestBody);
            string  webhookId = jsonBody.id;
            var     ev        = WebhookEvent.Get(apiContext, webhookId);

            // We have all the information the SDK needs, so perform the validation.
            // Note: at least on Sandbox environment this returns false.
            // var isValid = WebhookEvent.ValidateReceivedEvent(apiContext, ToNameValueCollection(requestheaders), requestBody, webhookId);

            switch (ev.event_type)
            {
            case "PAYMENT.CAPTURE.COMPLETED":
                // Handle payment completed
                break;

            case "PAYMENT.CAPTURE.DENIED":
                // Handle payment denied
                break;

            // Handle other webhooks
            default:
                break;
            }

            return(Ok());
        }
Ejemplo n.º 22
0
        public void Payment()
        {
            AppSettingsReader appSettingsReader = new AppSettingsReader();
            string            clientId          = (string)appSettingsReader.GetValue("clientId", typeof(string));
            string            clientSecret      = (string)appSettingsReader.GetValue("clientSecret", typeof(string));
            var apicontext = PayPalConfiguration.GetAPIContext(clientId, clientSecret);

            PaymentController controller = new PaymentController();

            controller.ControllerContext = new ControllerContext {
                HttpContext = new Mock.MockHttpContext(), RouteData = new RouteData()
            };
            BouquetOrder bouquet = new BouquetOrder(3, 1, new Bouquet(6, "gardenia", 2.00, 0));

            var result    = controller.Payment(apicontext, bouquet);
            var url       = ((RedirectResult)(result)).Url;
            var permanent = ((RedirectResult)(result)).Permanent;

            Assert.IsTrue(permanent == false, "Should have redirected");
            Assert.IsNotNull(result, "url null");
        }
Ejemplo n.º 23
0
        public static void UpdateBillingPlan(string planId, string path, object value)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Retrieve Plan
            var plan = Plan.Get(apiContext, planId);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace", // Only the 'replace' operation is supported when updating billing plans.
                    path  = path,
                    value = value
                }
            };

            plan.Update(apiContext, patchRequest);
        }
Ejemplo n.º 24
0
        public static Payment ExecutePayment(string paymentId, string payerId)
        {
            // ### 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.
            var apiContext = PayPalConfiguration.GetAPIContext();

            var paymentExecution = new PaymentExecution()
            {
                payer_id = payerId
            };
            var payment = new Payment()
            {
                id = paymentId
            };

            // Execute the payment.
            var executedPayment = payment.Execute(apiContext, paymentExecution);

            return(executedPayment);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Pay with Paypal
        /// </summary>
        /// <returns></returns>
        public ActionResult PayWithPaypal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            if (apiContext == null)
            {
                var error = new ErrorMessage();
                error.Message = "Configuration error";
                return(View("FailureView", error));
            }
            string payerId        = Request.Params["PayerID"];
            var    guid           = Request.Params["guid"];
            var    executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

            if (executePayment.state.ToLower() != "approved")
            {
                var error = new ErrorMessage();
                error.Message = "The payment couldn't be processed";
                return(View("FailureView", error));
            }

            return(View("SuccessView", executePayment.transactions));
        }
Ejemplo n.º 26
0
        public static Capture CapturePayment(string paymentId)
        {
            var apiContext = PayPalConfiguration.GetAPIContext();

            var payment = Payment.Get(apiContext, paymentId);
            var auth    = payment.transactions[0].related_resources[0].authorization;

            // Specify an amount to capture.  By setting 'is_final_capture' to true, all remaining funds held by the authorization will be released from the funding instrument.
            var capture = new Capture()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total    = "4.54"
                },
                is_final_capture = true
            };

            // Capture an authorized payment by POSTing to
            // URI v1/payments/authorization/{authorization_id}/capture
            var responseCapture = auth.Capture(apiContext, capture);

            return(responseCapture);
        }
Ejemplo n.º 27
0
        public Payment ProcessPayment(PayPalObjectInfo objPayPalObject)
        {
            var apiContext       = PayPalConfiguration.GetAPIContext();
            var paymentExecution = new PaymentExecution()
            {
                payer_id = objPayPalObject.PayerID
            };
            var payment = new Payment()
            {
                id = objPayPalObject.PaymentID
            };
            var executedPayment = new Payment();

            try
            {
                executedPayment = payment.Execute(apiContext, paymentExecution);
            }
            catch (PaymentsException ex)
            {
                throw new Exception("Sorry there is an error processing the payment. " + ex.Response);
            }

            return(executedPayment);
        }
Ejemplo n.º 28
0
        public ActionResult PaymentWithPaypal(string name, string price)
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerId"];
                if (string.IsNullOrEmpty(payerId))
                {
                    var    guid              = Convert.ToString((new Random()).Next(100000));
                    var    createPayment     = CreatePayment(apiContext, $"{Request.Url.Scheme}://{Request.Url.Authority}/PayPal/PaymentWithPaypal", name, price);
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var execution = ExecutePayment(apiContext, payerId, Request.Params["paymentId"]);
                    return(Redirect("https://google.com"));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return(Redirect("https://google.com"));
            }
        }
Ejemplo n.º 29
0
        public ActionResult Webhook()
        {
            // The APIContext object can contain an optional override for the trusted certificate.
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Get the received request's headers
            var requestheaders = HttpContext.Request.Headers;

            // Get the received request's body
            var requestBody = string.Empty;

            using (var reader = new System.IO.StreamReader(HttpContext.Request.InputStream))
            {
                requestBody = reader.ReadToEnd();
            }

            //get event data from the request body
            dynamic  jsonBody        = JObject.Parse(requestBody);
            string   webhookId       = jsonBody.id;
            string   paypalID        = jsonBody.resource.id;
            decimal  Totalamount     = (decimal)jsonBody.resource.amount.total;
            DateTime paypalEventDate = (DateTime)jsonBody.create_time;
            DateTime paypalTransDate = (DateTime)jsonBody.resource.create_time;

            var ev = WebhookEvent.Get(apiContext, webhookId);

            // We have all the information the SDK needs, so perform the validation.
            // Note: at least on Sandbox environment this returns false.
            // var isValid = WebhookEvent.ValidateReceivedEvent(apiContext, ToNameValueCollection(requestheaders), requestBody, webhookId);

            //add record on the Notification table
            //Note: remove if events are successful. Notification table is used for sms notifications.
            DB.addTestNotification(1, "1");

            //get jobid from CUSTOM object field
            //int jobId =  (int)jsonBody.resource.custom ; // bookingid ,
            //PPtrans.AddPaypalNotif("1", 1, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);

            //get job id from invoice number
            //PPtrans.AddPaypalNotif(paypalID, jobId, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);
            //jobId = (int)jsonBody.resource.invoice_number;
            // DB.addTestNotification(jobId, paypalID);

            //get job description
            JobMain      jobOrder     = db.JobMains.Find(1);
            string       clientName   = jobOrder.Description;
            EMailHandler mail         = new EMailHandler();
            string       siteRedirect = "https://realwheelsdavao.com/reservation/";

            /* Handle transaction request from paypal webhook events
             * switch (ev.event_type)
             * {
             *  case "PAYMENT.CAPTURE.COMPLETED":
             *  case "PAYMENT.SALE.COMPLETED": // Handle payment completed
             *      //record payment
             *      AddPaymentRecord(jobId, Totalamount);
             *
             *      //send mail
             *      mail.SendMail(jobId, "*****@*****.**", "PAYMENT-SUCCESS", clientName, siteRedirect);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-SUCCESS", clientName, siteRedirect);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-SUCCESS", clientName, siteRedirect);
             *
             *      //add to log
             *      PPtrans.AddPaypalNotif(paypalID, jobId, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);
             *      break;
             *  case "PAYMENT.SALE.DENIED":
             *  case "PAYMENT.CAPTURE.DENIED": // Handle payment denied
             *
             *      //send mail
             *      mail.SendMail(jobId, "*****@*****.**", "PAYMENT-DENIED", clientName, siteRedirect);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-DENIED", clientName, siteRedirect);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-DENIED", clientName, siteRedirect);
             *
             *      //add to log
             *      PPtrans.AddPaypalNotif(paypalID, jobId, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);
             *
             *      break;
             *  // Handle other webhooks
             *  default: // Handle payment denied
             *      //send mail
             *      mail.SendMail(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);
             *      //mail.SendMail2(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect, ev.event_type);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);
             *      //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);
             *
             *      //add to log
             *      PPtrans.AddPaypalNotif(paypalID, jobId, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);
             *
             *      break;
             * }
             */

            //AddPaymentRecord(jobId, Totalamount);
            //add to log
            //PPtrans.AddPaypalNotif(paypalID, jobId, paypalEventDate, paypalTransDate, ev.event_type, Totalamount);

            //send mail
            //mail.SendMail(1, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);
            //mail.SendMail2(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect, ev.event_type);
            //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);
            //mail.SendMail(jobId, "*****@*****.**", "PAYMENT-PENDING", clientName, siteRedirect);

            return(new HttpStatusCodeResult(200));
        }
Ejemplo n.º 30
0
        public async Task <ActionResult> Checkout()
        {
            var cart = CreateOrGetCart();

            Entities.Order  order = new Entities.Order();
            ApplicationUser user  = await System.Web.HttpContext.Current.GetOwinContext()
                                    .GetUserManager <ApplicationUserManager>()
                                    .FindByIdAsync(User.Identity.GetUserId());


            order.UserName     = user.UserName;
            order.Address      = user.Address;
            order.PostalCode   = user.PostalCode;
            order.City         = user.City;
            order.ContactPhone = user.PhoneNumber;
            order.OrderDate    = DateTime.Now;
            order.TotalPrice   = cart.GetTotalPrice();
            var stringArrayPrice   = order.TotalPrice.ToString("#.##").Split(',');
            var StringPriceWithDot = String.Join(".", stringArrayPrice);



            if (cart.CartBurgers.Any() || cart.CartDrinks.Any())
            {
                try
                {
                    var    apiContext = PayPalConfiguration.GetAPIContext();
                    string payerId    = Request.Params["PayerID"];
                    if (string.IsNullOrEmpty(payerId))
                    {
                        var itemList = new ItemList()
                        {
                            items = new List <Item>()
                            {
                                new Item()
                                {
                                    name     = order.UserName + "'s Order",
                                    currency = "USD",
                                    price    = StringPriceWithDot,
                                    quantity = "1",
                                    sku      = "Burgers&Drinks"
                                }
                            }
                        };

                        var payer = new Payer()
                        {
                            payment_method = "paypal"
                        };

                        var baseURI     = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/Checkout?";
                        var guid        = Convert.ToString((new Random()).Next(100000));
                        var redirectUrl = baseURI + "guid=" + guid;
                        var redirUrls   = new RedirectUrls()
                        {
                            cancel_url = redirectUrl + "&cancel=true",
                            return_url = redirectUrl
                        };

                        var details = new Details()
                        {
                            subtotal = StringPriceWithDot
                        };

                        var amount = new Amount()
                        {
                            currency = "USD",
                            total    = StringPriceWithDot, // Total must be equal to sum of shipping, tax and subtotal.
                            details  = details
                        };

                        var transactionList = new List <Transaction>();
                        transactionList.Add(new Transaction()
                        {
                            description    = "Transaction description.",
                            invoice_number = CommonPayPal.GetRandomInvoiceNumber(),
                            amount         = amount,
                            item_list      = itemList,
                            payee          = new Payee
                            {
                                email = "*****@*****.**"
                            }
                        });

                        var payment = new Payment()
                        {
                            intent        = "sale",
                            payer         = payer,
                            transactions  = transactionList,
                            redirect_urls = redirUrls
                        };
                        var createdPayment = payment.Create(apiContext);
                        var links          = createdPayment.links.GetEnumerator();

                        string paypalRedirectUrl = null;

                        while (links.MoveNext())
                        {
                            Links lnk = links.Current;

                            if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                            {
                                //saving the payapalredirect URL to which user will be redirected for payment
                                paypalRedirectUrl = lnk.href;
                            }
                        }

                        // saving the paymentID in the key guid
                        Session.Add(guid, createdPayment.id);

                        return(Redirect(paypalRedirectUrl));
                    }
                    else
                    {
                        // This function exectues after receving all parameters for the payment

                        var guid             = Request.Params["guid"];
                        var paymentId        = Session[guid] as string;
                        var paymentExecution = new PaymentExecution()
                        {
                            payer_id = payerId
                        };
                        var payment = new Payment()
                        {
                            id = paymentId
                        };

                        var executedPayment = payment.Execute(apiContext, paymentExecution);

                        //If executed payment failed then we will show payment failure message to user
                        if (executedPayment.state.ToLower() != "approved")
                        {
                            return(View("FailureView"));
                        }
                    }
                }
                catch (PayPal.PaymentsException ex)
                {
                    Debug.WriteLine(ex.InnerException);
                    Debug.WriteLine("----------------------");
                    Debug.WriteLine(ex.Data);
                    Debug.WriteLine("----------------------");
                    Debug.WriteLine(ex.Details);
                    Debug.WriteLine("----------------------");

                    Debug.WriteLine(ex.Response);
                }
                catch (Exception ex)
                {
                    return(View("FailureView"));
                }
                if (cart.CartBurgers.Any())
                {
                    foreach (var burger in cart.CartBurgers)
                    {
                        order.OrderBurgers.Add(new OrderBurger
                        {
                            Name       = burger.Name,
                            Price      = burger.Price,
                            Quantity   = burger.Quantity,
                            MeatName   = burger.MeatName,
                            BreadName  = burger.BreadName,
                            CheeseName = burger.CheeseName,
                            SauceName  = burger.SauceName,
                            VeggieName = burger.VeggieName
                        });
                    }
                }

                if (cart.CartDrinks.Any())
                {
                    foreach (var drink in cart.CartDrinks)
                    {
                        order.OrderDrinks.Add(new OrderDrink
                        {
                            Name     = drink.Name,
                            Litre    = drink.Litre,
                            Quantity = drink.Quantity,
                            Price    = drink.Price
                        });
                    }
                }

                db.Orders.Add(order);
                await db.SaveChangesAsync();

                //on successful payment, show success page to user.
                Session["count"] = 0;
                ClearCart();
                return(View("SuccessView", order));
            }


            return(RedirectToAction("Index", "Cart"));
        }