예제 #1
0
        public void CompletePayment(string paymentTransactionId, string payerId)
        {
            var apiContext = ApiContextFactory.Create();
            var payment = new Payment { id = paymentTransactionId };
            var paymentExecution = new PaymentExecution { payer_id = payerId };

            // Call paypal to complete the payment
            payment.Execute(apiContext, paymentExecution);
        }
 protected void Page_Init(Object sender, EventArgs e)
 {
     if (HttpContext.Current.User.Identity.IsAuthenticated)
     {
         if (Request.QueryString["OrderId"] != null && Request.QueryString["Success"] != null)
         {
             var orderID = Request.QueryString["OrderId"];
             var payerID = Request.QueryString["PayerId"];
             var isSuccess = Convert.ToBoolean(Request.QueryString["Success"]);
             if (isSuccess)
             {
                 PaymentExecution pymntExecution = new PaymentExecution();
                 pymntExecution.payer_id = payerID;
                 Payment pymnt = new Payment();
                 pymnt.id = GetOrdersPaymentID(orderID);
                 Payment pay = null;
                 try
                 {
                     pay = pymnt.Execute(accessToken, pymntExecution);
                     if (pay != null && pay.state.Trim().ToLower().Equals("approved"))
                     {
                         var state = pay.state.Trim();
                         var updatedAtDateTime = Convert.ToDateTime(pay.create_time);
                         var updatedAt = updatedAtDateTime.ToString("yyyy-MM-dd hh:mm:ss.FFFFF");
                         var ordID = Convert.ToInt32(orderID);
                         bool isUpdated = Update(ordID, state, updatedAt);
                     }
                 }
                 catch (Exception ex)
                 {
                     divAlertMessage.Visible = true;
                     divAlertMessage.Attributes["class"] = "alert fade in alert-error";
                     labelAlertMessage.InnerText = ex.Message;
                 }
             }
             else
             {
                 orderID = Request.QueryString["OrderId"];
                 var updatedAtDateTime = DateTime.Now;
                 var updatedAt = updatedAtDateTime.ToString("yyyy-MM-dd hh:mm:ss.FFFFF");
                 bool isUpdated = Update(Convert.ToInt32(orderID), "cancelled", updatedAt);
             }
         }
     }
     else
     {
         Response.Redirect("~/Users/SignIn.aspx");
     }
 }
예제 #3
0
        public ActionResult Confirmed(Guid id, string token, string payerId)
        {
            var viewData = new OrderConfirmedViewData
            {
                Id = id,
                Token = token,
                PayerId = payerId
            };

            var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            var payment = new Payment()
            {
                id = (string)Session[id.ToString()],
            };

            var executedPayment = payment.Execute(apiContext, new PaymentExecution { payer_id = payerId });

            viewData.AuthorizationId = executedPayment.transactions[0].related_resources[0].authorization.id;
            viewData.JsonRequest = JObject.Parse(payment.ConvertToJson()).ToString(Formatting.Indented);
            viewData.JsonResponse = JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented);

            return View(viewData);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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 apiContext = new APIContext(accessToken);
                    // 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 ));
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext,
                            pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = 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
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as 'sale'
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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 apiContext = new APIContext(accessToken);
                    // 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 ));

                    // Create a payment by posting to the APIService
                    // using a valid AccessToken
                    // The return object contains the status;
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ### 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..
            APIContext apiContext = Configuration.GetAPIContext();

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name = "Item Name";
                item.currency = "USD";
                item.price = "15";
                item.quantity = "5";
                item.sku = "sku";

                List<Item> itms = new List<Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                tran.item_list = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // Create a payment using a valid APIContext
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");

        }
예제 #6
0
        public async Task<IHttpActionResult> PaypalConfirmed(string token, string payerId, string id)
        {
            try
            {
                PaypalDetails paypalDetails = this.commonService.GetCache<PaypalDetails>(id);
                PaypalPayTransactionModel paymentTransaction = this.paymentService.GetPaypalPaymentId(Guid.Parse(id));
                if (paymentTransaction == null)
                {
                    return this.Redirect(string.Format(AppSettings.Get<string>("WebReturnURL"), paypalDetails.Domain, "Invalid request"));
                }

                string paymentId = paymentTransaction.PaymentId;
                if (string.IsNullOrWhiteSpace(paymentId))
                {
                    return this.Redirect(string.Format(AppSettings.Get<string>("WebReturnURL"), paypalDetails.Domain, "Can not proceed now, please try again."));
                }

                var paymentExecution = new PaymentExecution
                {
                    payer_id = payerId
                };

                var payment = new Payment { id = paymentId };
                var response = payment.Execute(this.Api, paymentExecution);
                if (response.state.ToLower() == "approved")
                {
                    PaypalPaymentDetailsModel paymentDetail = new PaypalPaymentDetailsModel();
                    paymentDetail.TransactionId = paymentTransaction.Id;
                    paymentDetail.PayerId = payerId;
                    paymentDetail.Email = response.payer.payer_info.email;
                    paymentDetail.FirstName = response.payer.payer_info.first_name;
                    paymentDetail.LastName = response.payer.payer_info.last_name;
                    paymentDetail.Address = response.payer.payer_info.shipping_address.line1 + " " + response.payer.payer_info.shipping_address.line2 + " " + response.payer.payer_info.shipping_address.state;
                    paymentDetail.Status = response.payer.status;
                    paymentDetail.IsComplete = true;
                    paymentDetail.CreatedOn = DateTime.UtcNow;
                    if (this.paymentService.CompletePaypalTransaction(paymentDetail))
                    {
                        try
                        {
                            bool isSuccess = true;
                            string crmContactId = this.youfferContactService.GetMappingEntryByContactId(paymentTransaction.ClientId).ContactCRMId;
                            string crmLeadId = this.youfferContactService.GetMappingEntryByContactId(paymentTransaction.ClientId).LeadId;
                            string crmOrgId = this.youfferContactService.GetOrgCRMId(paymentTransaction.CompanyId).CRMId;
                            LeadModel leadModel = this.crmManagerService.GetLead(crmLeadId);

                            decimal price = AppSettings.Get<decimal>(ConfigConstants.UserPrice);
                            BuyUserModelDto buyUserModelDto = new BuyUserModelDto { CompanyId = paymentTransaction.CompanyId, UserId = paymentTransaction.ClientId, Interest = paymentTransaction.Need, Amount = price, PurchasedFromCash = false, PurchasedFromCredit = false };
                            isSuccess = this.crmManagerService.AddOpportunity(buyUserModelDto);

                            ////return this.Redirect(string.Format(AppSettings.Get<string>("WebReturnURL"), "Payment Done"));
                            return this.Redirect(string.Format(AppSettings.Get<string>("WebPaymentDone").ToString() + "?status=success", paypalDetails.Domain));
                        }
                        catch (Exception ex)
                        {
                            this.LoggerService.LogException("PaymentController > G2SSuccess(while updating system for who purchased what): " + ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.LoggerService.LogException("PaypalConfirmed :- " + ex.Message);
            }

            ////return this.Redirect(string.Format(AppSettings.Get<string>("WebReturnURL"), "Payment Error found"));
            return this.Redirect(string.Format(AppSettings.Get<string>("WebPaymentDone").ToString() + "?status=error"));
        }
        public void ExecutePayment(string payerId)
        {
            PaymentExecution exec = new PaymentExecution();
            exec.payer_id = payerId;

            Payment payment = new Payment();
            Payment responsePayment = payment.Execute(credentials.AccessToken, new PaymentExecution());

            WriteTestData("TestExecutePayment", responsePayment);
        }
        public ActionResult Orders()
        {
            var model = new OrdersCollection();
            IEnumerable<Order> modelIEnumerable = null;
            if (Request.QueryString["OrderId"] != null && Request.QueryString["Success"] != null)
            {
                var orderId = Request.QueryString["OrderId"];
                var payerId = Request.QueryString["PayerId"];
                var isSuccess = Convert.ToBoolean(Request.QueryString["Success"]);
                if (isSuccess)
                {
                    PaymentExecution payExecution = new PaymentExecution();
                    payExecution.payer_id = payerId;
                    Payment paymnt = new Payment();
                    paymnt.id = GetOrdersPaymentId(orderId);
                    Payment pay = null;
                    try
                    {
                        pay = paymnt.Execute(Api, payExecution);
                        if (pay != null && pay.state.Trim().ToLower().Equals("approved"))
                        {
                            var state = pay.state.Trim();
                            var updatedAtDateTime = Convert.ToDateTime(pay.create_time);
                            var updatedAt = updatedAtDateTime.ToString("yyyy-MM-dd hh:mm:ss.FFFFF");
                            var ordId = Convert.ToInt32(orderId);
                            bool isUpdated = Update(ordId, state, updatedAt);
                        }
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }
                }
                else
                {
                    orderId = Request.QueryString["OrderId"];
                    var updatedAtDateTime = DateTime.Now;
                    var updatedAt = updatedAtDateTime.ToString("yyyy-MM-dd hh:mm:ss.FFFFF");
                    bool isUpdated = Update(Convert.ToInt32(orderId), "cancelled", updatedAt);
                }
            }

            var email = User.Identity.Name.Trim();
            int userId = GetSignedInUserId(email);
            DataTable datTable = GetOrders(userId);
            if (datTable != null && datTable.Rows.Count > 0)
            {
                model.Orders = (from DataRow row in datTable.Rows
                                select new Order
                                {
                                    OrderId = Convert.ToInt32(row["id"]),
                                    UserId = Convert.ToInt32(row["user_id"]),
                                    PaymentId = row["payment_id"].ToString(),
                                    State = row["state"].ToString(),
                                    AmountInUSD = row["amount"].ToString(),
                                    Description = row["description"].ToString(),
                                    CreatedDateTime = Convert.ToDateTime(row["created_at"]),
                                    UpdatedDateTime = Convert.ToDateTime(row["updated_at"]),

                                }).ToList();

                modelIEnumerable = model.Orders;
            }
            return View(modelIEnumerable);
        }