public ActionResult Checkout(FormCollection collection) { Service service = new Service(); PayPalIndexViewModel model = new PayPalIndexViewModel(); var PayPalService = new PayPalService(); var gateway = PayPalService.PayPalGateway(); var user = UserManager.FindByName(User.Identity.Name); var userInfo = service.GetProfileInfo(user.Id); var memberInfo = service.GetMembership(user.UserName); var subscriptionInfo = service.GetSubscription(memberInfo.MembershipId); var radioButton = collection["radioButton"]; string nonce = collection["payment_method_nonce"]; DateTime startDate = DateTime.Now; DateTime expireDate = DateTime.Now; // Use payment method nonce here if (radioButton == "Monthly") { expireDate.AddMonths(1); Result <Subscription> subResult = PayPalService.PayPalSubscription(nonce, ConstantStrings.annualPlanId); if (subResult.IsSuccess()) { Subscription transaction = subResult.Target; ViewData["TransactionId"] = transaction.Id; service.InactivateSubscription(subscriptionInfo.SubscriptionId); service.CreateSubscription(memberInfo.MembershipId, startDate, expireDate, ConstantStrings.monthlySubscription, subResult.Target.Id); } else { ViewData["Message"] = subResult.Message; } } else if (radioButton == "Annually") { expireDate.AddYears(1); Result <Subscription> subResult = PayPalService.PayPalSubscription(nonce, ConstantStrings.annualPlanId); if (subResult.IsSuccess()) { Subscription transaction = subResult.Target; ViewData["TransactionId"] = transaction.Id; service.InactivateSubscription(subscriptionInfo.SubscriptionId); service.CreateSubscription(memberInfo.MembershipId, startDate, expireDate, ConstantStrings.annualSubscription, subResult.Target.Id); } else { ViewData["Message"] = subResult.Message; } } UserManager.RemoveFromRole(user.Id, "Basic"); UserManager.AddToRole(user.Id, "Premium"); return(View()); }
private bool SaveOffertaCompleta(PayPalIndexViewModel paypal, Payment payment) { AcquistoViewModel viewModel = Session["PayPalCompra"] as AcquistoViewModel; AnnuncioModel model = Session["PayPalAnnuncio"] as AnnuncioModel; using (DatabaseContext db = new DatabaseContext()) { // AGGIUNGERE TRANSAZIONE NELLA TABELLA LOG_PAGAMENTO LOG_PAGAMENTO log = new LOG_PAGAMENTO(); ANNUNCIO annuncio = db.ANNUNCIO.SingleOrDefault(m => m.TOKEN.ToString() == viewModel.Token && m.SESSIONE_COMPRATORE == model.SESSIONE_COMPRATORE); log.ID_ANNUNCIO = annuncio.ID; log.ID_COMPRATORE = (Session["utente"] as PersonaModel).Persona.ID; log.SESSIONE_COMPRATORE = paypal.Guid; log.ID_PAGAMENTO = payment.id; //log.ID_PAGAMENTO = "TEST"; log.ISTITUTO_PAGAMENTO = "PAYPAL"; log.NOME_ANNUNCIO = "Pagamento spedizione per " + annuncio.NOME; log.DATA_INSERIMENTO = DateTime.Now; db.LOG_PAGAMENTO.Add(log); db.SaveChanges(); int idPayPal = SavePayPal(db, payment); using (DbContextTransaction transaction = db.Database.BeginTransaction()) { viewModel.PagamentoFatto = true; AnnuncioModel annuncioModel = new AnnuncioModel(annuncio); Models.Enumerators.VerificaAcquisto verifica = annuncioModel.Acquisto(db, viewModel, true); if (verifica == Models.Enumerators.VerificaAcquisto.Ok) { OFFERTA offerta = db.OFFERTA.SingleOrDefault(m => m.ID == paypal.Id); if (model.CompletaAcquistoOfferta(db, offerta, idPayPal)) { transaction.Commit(); this.RefreshPunteggioUtente(db); Models.ViewModels.Email.PagamentoOffertaViewModel pagamentoOfferta = new Models.ViewModels.Email.PagamentoOffertaViewModel(); pagamentoOfferta.NominativoDestinatario = offerta.ANNUNCIO.PERSONA.NOME + " " + offerta.ANNUNCIO.PERSONA.COGNOME; pagamentoOfferta.NomeAnnuncio = offerta.ANNUNCIO.NOME; pagamentoOfferta.Moneta = offerta.PUNTI; pagamentoOfferta.SoldiSpedizione = offerta.SOLDI; pagamentoOfferta.Baratti = offerta.OFFERTA_BARATTO.Select(m => m.ANNUNCIO.NOME).ToList(); this.SendNotifica((Session["utente"] as PersonaModel).Persona, offerta.ANNUNCIO.PERSONA, TipoNotifica.OffertaPagata, ControllerContext, "pagamentoOfferta", pagamentoOfferta); System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary(new { token = viewModel.Token }); _UrlFinePagamento = Url.Action("Index", "Annuncio", data, this.Request.Url.Scheme, this.Request.Url.Host); return(true); } // altrimenti acquisto fallito } } } return(false); }
private bool SavePayment(PayPalIndexViewModel viewModel, Payment payment) { switch (viewModel.Azione) { case AzionePayPal.Acquisto: return(SaveAcquisto(viewModel, payment)); case AzionePayPal.Offerta: return(SaveOfferta(payment)); case AzionePayPal.OffertaOK: return(SaveOffertaCompleta(viewModel, payment)); } return(false); }
private bool SaveAcquisto(PayPalIndexViewModel paypal, Payment payment) { AcquistoViewModel viewModel = Session["PayPalCompra"] as AcquistoViewModel; AnnuncioModel model = Session["PayPalAnnuncio"] as AnnuncioModel; using (DatabaseContext db = new DatabaseContext()) { // AGGIUNGERE TRANSAZIONE NELLA TABELLA LOG_PAGAMENTO LOG_PAGAMENTO log = new LOG_PAGAMENTO(); ANNUNCIO annuncio = db.ANNUNCIO.SingleOrDefault(m => m.TOKEN.ToString() == viewModel.Token && m.SESSIONE_COMPRATORE == model.SESSIONE_COMPRATORE); log.ID_ANNUNCIO = annuncio.ID; log.ID_COMPRATORE = (Session["utente"] as PersonaModel).Persona.ID; log.SESSIONE_COMPRATORE = paypal.Guid; log.ID_PAGAMENTO = payment.id; //log.ID_PAGAMENTO = "TEST"; log.ISTITUTO_PAGAMENTO = "PAYPAL"; log.NOME_ANNUNCIO = annuncio.NOME; log.DATA_INSERIMENTO = DateTime.Now; db.LOG_PAGAMENTO.Add(log); db.SaveChanges(); int idPaypal = SavePayPal(db, payment); using (DbContextTransaction transaction = db.Database.BeginTransaction()) { viewModel.PagamentoFatto = true; AnnuncioModel annuncioModel = new AnnuncioModel(annuncio); Models.Enumerators.VerificaAcquisto verifica = annuncioModel.Acquisto(db, viewModel); if (verifica == Models.Enumerators.VerificaAcquisto.Ok) { if (model.CompletaAcquisto(db, viewModel, idPaypal)) { transaction.Commit(); this.RefreshPunteggioUtente(db); this.SendNotifica(annuncioModel.PERSONA, annuncioModel.PERSONA1, TipoNotifica.AnnuncioAcquistato, ControllerContext, "annuncioAcquistato", annuncioModel); this.SendNotifica(annuncioModel.PERSONA1, annuncioModel.PERSONA, TipoNotifica.AnnuncioVenduto, ControllerContext, "annuncioVenduto", annuncioModel); System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary(new { token = viewModel.Token }); _UrlFinePagamento = Url.Action("Index", "Annuncio", data, this.Request.Url.Scheme, this.Request.Url.Host); return(true); } // altrimenti acquisto fallito } } } return(false); }
public ActionResult Index() { PayPalIndexViewModel model = new PayPalIndexViewModel(); Service service = new Service(); var user = UserManager.FindByName(User.Identity.Name); var customerId = service.GetCustomer(user.Id); var PayPalService = new PayPalService(); var gateway = PayPalService.PayPalGateway(); var clientToken = gateway.ClientToken.generate( new ClientTokenRequest { CustomerId = customerId } ); model.ClientToken = clientToken; TempData["ClientToken"] = clientToken; return(View(model)); }
public ActionResult Test() { APIContext apiContext = Configuration.GetAPIContext(); PayPalIndexViewModel viewModel = new PayPalIndexViewModel(); viewModel.Azione = AzionePayPal.Acquisto; string urlCancel = GetUrlCancel(viewModel.Azione, viewModel.Token); viewModel.Guid = Convert.ToString((new Random()).Next(100000)); System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary(viewModel); string url = Url.Action("Payment", "PayPal", data, this.Request.Url.Scheme, this.Request.Url.Host); List <Transaction> lista = new List <Transaction>(); //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List <Item>() }; TIPO_VALUTA tipoValuta = (HttpContext.Application["tipoValuta"] as List <TIPO_VALUTA>).SingleOrDefault(m => m.SIMBOLO == NumberFormatInfo.CurrentInfo.CurrencySymbol); itemList.items.Add(new Item() { name = "Nome test", currency = tipoValuta.CODICE, price = ConvertDecimalToString(11), quantity = "1", sku = "sku" }); itemList.items.Add(new Item() { name = string.Concat(App_GlobalResources.Language.Shipment, " test"), currency = tipoValuta.CODICE, price = ConvertDecimalToString(11), //price = ConvertDecimalToString(new Decimal(1006.5)), // prova fissa verifica conversione quantity = "1", sku = "sku" }); decimal subtotal = itemList.items.Sum(m => ConvertStringToDecimal(m.price)); // similar as we did for credit card, do here and create details object var details = new Details() { tax = "0", shipping = "0", subtotal = ConvertDecimalToString(subtotal) }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = tipoValuta.CODICE, total = ConvertDecimalToString(subtotal), // Total must be equal to sum of shipping, tax and subtotal. details = details }; Transaction transazione = new Transaction(); transazione.description = "Test descrizione"; transazione.invoice_number = "testami"; transazione.amount = amount; transazione.item_list = itemList; lista.Add(transazione); var createdPayment = this.CreatePayment(apiContext, url, urlCancel, lista); 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; } } return(Redirect(paypalRedirectUrl)); }
public ActionResult Payment(PayPalIndexViewModel viewModel) { string urlCancel = GetUrlCancel(viewModel.Azione, viewModel.Token); int? id = null; try { //getting the apiContext as earlier APIContext apiContext = Configuration.GetAPIContext(); if ((Session["PayPalCompra"] != null && Session["PayPalAnnuncio"] != null) || Session["PayPalOfferta"] != null) { id = GetIdFromSession(); bool enablePagamento = CanPagamento(viewModel.Azione); if (string.IsNullOrEmpty(viewModel.PayerID) && string.IsNullOrWhiteSpace(viewModel.Guid) && enablePagamento) { //this section will be executed first because PayerID doesn't exist //it is returned by the create function call of the payment class // Creating a payment // baseURL is the url on which paypal sendsback the data. // So we have provided URL of this controller only viewModel.Guid = Convert.ToString((new Random()).Next(100000)); System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary(viewModel); string url = Url.Action("Payment", "PayPal", data, this.Request.Url.Scheme, this.Request.Url.Host); System.Web.Routing.RouteValueDictionary dataCancelPayPal = new System.Web.Routing.RouteValueDictionary(new { azione = viewModel.Azione, id = id }); string urlCancelPaypal = Url.Action("CancelPayment", "PayPal", dataCancelPayPal, this.Request.Url.Scheme, this.Request.Url.Host); //CreatePayment function gives us the payment approval url //on which payer is redirected for paypal account payment var createdPayment = this.CreatePayment(apiContext, url, urlCancelPaypal, GetListTransaction(viewModel.Azione, viewModel.Guid)); //get links returned from paypal in response to Create function call 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(viewModel.Guid, createdPayment.id); return(Redirect(paypalRedirectUrl)); } else if (!string.IsNullOrEmpty(viewModel.PayerID) || !string.IsNullOrWhiteSpace(viewModel.Guid)) { // This section is executed when we have received all the payments parameters // from the previous call to the function Create // Executing a payment var executedPayment = ExecutePayment(apiContext, viewModel.PayerID, Session[viewModel.Guid] as string); if (executedPayment.state.ToLower() != "approved") { // redirect errore nell'acquisto TempData["errore"] = "Errore durante l'acquisto"; } else { if (SavePayment(viewModel, executedPayment)) { TempData["Esito"] = App_GlobalResources.Language.JsonBuyAd; TempData["pagamentoEffettuato"] = true; return(Redirect(_UrlFinePagamento)); } else { TempData["errore"] = App_GlobalResources.ErrorResource.AdBuyFailed; } } } } else { TempData["errore"] = "Sessione pagamento scaduta!"; } } catch (Exception ex) { //Logger.log("Error" + ex.Message); LoggatoreModel.Errore(ex); // redirect errore nell'acquisto TempData["errore"] = "Errore grave durante l'acquisto: " + ex.Message; } // mettere qui l'annullo dell'acquisto in modo da tornare indietro if (id != null) { AnnullaPagamento(viewModel.Azione, (int)id); } return(Redirect(urlCancel)); }