private async Task ExistingSubscriptionPaymentSkippedUpdateSubscription(string payPalAgreement) { //get a user with PayPal agreement. var userSubscription = _dbcontext.UserSubscriptions.Where(x => x.PayPalAgreementId == payPalAgreement && !String.IsNullOrEmpty(x.PayPalAgreementId)).FirstOrDefault(); if (userSubscription != null) { //get user subscription var client = _clientFactory.GetClient(); AgreementGetRequest request = new AgreementGetRequest(userSubscription.PayPalAgreementId); BraintreeHttp.HttpResponse result = await client.Execute(request); Agreement agreement = result.Result <Agreement>(); string expiryDateAsString = agreement.AgreementDetails.NextBillingDate.Substring(0, 10); DateTime expiryDate = DateTime.ParseExact(expiryDateAsString, "yyyy-MM-dd", null); userSubscription.ExpiryDate = expiryDate; userSubscription.State = "Cancelled"; _dbcontext.UserSubscriptions.Update(userSubscription); await _dbcontext.SaveChangesAsync(); var userMessage = $"Your subscription for {userSubscription.Description} has been cancelled due to SKIPPED payment. You will have access until {userSubscription.ExpiryDate}."; await EmailCustomer(userSubscription.PayerEmail, userMessage, "AndyTipster subscription has been cancelled due to SKIPPED payment."); var adminMessage = $"Regular Subscription PAYMENT SKIPPED: {userSubscription.PayerFirstName} {userSubscription.PayerLastName} " + $": {userSubscription.PayerEmail} have SKIPPED PAYMENT {userSubscription.Description}. They will have access until : {userSubscription.ExpiryDate}."; await EmailAdmin(adminMessage, "Regular Subscription SKIPPED PAYMENT, Subscription UPDATED."); } }
public async Task <IActionResult> Index() { //get user subscription var client = _clientFactory.GetClient(); AgreementGetRequest request = new AgreementGetRequest("I-GY2WH34CHXR5"); BraintreeHttp.HttpResponse result = await client.Execute(request); Agreement agreement = result.Result <Agreement>(); var payPalCancelSubscription = System.Net.WebRequest.Create("https://api.paypal.com/v1/payments/billing-agreements/I-GY2WH34CHXR5/cancel"); //Set values for the verification request payPalCancelSubscription.Method = "POST"; var response = payPalCancelSubscription.GetResponse(); //await AddEmailtoList("*****@*****.**"); return(View()); }
public async Task <IActionResult> Pay([FromQuery] string attemptId) { var attempt = await this.paymentsService.GetPaymentAttempt(attemptId); var clientId = this.configuration.GetSection("PayPal").GetSection("clientId").Value; var secret = this.configuration.GetSection("PayPal").GetSection("secret").Value; var environment = new SandboxEnvironment(clientId, secret); var client = new PayPalHttpClient(environment); var portocol = this.HttpContext.Request.Scheme; var host = this.HttpContext.Request.Host; var returnUrl = $"{portocol}://{host}/Payments/Execute/{attempt.Id}"; var cancelUrl = $"{portocol}://{host}/Homes/Index"; var payment = new PayPal.v1.Payments.Payment() { Intent = "sale", Transactions = new List <Transaction>() { new Transaction() { Amount = new Amount() { Total = attempt.Price.ToString("G", CultureInfo.InvariantCulture), Currency = "USD", }, }, }, RedirectUrls = new RedirectUrls() { ReturnUrl = returnUrl, CancelUrl = cancelUrl, }, Payer = new Payer() { PaymentMethod = "paypal", }, }; PaymentCreateRequest request = new PaymentCreateRequest(); request.RequestBody(payment); System.Net.HttpStatusCode statusCode; try { BraintreeHttp.HttpResponse response = await client.Execute(request); statusCode = response.StatusCode; Payment result = response.Result <Payment>(); string redirectUrl = null; foreach (LinkDescriptionObject link in result.Links) { if (link.Rel.Equals("approval_url")) { redirectUrl = link.Href; } } if (redirectUrl == null) { return(this.Json("Failed to find an approval_url in the response!")); } else { return(this.Redirect(redirectUrl)); } } catch (BraintreeHttp.HttpException ex) { statusCode = ex.StatusCode; var debugId = ex.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault(); return(this.Json("Request failed! HTTP response code was " + statusCode + ", debug ID was " + debugId)); } }
public async Task <PayPalPaymentCreationResultDto> CreatePayPalPaymentAsync(string amountToPay) { var environment = new SandboxEnvironment(_payPalSettings.ClientId, _payPalSettings.ClientSecret); var client = new PayPalHttpClient(environment); var steamUser = _steamUserService.GetCurrentRequestSteamUser(); var payment = new Payment() { Intent = "sale", Transactions = new List <Transaction>() { new Transaction() { Amount = new Amount() { Total = amountToPay, Currency = "USD" } } }, RedirectUrls = new RedirectUrls() { ReturnUrl = $"{_hostString}/{_multiTenantContext.TenantInfo.Identifier}/payment/ExecutePayPalPayment", CancelUrl = $"{_hostString}/{_multiTenantContext.TenantInfo.Identifier}/payment/PaymentFailed" }, Payer = new Payer() { PaymentMethod = "paypal" }, NoteToPayer = _configuration["BuyerNotes"] }; PaymentCreateRequest paymentCreateRequest = new PaymentCreateRequest(); paymentCreateRequest.RequestBody(payment); _logger.LogInformation($"Preparation for payment creation against PayPal API"); HttpStatusCode responseStatusCode; try { BraintreeHttp.HttpResponse paymentCreateRequestResult = await client.Execute(paymentCreateRequest); _logger.LogInformation($"PayPal payment creation result, {nameof(paymentCreateRequestResult)}: {JsonConvert.SerializeObject(paymentCreateRequestResult)}"); responseStatusCode = paymentCreateRequestResult.StatusCode; if (responseStatusCode != HttpStatusCode.Created) { return(null); } Payment paymentResult = paymentCreateRequestResult.Result <Payment>(); await _payPalCreatedPaymentService.CreateAsync(paymentResult); return(new PayPalPaymentCreationResultDto { State = PaymentCreationResultEnum.Success, PaymentDetails = paymentResult }); } catch (BraintreeHttp.HttpException e) { responseStatusCode = e.StatusCode; var debugId = e.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault(); _logger.LogError(e, $"PayPal payment creation: Failed\nSteamUserID: {steamUser.Id}\nSteamUserUID: {steamUser.Uid}\nDebugId: {debugId}\nStatusCode: {responseStatusCode}"); return(new PayPalPaymentCreationResultDto { State = PaymentCreationResultEnum.Failed, FailedReason = debugId }); } }
public async Task <PayPalPaymentExecuteResultDto> ExecutePayPalPaymentAsync(string paymentId, string token, string payerId) { var environment = new SandboxEnvironment(_payPalSettings.ClientId, _payPalSettings.ClientSecret); var client = new PayPalHttpClient(environment); var steamUser = _steamUserService.GetCurrentRequestSteamUser(); PaymentExecution paymentExecution = new PaymentExecution() { PayerId = payerId }; PaymentExecution payment = new PaymentExecution() { PayerId = payerId }; PaymentExecuteRequest request = new PaymentExecuteRequest(paymentId); request.RequestBody(payment); HttpStatusCode statusCode; Payment paymentExecutionResult = null; _logger.LogInformation($"Preparation for payment execution against PayPal API"); HttpStatusCode responseStatusCode; try { BraintreeHttp.HttpResponse response = await client.Execute(request); statusCode = response.StatusCode; paymentExecutionResult = response.Result <Payment>(); await _payPalExecutedPaymentService.CreateAsync(paymentExecutionResult); _logger.LogInformation($"PayPal payment execution result, {nameof(paymentExecutionResult)}: {JsonConvert.SerializeObject(paymentExecutionResult)}"); } catch (BraintreeHttp.HttpException e) { responseStatusCode = e.StatusCode; var debugId = e.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault(); _logger.LogError(e, $"PayPal payment execution: Failed\nSteamUserID: {steamUser.Id}\nSteamUserUID: {steamUser.Uid}\nDebugId: {debugId}\nStatusCode: {responseStatusCode}"); return(new PayPalPaymentExecuteResultDto { State = PaymentExecutionResultEnum.Failed, FailedReason = debugId }); } if (paymentExecutionResult.State == "approved") { var updateSteamUserShopBalanceResult = await AddFundsToSteamUserShopAsync(paymentExecutionResult); if (!updateSteamUserShopBalanceResult) { return new PayPalPaymentExecuteResultDto { State = PaymentExecutionResultEnum.Failed, FailedReason = "Error on adding funds, please contact support!" } } ; return(new PayPalPaymentExecuteResultDto { State = PaymentExecutionResultEnum.Success, AmountPaid = paymentExecutionResult .Transactions.First() .RelatedResources.First() .Sale.Amount.Total, CurrentBalance = _steamUserService.GetCurrentRequestSteamUserShop().Balance }); } return(new PayPalPaymentExecuteResultDto { State = PaymentExecutionResultEnum.Failed, FailedReason = "Payment has not been approved!" }); }
private async Task CheckUpdateUserSubscriptionDetails(ApplicationUser user) { List <UserSubscriptions> userSubs = _dbContext.UserSubscriptions .Where(x => x.UserId == user.Id && x.PayPalAgreementId != null) .ToList(); if (userSubs.Count() > 0) { List <string> userSubscriptionIds = _dbContext.UserSubscriptions .Where(x => x.UserId == user.Id && x.PayPalAgreementId != null) .Select(x => x.PayPalAgreementId) .ToList(); foreach (var Id in userSubscriptionIds) { //get user subscription var client = _clientFactory.GetClient(); AgreementGetRequest request = new AgreementGetRequest(Id); BraintreeHttp.HttpResponse result = await client.Execute(request); Agreement agreement = result.Result <Agreement>(); //get user subscription UserSubscriptions userExistingSubscription = user.Subscriptions.Where(x => x.PayPalAgreementId == Id).FirstOrDefault(); //first time user is cancelling. if (agreement.State == "Cancelled" && userExistingSubscription.State != "Cancelled") { //if this is the first cancellation. if (userExistingSubscription.ExpiryDate.Year < 1995) { //set expiry date in the User Subscription to the next billing date. //"last_payment_date": "2020-06-15T17:57:02Z", // "next_billing_date": "2020-07-15T10:00:00Z", string expiryDateAsString = agreement.AgreementDetails.NextBillingDate.Substring(0, 10); DateTime expiryDate = DateTime.ParseExact(expiryDateAsString, "yyyy-MM-dd", null); userExistingSubscription.ExpiryDate = expiryDate; //update user subscription status. userExistingSubscription.State = agreement.State; //only send cancellation email when Paypal first sends cancellation confirmation. var cancellationEmailAlreadyBeenSent = _dbContext.UserSubscriptions.Where(x => x.UserId == user.Id && x.PayPalAgreementId == agreement.Id && x.State != "Cancelled").Any(); if (!cancellationEmailAlreadyBeenSent) { //Send user an email and let them know expiry date. var confirmationHtml = $"<h2>As per your request, your Subscription <strong>{userExistingSubscription.Description}</strong> has been cancelled.</h2> <p>However, you can continue enjoy your access till your paid period expired on {userExistingSubscription.ExpiryDate}.</p>"; var sendGridKey = _configuration.GetValue <string>("SendGridApi"); await Emailer.SendEmail(user.Email, "AndyTipster Subscription, has been cancelled", confirmationHtml, sendGridKey); //Send admin an email and let them know expiry date. var confirmationAdminHtml = $"<h2>User {user.Email} has cancelled their subscription for <strong>{userExistingSubscription.Description}</strong>.</h2> <p>However, user has access till their paid period expired on {userExistingSubscription.ExpiryDate}.</p><p>An email confirmation has been sent to user on {user.Email}</p>"; await Emailer.SendEmail("*****@*****.**", "A user has cancelled a Subscription", confirmationAdminHtml, sendGridKey); } } } if (agreement.State == "Cancelled" && userExistingSubscription.State == "Cancelled") { //check if subscription date has expired. if (userExistingSubscription.ExpiryDate < DateTime.Now) // user subs expired, delete their subscription. { //delete Subscription. var subsTobeDeleted = _dbContext.Subscriptions.Where(x => x.PayPalAgreementId == agreement.Id).FirstOrDefault(); if (subsTobeDeleted != null) { _dbContext.Subscriptions.Remove(subsTobeDeleted); } //delete user Subscription var userSubsToBeDeleted = _dbContext.UserSubscriptions.Where(x => x.UserId == user.Id && x.State == "Cancelled" && x.PayPalAgreementId == agreement.Id).FirstOrDefault(); if (userSubsToBeDeleted != null) { _dbContext.UserSubscriptions.Remove(userSubsToBeDeleted); } _dbContext.SaveChanges(); //Send user an email and let them know subscription now has expired. var expiredHtml = $"<h2>Your Subscription <strong>{userExistingSubscription.Description}</strong> has now expired.</h2>"; var sendGridKey = _configuration.GetValue <string>("SendGridApi"); await Emailer.SendEmail(user.Email, "Andy Tipster Subscription has expired.", expiredHtml, sendGridKey); //Send admin an email and let them know expiry. var expiredAdminHtml = $"<h2>User {user.Email} subscription for <strong>{userExistingSubscription.Description}</strong>. has now expired.</h2><p>An email confirmation has been sent to user on {user.Email}</p>"; await Emailer.SendEmail("*****@*****.**", $"{userExistingSubscription.PayerEmail} : Subscription has expired.", expiredAdminHtml, sendGridKey); } } await userManager.UpdateAsync(user); } } }
/// <summary> /// Create the default billing plans for this website /// </summary> private async Task CreatePayPalPlans() { var client = _clientFactory.GetClient(); foreach (var plan in BillingPlanSeed.PayPalPlans("https://www.andytipster.com/Subscription/Return", "https://www.andytipster.com/Subscription/Cancel")) //foreach (var plan in BillingPlanSeed.PayPalPlans("https://localhost:44376/Subscription/Return", "https://localhost:44376/Subscription/Cancel")) { // Create Plan var request = new PlanCreateRequest().RequestBody(plan); BraintreeHttp.HttpResponse result = await client.Execute(request); var obj = result.Result <Plan>(); // Activate Plan var activateRequest = new PlanUpdateRequest <Plan>(obj.Id) .RequestBody(GetActivatePlanBody()); await client.Execute(activateRequest); // Add to database record //var dbPlan = _dbContext.BillingPlans.FirstOrDefault(x => // x.Name == obj.Name); //if (dbPlan != null && string.IsNullOrEmpty(dbPlan.PayPalPlanId)) //{ // dbPlan.PayPalPlanId = obj.Id; // await _dbContext.SaveChangesAsync(); //} } //// Create plans //var justBrowsingPlanRequest = new PlanCreateRequest().RequestBody(justBrowsingPlan); //var justBrowsingPlanResult = await client.Execute(justBrowsingPlanRequest); //var justBrowsingPlanObject = justBrowsingPlanResult.Result<Plan>(); //var letsDoThisPlanRequest = new PlanCreateRequest().RequestBody(letsDoThisPlan); //var letsDoThisPlanResult = await client.Execute(letsDoThisPlanRequest); //var letsDoThisPlanObject = letsDoThisPlanResult.Result<Plan>(); //var beardIncludedPlanRequest = new PlanCreateRequest().RequestBody(beardIncludedPlan); //var beardIncludedPlanResult = await client.Execute(beardIncludedPlanRequest); //var beardIncludedPlanObject = beardIncludedPlanResult.Result<Plan>(); //var hookItToMyVeinsPlanRequest = new PlanCreateRequest().RequestBody(hookItToMyVeinsPlan); //var hookItToMyVeinsPlanResult = await client.Execute(hookItToMyVeinsPlanRequest); //var hookItToMyVeinsPlanObject = hookItToMyVeinsPlanResult.Result<Plan>(); //// Activate plans //var activateJustBrowsingPlanRequest = new PlanUpdateRequest<Plan>(justBrowsingPlanObject.Id) // .RequestBody(GetActivatePlanBody()); //await client.Execute(activateJustBrowsingPlanRequest); //var activateletsDoThisPlanRequest = new PlanUpdateRequest<Plan>(letsDoThisPlanObject.Id) // .RequestBody(GetActivatePlanBody()); //await client.Execute(activateletsDoThisPlanRequest); //var activateBeardIncludedPlanRequest = new PlanUpdateRequest<Plan>(beardIncludedPlanObject.Id) // .RequestBody(GetActivatePlanBody()); //await client.Execute(activateBeardIncludedPlanRequest); //var activateHookItToMyVeinsPlanRequest = new PlanUpdateRequest<Plan>(hookItToMyVeinsPlanObject.Id) // .RequestBody(GetActivatePlanBody()); //await client.Execute(activateHookItToMyVeinsPlanRequest); }
public static string CreatePaymentRequest(string price) { //var environment = new LiveEnvironment("AbsLlwBzsLwTvG-6awsiklgFPeDNWlGctQ9MukFQl-VimUpPwBtTLpR5SX8Wyu0U_R8pg6mGxgrpzYiA", "EIFw-teU8tWyH7UBXgI7UftSXuJoB1aG51jkZMiRb23x39OaTd9kLOcKSVtb6FWK5vj1sSypW1kC9xUB"); var environment = new SandboxEnvironment("ARXuDzN7ArL3ZiTG0_ebn-4u53kqetWWQSkM5UoVk5KZ_ClhTjSueiVJTnDuFvYtf4TnPxxJDRSJryWJ", "EL6FuAA6ocMA6rFtSWg7Ck-mZYMCq4W-G-huZPVsiOIT9zyI9z2Wh_-_Elv9GiiWP00S8fn28I5G-NFm"); var client = new PayPalHttpClient(environment); var payment = new PayPal.v1.Payments.Payment() { Intent = "sale", Transactions = new List <Transaction>() { new Transaction() { Amount = new Amount() { Total = price, Currency = "EUR" } } }, RedirectUrls = new RedirectUrls() { ReturnUrl = "https://localhost:44353/Invoice/InvoiceComplete", //ReturnUrl = "https://www.spartanboosting.com/Invoice/InvoiceComplete", CancelUrl = "https://www.spartanboosting.com" }, Payer = new Payer() { PaymentMethod = "paypal" } }; PaymentCreateRequest request = new PaymentCreateRequest(); request.RequestBody(payment); System.Net.HttpStatusCode statusCode; try { BraintreeHttp.HttpResponse response = client.Execute(request).Result; statusCode = response.StatusCode; Payment result = response.Result <Payment>(); string redirectUrl = null; foreach (LinkDescriptionObject link in result.Links) { if (link.Rel.Equals("approval_url")) { redirectUrl = link.Href; } } if (redirectUrl == null) { // Didn't find an approval_url in response.Links //await context.Response.WriteAsync("Failed to find an approval_url in the response!"); } else { return(redirectUrl); } } catch (BraintreeHttp.HttpException ex) { statusCode = ex.StatusCode; var debugId = ex.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault(); //await context.Response.WriteAsync("Request failed! HTTP response code was " + statusCode + ", debug ID was " + debugId); } return(""); }
public async Task <ActionResult> OrderProducts() {//hier betaling uitvoeren. met id kan hij pas de betaling uitvoeren var o_aanhef = HttpContext.Request.Query["o_aanhef"].ToString(); var o_name = HttpContext.Request.Query["o_name"].ToString(); var o_postal = HttpContext.Request.Query["o_postal"].ToString(); var o_address = HttpContext.Request.Query["o_address"].ToString(); var o_number = HttpContext.Request.Query["o_number"].ToString(); var prijs = HttpContext.Request.Query["prijs"].ToString(); var paymentId = HttpContext.Request.Query["paymentId"].ToString(); var PayerID = HttpContext.Request.Query["PayerID"].ToString(); var environment = new SandboxEnvironment("ATAmdaFGY2Pz6CH83fmdK8OaXu2Wd8b9fLDyuU8X3SNiAzvu2_Ks4IU3wPiNbpE74nWIkhb4jN_7pz9E", "EOksjziNOaGEYh-OroCWTFT_EKDlqJEIpsrZLMtUhmYNxgDZ_v6KGwyL1MFcWJ-dfv97PApRKroAAT0g"); var Pay_client = new PayPalHttpClient(environment); PayPal.v1.Payments.PaymentExecuteRequest request = new PayPal.v1.Payments.PaymentExecuteRequest(paymentId); request.RequestBody(new PayPal.v1.Payments.PaymentExecution() { PayerId = PayerID }); BraintreeHttp.HttpResponse response = await Pay_client.Execute(request); if (o_aanhef == null) { o_aanhef = ""; } var db = new ModelContext(); var UserId = HttpContext.Session.GetInt32("UID"); int?UserIdResult = 0; if (UserId == null) { UserId = HttpContext.Session.GetInt32("SessionAccountId"); UserIdResult = HttpContext.Session.GetInt32("SessionAccountId"); } else { UserIdResult = (from s in db.Account where s.id == UserId select s.id).Single(); } var ShoppingCartResult = from s in db.ShoppingCart where s.AccountId == UserId select s; Console.WriteLine(o_name + o_postal + o_address + o_number); //MaxId //nieuwe bestelling aanmaken int MaxId = 0; var result = from s in db.Order select s.Id; if (!result.Any()) { } else { MaxId = result.Max(); } Order order = new Order { Id = MaxId + 1, AccountId = UserIdResult, Datum = DateTime.Now, Prijs = prijs, OrderStatus = "Verwerkt", }; db.Order.Add(order); db.SaveChanges(); foreach (var item in ShoppingCartResult) { int MaxOrderedProductsId = 0; var resultt = from s in db.OrderedProducts select s.Id; if (!resultt.Any()) { } else { MaxOrderedProductsId = resultt.Max(); } OrderedProducts orderedProducts = new OrderedProducts { Id = MaxOrderedProductsId + 1, OrderId = MaxId + 1, ProductId = item.VoorraadId, Quantity = item.Quantity, }; db.OrderedProducts.Add(orderedProducts); db.SaveChanges(); var voorraad = (from v in db.Voorraad where v.Id == item.VoorraadId select v).ToList(); foreach (var item2 in voorraad) { var NewQuantity = item2.Kwantiteit - item.Quantity; item2.Kwantiteit = NewQuantity; } db.SaveChanges(); } var deleteShoppingCart = (from d in db.ShoppingCart where d.AccountId == UserIdResult select d).ToList(); foreach (var item in deleteShoppingCart) { db.ShoppingCart.Remove(item); db.SaveChanges(); } var check = (from s in db.ShoppingCart where s.AccountId == UserId select s).ToList(); //Bestellingsmail voor Petgoods4All MailMessage mail = new MailMessage(); SmtpClient client = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add("*****@*****.**"); mail.Subject = "Order: " + MaxId + 1; mail.Body = "Order placed from user " + UserId + ".\n"; foreach (var item in check) { var item2 = (from s in db.Voorraad where item.VoorraadId == s.Id select s.Naam).Single(); mail.Body = mail.Body + "Product: " + item2 + "\n"; } mail.Body = mail.Body + "aanhef: " + o_aanhef + "\n" + "adres: " + o_address + "\n" + "postcode: " + o_postal + "\n" + "huisnummer: " + o_number + "\n" + "naam: " + o_name + "\n"; client.Port = 587; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "adminpetgoods4all"); client.EnableSsl = true; client.Send(mail); Console.WriteLine("Mail sent to Petgoods4all"); // Einde Bestellingsmail voor Petgoods4All //Bevestigingsmail besteller string UserEmail = (from s in db.Account where s.id == UserId select s.email).Single(); mail.To.Clear(); mail.To.Add(UserEmail); mail.Subject = "Order: " + MaxId + 1; mail.Body = "Geachte " + o_aanhef + " " + o_name + ", \n" + "Bedankt voor uw bestelling.\n" + "De producten komen uw kant op.\n" + "adres:" + o_address + "\n" + "postcode: " + o_postal + "\n" + "Huisnummer: " + o_number + "\n" + "Veel dierenplezier met de producten!\n Met vriendelijke groeten,\n\n Petgoods4All"; client.Port = 587; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "adminpetgoods4all"); client.EnableSsl = true; client.Send(mail); Console.WriteLine("KlantMail sent "); var AnonymousUser = HttpContext.Session.GetInt32("SessionAccountId"); if (AnonymousUser == null) { return(OrderHistory()); } else { //var delUser = (from s in db.Account where s.id == UserId select s).Single(); //db.Account.Remove(delUser); //db.SaveChanges(); int?randomAccountIdSum; var AccountResult = from r in db.Account select r.id; HttpContext.Session.Remove("SessionAccountId"); if (AccountResult == null) { randomAccountIdSum = AccountResult.Max() + 1; } else { randomAccountIdSum = 1; } int randomAccountId = randomAccountIdSum.GetValueOrDefault(1); HttpContext.Session.SetInt32("SessionAccountId", randomAccountId); return(Redirect("http://localhost:56003/Order/Bedankt")); } }
public async Task <ActionResult> Pay(string prijs, string o_email = "", string o_name = "", string o_postal = "", string o_address = "", string o_number = "") { var db = new ModelContext(); //if userId null "UserId = HttpContext.Session.GetInt32("SessionAccountId");" en de user zelf zijn data laten invullen var UserId = HttpContext.Session.GetInt32("UID"); o_email = o_email.Replace(" ", "_"); o_postal = o_postal.Replace(" ", "_"); o_address = o_address.Replace(" ", "_"); o_number = o_number.Replace(" ", "_"); if (UserId == null) { var checkEmail = (from s in db.Account where s.email == o_email select s.email).Any(); if (checkEmail == true) { var getEmail = (from s in db.Account where s.email == o_email select s).Single(); HttpContext.Session.SetInt32("SessionAccountId", getEmail.id); db.Account.Remove(getEmail); db.SaveChanges(); } UserId = HttpContext.Session.GetInt32("SessionAccountId"); Account a = new Account { id = UserId.GetValueOrDefault(0), email = o_email, password = "", voornaam = "", achternaam = o_name, straatnaam = o_address, huisnummer = o_number, postcode = o_postal, provincie = "", telefoonnummer = null, IsUnregistered = true }; db.Account.Add(a); db.SaveChanges(); } int UserIdResult = (from s in db.Account where s.id == UserId select s.id).Single(); o_name = (from s in db.Account where s.id == UserIdResult select s.achternaam).Single(); o_postal = (from s in db.Account where s.id == UserIdResult select s.postcode).Single(); o_address = (from s in db.Account where s.id == UserIdResult select s.straatnaam).Single(); o_number = (from s in db.Account where s.id == UserIdResult select s.huisnummer).Single(); o_name = o_name.Replace(" ", "_"); o_postal = o_postal.Replace(" ", "_"); o_address = o_address.Replace(" ", "_"); o_number = o_number.Replace(" ", "_"); // string o_aanhef, string o_name, string o_postal, string o_address, string o_number var environment = new SandboxEnvironment("ATAmdaFGY2Pz6CH83fmdK8OaXu2Wd8b9fLDyuU8X3SNiAzvu2_Ks4IU3wPiNbpE74nWIkhb4jN_7pz9E", "EOksjziNOaGEYh-OroCWTFT_EKDlqJEIpsrZLMtUhmYNxgDZ_v6KGwyL1MFcWJ-dfv97PApRKroAAT0g"); var Pay_client = new PayPalHttpClient(environment); Console.WriteLine("Prijs:" + prijs); var payment = new PayPal.v1.Payments.Payment() { Intent = "sale", Transactions = new List <PayPal.v1.Payments.Transaction>() { new PayPal.v1.Payments.Transaction() { Amount = new PayPal.v1.Payments.Amount() { Total = prijs, Currency = "EUR", Details = new PayPal.v1.Payments.AmountDetails() { Subtotal = prijs } }, ItemList = new PayPal.v1.Payments.ItemList() { Items = new List <PayPal.v1.Payments.Item>() { new PayPal.v1.Payments.Item() { Name = "Petgoods4All Products", Currency = "EUR", Price = prijs, Quantity = "1", Description = "Bedankt voor uw aankoop" } } } , Description = "Betaling Petgoods4All" } }, RedirectUrls = new PayPal.v1.Payments.RedirectUrls() { CancelUrl = "http://localhost:56003/", ReturnUrl = "http://localhost:56003/Order/OrderProducts?prijs=" + prijs + "&o_aanhef=" + "DHR/MVR." + "&o_name=" + o_name + "&o_postal=" + o_postal + "&o_address=" + o_address + "&o_number=" + o_number }, Payer = new PayPal.v1.Payments.Payer() { PaymentMethod = "paypal" } }; PayPal.v1.Payments.PaymentCreateRequest request = new PayPal.v1.Payments.PaymentCreateRequest(); request.RequestBody(payment); System.Net.HttpStatusCode statusCode; try { BraintreeHttp.HttpResponse httpResponse = await Pay_client.Execute(request); BraintreeHttp.HttpResponse response = httpResponse; statusCode = response.StatusCode; PayPal.v1.Payments.Payment result = response.Result <PayPal.v1.Payments.Payment>(); string redirectUrl = null; foreach (PayPal.v1.Payments.LinkDescriptionObject link in result.Links) { if (link.Rel.Equals("approval_url")) { redirectUrl = link.Href; Console.WriteLine(redirectUrl); return(Redirect(redirectUrl)); } } } catch (BraintreeHttp.HttpException httpException) { statusCode = httpException.StatusCode; var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault(); Console.WriteLine("Paypal_error: " + debugId + statusCode); return(Redirect("http://localhost:56003/")); } return(Redirect("http://localhost:56003/")); }
public async Task <string> ProcessPayment(PayPalTestViewModel model) { var environment = new SandboxEnvironment(_configuration["PayPal:SandBox:ClientId"], _configuration["PayPal:SandBox:ClientSecret"]); var client = new PayPalHttpClient(environment); var payment = new PayPal.v1.Payments.Payment() { Intent = "sale", Transactions = new List <Transaction>() { new Transaction() { Amount = new Amount() { Total = model.Amount, Currency = "INR" } } }, RedirectUrls = new RedirectUrls() { ReturnUrl = _urlHelper.Action("Done", "Test", new { amt = model.Amount }, _context.HttpContext.Request.Scheme, _context.HttpContext.Request.Host.ToString()), CancelUrl = _urlHelper.Action("Cancel", "Test", new { amt = model.Amount }, _context.HttpContext.Request.Scheme, _context.HttpContext.Request.Host.ToString()) }, Payer = new Payer() { PaymentMethod = "paypal" } }; PaymentCreateRequest request = new PaymentCreateRequest(); request.RequestBody(payment); System.Net.HttpStatusCode statusCode; BraintreeHttp.HttpResponse response = await client.Execute(request); statusCode = response.StatusCode; Payment result = response.Result <Payment>(); string redirectUrl = null; foreach (LinkDescriptionObject link in result.Links) { if (link.Rel.Equals("approval_url")) { redirectUrl = link.Href; } } if (redirectUrl == null) { // Didn't find an approval_url in response.Links return(null); } else { return(redirectUrl); } }