See PayPal Developer documentation for more information.
public ActionResult PaymentWithPayPal(string donationAmt) { //OAuthTokenCredential tokenCredential = new OAuthTokenCredential("AeJs4Inwk1Pn8ZNhkWiSLwerx4K64E1PD5TtL4FF7XImtEZ29aAWBTxYOVIBWxEXlW6FycnBz3U7J8jQ", "ENerw7v3F1YT1w5YRYHRPCbjfVSpAbvHVTJFfqc0jWPyeq8hcgmvaZn-1T1WzklDVqw7Pd7MGp3KEQXO"); //string accessToken = tokenCredential.GetAccessToken(); // Get a reference to the config var config = ConfigManager.Instance.GetProperties(); // Use OAuthTokenCredential to request an access token from PayPal var accessToken = new OAuthTokenCredential(config).GetAccessToken(); var apiContext = new APIContext(accessToken); try { string payerId = Request.Params["PayerID"]; Payment payment = null; if (string.IsNullOrEmpty(payerId)) { // ###Items // Items within a transaction. Item item = new Item(); item.name = "Item Name"; item.currency = "USD"; item.price = donationAmt; item.quantity = "1"; 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 + "/Donations/DonationSuccessView?"; // # 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 = "0"; details.shipping = "0"; details.subtotal = donationAmt; // ###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 = donationAmt + ".00"; 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 = "Donation"; 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` payment = new Payment(); payment.intent = "sale"; payment.payer = payr; payment.transactions = transactionList; payment.redirect_urls = redirUrls; var createdPayment = payment.Create(apiContext); string paypalRedirectUrl = null; var links = createdPayment.links.GetEnumerator(); 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 { var guid = Request.Params["guid"]; var paymentId = Session[guid] as string; var paymentExecution = new PaymentExecution() { payer_id = payerId }; var pymnt = new Payment() { id = paymentId }; var executedPayment = pymnt.Execute(apiContext, paymentExecution); } } catch (Exception e) { string error = e.ToString(); return View("DonationFailureView"); } return View("DonationSuccessView"); }
protected override void RunSample() { // ### Api Context // Pass in a `APIContext` object to authenticate // the call and to send a unique request id // (that ensures idempotency). The SDK generates // a request id if you do not pass one explicitly. // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext. var apiContext = Configuration.GetAPIContext(); string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` var payer = new Payer() { payment_method = "paypal" }; // # Redirect URLS string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/OrderSample.aspx?"; 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 }; // ###Amount // Lets you specify a payment amount. var amount = new Amount() { currency = "USD", total = "5.00" }; // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List<Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new Transaction() { description = "Transaction description.", amount = amount }); // ###Payment // Create a payment with the intent set to 'order' var payment = new Payment() { intent = "order", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // ^ Ignore workflow code segment #region Track Workflow flow.AddNewRequest("Create payment order", payment); #endregion // Create the payment resource. var createdPayment = payment.Create(apiContext); // ^ Ignore workflow code segment #region Track Workflow flow.RecordResponse(createdPayment); #endregion // Use the `approval_url` link provided by the returned object to approve the order payment. var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { this.flow.RecordRedirectUrl("Redirect to PayPal to approve the order...", link.href); } } Session.Add("flow-" + guid, this.flow); Session.Add(guid, createdPayment.id); } else { var guid = Request.Params["guid"]; // ^ Ignore workflow code segment #region Track Workflow this.flow = Session["flow-" + guid] as RequestFlow; this.RegisterSampleRequestFlow(); this.flow.RecordApproval("Order payment approved successfully."); #endregion // Execute the order var paymentId = Session[guid] as string; var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new Payment() { id = paymentId }; // ^ Ignore workflow code segment #region Track Workflow flow.AddNewRequest("Execute payment", payment); #endregion // Execute the order payment. var executedPayment = payment.Execute(apiContext, paymentExecution); // ^ Ignore workflow code segment #region Track Workflow flow.RecordResponse(executedPayment); #endregion // Get the information about the executed order from the returned payment object. this.order = executedPayment.transactions[0].related_resources[0].order; this.amount = executedPayment.transactions[0].amount; // Once the order has been executed, an order ID is returned that can be used // to do one of the following: // this.AuthorizeOrder(); // this.CaptureOrder(); // this.VoidOrder(); // this.RefundOrder(); // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/). } }
public static Amount CreatePayPalAmount(double pytAmount, Details details) { Amount amount = new Amount() { currency = "GBP", total = pytAmount.ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; return amount; }
public Transaction CreateTransaction(string txDescription, Amount txAmount, List<Item> txItems) { return new Transaction() { description = txDescription, amount = txAmount, item_list = new ItemList() { items = txItems } }; }
public static List<Transaction> CreatePayPalAmount(Amount payPalAmount, ItemList itemList, string guid) { List<Transaction> transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "Transaction description.", invoice_number = guid, // "your invoice number: " + timestamp, amount = payPalAmount, item_list = itemList }); return transactionList; }
protected void Run() { var apiContext = Configuration.GetAPIContext(); string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } }; var payer = new Payer() { payment_method = "paypal" }; // Redirect URLS var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Default.aspx?"; 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() { tax = "15", shipping = "10", subtotal = "75" }; var amount = new Amount() { currency = "USD", total = "100.00", details = details }; var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "Transaction description.", invoice_number = Common.GetRandomInvoiceNumber(), amount = amount, item_list = itemList }); var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; #region Track Workflow this.Flow.AddNewRequest("Create PayPal payment", payment); #endregion var createdPayment = payment.Create(apiContext); #region Track Workflow this.Flow.RecordResponse(createdPayment); #endregion var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { this.Flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href); } } Session.Add(guid, createdPayment.id); Session.Add("flow-" + guid, this.Flow); }; }
private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl) { Payer payer = new Payer() { payment_method = "paypal" }; var amount = new Amount() { currency = "USD", total = "100", details = new Details() { tax = "15", shipping = "10", subtotal = "75" } }; var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; var itemList = new ItemList() { items = new List<Item>() }; itemList.items.Add(new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" }); var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "Transaction description.", amount = amount, item_list = itemList }); var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters(); authorizationCodeParameters.setClientId(Configuration.ClientId); authorizationCodeParameters.setClientSecret(Configuration.ClientSecret); authorizationCodeParameters.SetCode(authorizationCode); var apiContext = Configuration.GetAPIContext(); var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters); var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token); var futurePaymentApiContext = Configuration.GetAPIContext(accessToken); var futurePayment = new FuturePayment() { intent = "authorize", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return futurePayment.Create(futurePaymentApiContext, correlationId); }
private Amount CreateAmount(GroveCM.Models.Order order) { var details = new Details { subtotal = order.SubTotal.ToString("0.00", CultureInfo.CurrentCulture), shipping = order.Shipping.ToString("0.00", CultureInfo.CurrentCulture), tax = order.Tax.ToString("0.00", CultureInfo.CurrentCulture), //fee = order.Fees.ToString("0.00", CultureInfo.CurrentCulture) }; var total = order.SubTotal + order.Shipping + order.Tax; //+ order.Fees; var amount = new Amount { currency = "GBP", details = details, total = total.ToString("0.00", CultureInfo.CurrentCulture) }; return amount; }
/// <summary> /// Create and return new Payment /// </summary> /// <param name="cart">user Cart</param> /// <param name="baseUrl">base uri of Requst</param> /// <returns>created Payment</returns> public string GetPayment(Cart cart, string baseUrl) { if (cart == null) { throw new ArgumentNullException(Resources.NullOrEmptyValue, nameof(cart)); } if (cart.ContentCartDtoCollection == null || (cart.ContentCartDtoCollection.Count() <= 0)) { throw new EmptyCartException(Resources.CountContentInCartIsNull); } if (cart.PriceAllItemsCollection != cart.ContentCartDtoCollection.Sum <ContentCartDto>(x => x.PriceItem) || cart.PriceAllItemsCollection <= 0) { throw new ContentCartPriceException(Resources.InvaliContentCartValueOfPrice); } var config = Configuration.GetConfig(); var accessToken = new OAuthTokenCredential(config).GetAccessToken(); var apiContext = new APIContext(accessToken); string payerId = "payerId"; // Request.Params["PayerID"]; // ###Items // Items within a transaction. var itemList = new PayPal.Api.ItemList(); itemList.items = this.GetItemList(cart.ContentCartDtoCollection); // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` var payer = new PayPal.Api.Payer() { payment_method = "paypal" }; // ###Redirect URLS // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. var redirUrls = this.GetRedirectUrls(baseUrl); // ###Details // Let's you specify details of a payment amount. var tax = this.GetTax(cart.PriceAllItemsCollection); var details = new PayPal.Api.Details() { tax = decimal.Round(tax, 2).ToString(CultureInfo.CreateSpecificCulture("en-US")), shipping = "0", subtotal = decimal.Round(cart.PriceAllItemsCollection, 2).ToString(CultureInfo.CreateSpecificCulture("en-US")) }; // ###Amount // Let's you specify a payment amount. var amount = new PayPal.Api.Amount() { currency = "USD", total = decimal.Round(cart.PriceAllItemsCollection + tax, 2).ToString(CultureInfo.CreateSpecificCulture("en-US")), // Total must be equal to sum of shipping, tax and subtotal. details = details }; // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List <PayPal.Api.Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new PayPal.Api.Transaction() { description = "Payd contents.", invoice_number = new System.Random().Next(999999).ToString(), // Get id number transaction amount = amount, item_list = itemList }); // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new PayPal.Api.Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a valid APIContext var createdPayment = payment.Create(apiContext); // return Redirect(createdPayment.GetApprovalUrl(true)); return(createdPayment.GetApprovalUrl(true)); }
public void AuthroizationReauthorizeTest() { var authorization = Authorization.Get(TestingUtil.GetApiContext(), "7GH53639GA425732B"); var reauthorizeAmount = new Amount(); reauthorizeAmount.currency = "USD"; reauthorizeAmount.total = "1"; authorization.amount = reauthorizeAmount; TestingUtil.AssertThrownException<PayPal.PaymentsException>(() => authorization.Reauthorize(TestingUtil.GetApiContext())); }
//**************** //TO DO - remove common functions to separate class private Payment CreatePayment(APIContext apiContext, string redirectUrl, double pytAmount, string guid) { var itemList = new ItemList() { items = new List<Item>() }; itemList.items.Add(new Item() { name = "Item Name", currency = "GBP", price = pytAmount.ToString(), quantity = "1", sku = "sku" }); var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; var details = new Details() { tax = "0", shipping = "0", subtotal = pytAmount.ToString() }; var amount = new Amount() { currency = "GBP", total = pytAmount.ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture); var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "Transaction description.", invoice_number = guid, // "your invoice number: " + timestamp, amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
private Payment CreatePaymentInternal(APIContext apiContext, string redirectUrl, double amountValue) { var amountStringValue = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", amountValue); var invoiceNumber = Convert.ToString((new Random()).Next(100000)); //similar to credit card create itemlist and add item objects to it var itemList = new ItemList { items = new List<Item>() }; itemList.items.Add(new Item { name = "Socialforce credit amount", currency = "USD", price = amountStringValue, quantity = "1", sku = "sku" }); var payer = new Payer { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls { cancel_url = redirectUrl, return_url = redirectUrl }; // similar as we did for credit card, do here and create details object //var details = new Details //{ // subtotal = amountValue.ToString(CultureInfo.InvariantCulture) //}; // similar as we did for credit card, do here and create amount object var amount = new Amount { currency = "USD", total = amountStringValue, // Total must be equal to sum of shipping, tax and subtotal. //details = details }; var transactionList = new List<Transaction>(); transactionList.Add(new Transaction { description = "Gigbucket credit amount", invoice_number = invoiceNumber, amount = amount, item_list = itemList }); var payment = new Payment { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return payment.Create(apiContext); }
public PayPal.Api.Payment GetPayment (Booking booking ) { // var panier = await GetActivePanier(true); //var titres = panier.PanierAlbums.SelectMany(x => x.Titres).Select(x => new Item { name = x.Nom, currency = "EUR", price = x.Prix.ToString(), quantity = "1" }); //var total = panier.PanierAlbums.Sum(x => x.Total); var item = new Item() { name = string.Format("Reserva de Cancha {0} " , booking.Field.Name), currency ="USD", quantity ="1", price = booking.Price.ToString(), }; //configuracion de paypal APIContext api = getPaypalContext(); List<Item> items = new List<Item>(); items.Add(item); ItemList itemList = new ItemList(); itemList.items = items; Amount amnt = new Amount(); amnt.currency = "USD"; amnt.total = booking.Price.ToString(); List<Transaction> transactionList = new List<Transaction>(); Transaction tran = new Transaction(); //tran.description = "creating a payment"; tran.amount = amnt; tran.item_list = itemList; transactionList.Add(tran); Payer payr = new Payer(); payr.payment_method = "paypal"; RedirectUrls redirUrls = new RedirectUrls(); redirUrls.cancel_url = cancel_url; redirUrls.return_url = return_url; PayPal.Api.Payment pymnt = new PayPal.Api.Payment(); pymnt.intent = "sale"; pymnt.payer = payr; pymnt.transactions = transactionList; pymnt.redirect_urls = redirUrls; var payment = pymnt.Create(api); if (pymnt != null) { //panier.paymentId = payment.id; //await SaveAsync(); } return payment; }
private Payment CreatePayment(APIContext apiContext, string returnUrl, string cancelUrl, Models.Transaction t) { //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List<PayPal.Api.Item>() }; decimal tax = 0, shipping = 0; decimal t_subtotes = 0; List<CartItemViewModel> l_civm = (List<CartItemViewModel>)Session["Cart"]; /* Insert Transaction To Database; Set Status to 1 (NotPaid) Make sure to create TransactionItems */ foreach (CartItemViewModel civm in l_civm) { TransactionItem ti = new TransactionItem(); ti.transaction_id = t.id; ti.item_name = civm.name; ti.item_price = civm.price; ti.quantity = civm.quantity; db.TransactionItems.Add(ti); itemList.items.Add(new PayPal.Api.Item() { name = civm.name, currency = "USD", price = Math.Round(civm.price, 2).ToString(), quantity = civm.quantity.ToString(), sku = civm.id.ToString() }); t_subtotes += civm.price * civm.quantity; // similar as we did for credit card, do here and create details object } var totes = tax + shipping + t_subtotes; var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = cancelUrl, return_url = returnUrl }; var details = new Details() { tax = Math.Round(tax, 2).ToString(), shipping = Math.Round(shipping, 2).ToString(), subtotal = Math.Round(t_subtotes, 2).ToString() }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = Math.Round(totes, 2).ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List<PayPal.Api.Transaction>(); transactionList.Add(new PayPal.Api.Transaction() { description = "Transaction description.", invoice_number = Session["User"].ToString() + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"), amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
public ActionResult PaymentWithCreditCard(Bids bid) { ApplicationUser currentUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId()); #region Item Info Item item = new Item(); item.name = bid.bidStake.ToString() + "% stake in " + bid.ventureID; item.currency = "USD"; item.price = bid.bid.ToString(); item.quantity = "1"; item.sku = bid.ventureID.ToString(); List<Item> itms = new List<Item>(); itms.Add(item); ItemList itemList = new ItemList(); itemList.items = itms; #endregion #region Billing Info Address billingAddress = new Address(); //billingAddress.city = currentUser.City; //billingAddress.country_code = currentUser.CountryCode; //billingAddress.line1 = currentUser.AddressLine1; //billingAddress.postal_code = currentUser.ZipCode; //billingAddress.state = currentUser.State; #endregion #region Credit Card CreditCard crdtCard = new CreditCard(); crdtCard.billing_address = billingAddress; //crdtCard.cvv2 = currentUser.CCV2; //crdtCard.expire_month = currentUser.CCExpireMonth; //crdtCard.expire_year = currentUser.CCExpireYear; //crdtCard.first_name = currentUser.FirstName; //crdtCard.last_name = currentUser.LastName; //crdtCard.number = currentUser.CCNumber; //crdtCard.type = currentUser.CCType; //paypal allows 4 types #endregion #region Transaction Details Details details = new Details(); details.shipping = "0"; details.subtotal = bid.bid.ToString(); details.tax = "0"; Amount amnt = new Amount(); amnt.currency = "USD"; amnt.total = details.subtotal; amnt.details = details; Transaction tran = new Transaction(); tran.amount = amnt; tran.description = bid.createdOn.ToString(); tran.item_list = itemList; tran.invoice_number = bid.Id.ToString(); #endregion #region Payment List<Transaction> transactions = new List<Transaction>(); transactions.Add(tran); FundingInstrument fundInstrument = new FundingInstrument(); fundInstrument.credit_card = crdtCard; List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>(); fundingInstrumentList.Add(fundInstrument); Payer payer = new Payer(); payer.funding_instruments = fundingInstrumentList; payer.payment_method = "credit_card"; // finally create the payment object and assign the payer object & transaction list to it Payment payment = new Payment(); payment.intent = "sale"; payment.payer = payer; payment.transactions = transactions; try { APIContext apiContext = Configuration.GetAPIContext(); Payment createdPayment = payment.Create(apiContext); if (createdPayment.state.ToLower() != "approved") { return View("FailureView"); } } catch (PayPal.PayPalException ex) { Logger.Log("Error: " + ex.Message); return View("FailureView"); } return View("SuccessView"); }
private Payment CreatePayment(APIContext apiContext, string redirectUrl) { //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List<Item>() }; SqlConnection sqlConnection1; DataSet resultSet; gettheTableData(out sqlConnection1, out resultSet); sqlConnection1.Close(); var FaceID = resultSet.Tables[0].Rows[0].ItemArray.ToArray()[13].ToString(); var itemPaid = db.userPaids.First(u => u.FBID == FaceID); itemList.items.Add(new Item() { name = itemPaid.party.name.ToString(), currency = "USD", price = itemPaid.ammount.ToString(), quantity = "1", sku = "sku" }); var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; var tax = itemPaid.ammount * .1m; // similar as we did for credit card, do here and create details object var details = new Details() { tax = tax.ToString("0.00###"), shipping = "1.00", subtotal = (itemPaid.ammount).ToString() }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = (itemPaid.ammount +1 + tax).ToString("0.00###"), // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "hackargin.", invoice_number = "your invoice gfdgnumber", amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
private Payment CreatePayment(IOrder order, string paymentType, string redirectUrl, CardDetails cardDetails) { //Create items for which you are taking payment var items = order.OrderDetails.GetList().Select(product => new Item { name = product.Name, currency = "GBP", price = product.Price.ToString(CultureInfo.InvariantCulture), quantity = product.Quantity.ToString(CultureInfo.InvariantCulture), sku = product.Category }).ToList(); // Create ItemList object var itemList = new ItemList { items = items }; // Specify the details of your payment amount. var subtotal = order.GetProductCost() - order.GetVat(); var details = new Details { shipping = order.DeliveryCharges.ToString(CultureInfo.InvariantCulture), subtotal = subtotal.ToString(CultureInfo.InvariantCulture), tax = order.GetVat().ToString(CultureInfo.InvariantCulture) }; // Specify your total payment amount and assign the details object var totalCost = order.GetProductCost() + order.DeliveryCharges; var amount = new Amount { currency = "GBP", total = totalCost.ToString(CultureInfo.InvariantCulture), //details = details }; // Now add transactions var transactions = new List<Transaction> { new Transaction { amount = amount, description = string.Format("Total amount = £{0}", order.GetProductCost() + order.DeliveryCharges), //item_list = itemList, //invoice_number = order.OrderNumber.ToString(CultureInfo.InvariantCulture) } }; Payer payer; if (paymentType.Equals("payPal", StringComparison.OrdinalIgnoreCase)) { payer = new Payer { payment_method = "paypal" }; } else { //Address for the payment var billingAddress = new Address { country_code = "GB", line1 = cardDetails.Address, postal_code = cardDetails.Postcode, city = cardDetails.City }; //Now Create an object of credit card and add above details to it var creditCard = new CreditCard { billing_address = billingAddress, cvv2 = cardDetails.CardVerificationCode.GetValueOrDefault().ToString(CultureInfo.InvariantCulture), expire_month = cardDetails.ExpirationMonth.GetValueOrDefault(), expire_year = cardDetails.ExpirationYear.GetValueOrDefault(), first_name = cardDetails.FirstName, last_name = cardDetails.LastName, number = cardDetails.CardNumber.GetValueOrDefault().ToString(CultureInfo.InvariantCulture), type = cardDetails.CardType.ToLower() }; // Now we need to create the FundingInstrument object of the Payer // for credit card payments, set the CreditCard which we made above var fundInstrument = new FundingInstrument { credit_card = creditCard }; // The Payment creation API requires a list of FundingIntrument var fundingInstrumentList = new List<FundingInstrument> { fundInstrument }; // Now create Payer object and assign the fundinginstrument list to the object payer = new Payer { funding_instruments = fundingInstrumentList, payment_method = "credit_card" }; } // Finally we need create the payment object and assign the payer object & transaction list to it var payment = new Payment { intent = "sale", payer = payer, transactions = transactions }; if (!string.IsNullOrEmpty(redirectUrl)) { var redirUrls = new RedirectUrls { cancel_url = redirectUrl, return_url = redirectUrl }; payment.redirect_urls = redirUrls; } return payment; }
public ActionResult Payment(Models.Payment model) { var apiContext = Configuration.GetAPIContext(); try { string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { // ###Items // Items within a transaction. var itemList = new PayPal.Api.ItemList() { items = new List<Item>() { new Item() { name = "Mezo Experts", currency = "USD", price = model.Amount.ToString(), quantity = "1", sku = "sku" } } }; // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` var payer = new PayPal.Api.Payer() { payment_method = "paypal" }; // ###Redirect URLS // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Students/AccountSettings?"; 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 }; // ###Details // Let's you specify details of a payment amount. var details = new PayPal.Api.Details() { tax = "0", shipping = "0", subtotal = model.Amount.ToString() }; // ###Amount // Let's you specify a payment amount. var amount = new PayPal.Api.Amount() { currency = "USD", total = model.Amount.ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List<PayPal.Api.Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new PayPal.Api.Transaction() { description = "Mezo Experts Services", invoice_number = Common.GetRandomInvoiceNumber(), amount = amount, item_list = itemList }); // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new PayPal.Api.Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls, }; // Create a payment using a valid APIContext 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); PaypalPayments payments = new PaypalPayments(); payments.amount = model.Amount.ToString(); payments.ID = Guid.NewGuid(); payments.status = Status.Offered; payments.paymentId = createdPayment.id; payments.token = createdPayment.token; payments.guid = guid; payments.UserId = new Guid(User.Identity.GetUserId()); db.payments.Add(payments); db.SaveChanges(); return Redirect(paypalRedirectUrl); } return null; } catch (Exception ex) { return View("FailureView"); } // return Json(new { result = createdPayment.links[0].href, redirect = createdPayment.links[1].href, execute = createdPayment.links[2].href }); return null; }
public ActionResult Payment(Models.Payment model) { //Dictionary<string, string> payPalConfig = new Dictionary<string, string>(); //payPalConfig.Add("mode", "sandbox"); //OAuthTokenCredential tokenCredential = new AuthTokenCredential("AXVrBytGm6RdmOYfcUFM-VoOa8TvQhVYN6-TapoUzU2oErEpO0XzbYn8qD26R3iFduECZqOQmB78bZbS", "EGz3u0h-poL7i3MbLUQQXgqiYPEbbdzX95h57JzlnKrjKRV1-MNLPApqgKt30Y7VWmgwb5UxFWja0__2", payPalConfig); //string accessToken = tokenCredential.GetAccessToken(); var apiContext = Configuration.GetAPIContext(); try { string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { // ###Items // Items within a transaction. var itemList = new PayPal.Api.ItemList() { items = new List<Item>() { new Item() { name = "Mezo Experts", currency = "USD", price = model.Amount.ToString(), quantity = "1", sku = "sku" } } }; // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` var payer = new PayPal.Api.Payer() { payment_method = "paypal" }; // ###Redirect URLS // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Tutors/AccountSettings?"; 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 }; // ###Details // Let's you specify details of a payment amount. var details = new PayPal.Api.Details() { tax = "0", shipping = "0", subtotal = model.Amount.ToString() }; // ###Amount // Let's you specify a payment amount. var amount = new PayPal.Api.Amount() { currency = "USD", total = model.Amount.ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List<PayPal.Api.Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new PayPal.Api.Transaction() { description = "Mezo Experts Services", invoice_number = Common.GetRandomInvoiceNumber(), amount = amount, item_list = itemList }); // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new PayPal.Api.Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls, }; // Create a payment using a valid APIContext 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); } return null; } catch (Exception ex) { return View("FailureView"); } // return Json(new { result = createdPayment.links[0].href, redirect = createdPayment.links[1].href, execute = createdPayment.links[2].href }); return null; }
private List<Transaction> BuildTransactions(DexCMS.Tickets.Orders.Models.Order order) { var details = new Details { shipping = "0.00", tax = "0.00", subtotal = order.OrderTotal.ToString() }; var amount = new Amount { currency = "USD", details = details, total = order.OrderTotal.ToString() }; var itemList = new ItemList() { items = new List<Item>() }; foreach (var ticket in order.Tickets) { itemList.items.Add(new Item { name = GetTicketName(ticket), currency = "USD", price = ticket.TicketTotalPrice.ToString(), quantity = "1", sku = ticket.TicketID.ToString() }); } var transaction = new Transaction { amount = amount, description = string.Format("Order #{0} purchased from {1}", order.OrderID, SiteSettings.Resolve.GetSetting("SiteTitle")), item_list = itemList, invoice_number = order.OrderID.ToString() }; var transactions = new List<Transaction> { transaction }; return transactions; }
private Payment CreatePayment(APIContext apiContext, string redirectUrl) { //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List<Item>() }; itemList.items.Add(new Item() { name = "Item Name", currency = "EUR", price = "150", quantity = "1", sku = "sku" }); var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; // similar as we did for credit card, do here and create details object var details = new Details() { tax = "27", shipping = "1", subtotal = "150" }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "EUR", total = "178", // 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 = "your invoice number", amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
private Payment CreatePayment(APIContext apiContext, string redirectUrl, int orderId) { //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List<Item>() }; foreach (FunOrderDetail od in dbmeals.FunOrderDetails.Where(x => x.OrderID == orderId)) { itemList.items.Add(new Item() { name = od.Description, currency = "USD", price = String.Format("{0:0}", od.Price),//.ToString(), quantity = (od.Quantity).ToString(), sku = od.ID.ToString() }); } var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; // similar as we did for credit card, do here and create details object var details = new Details() { tax = "0", shipping = "0", subtotal = String.Format("{0:0}", dbmeals.FunOrderDetails.Where(x => x.OrderID == orderId).Sum(x => (x.Price * x.Quantity))) }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = details.subtotal, // 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 = orderId.ToString(), amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
public bool CreatePayment(string priceStr, string description) { try { // Authenticate with PayPal var config = ConfigManager.Instance.GetProperties(); var accessToken = new OAuthTokenCredential(config).GetAccessToken(); apiContext = new APIContext(accessToken); var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "PrintAhead print", currency = "USD", price = priceStr, quantity = "1", sku = "sku" } } }; var payer = new Payer() { payment_method = "paypal" }; var redirUrls = new RedirectUrls() { cancel_url = "http://www.abalonellc.com/hairshop-10-coming-so10.html", return_url = "http://www.abalonellc.com/" }; var details = new Details() { tax = "0", shipping = "0", subtotal = priceStr }; var amount = new Amount() { currency = "USD", total = priceStr, // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List<Transaction> { new Transaction() { description = description, // transaction description invoice_number = GetRandomInvoiceNumber(), amount = amount, item_list = itemList } }; var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; createdPayment = payment.Create(apiContext); var links = createdPayment.links.GetEnumerator(); var hasGoodLink = false; while (links.MoveNext()) { var link = links.Current; if (link != null && link.rel.ToLower().Trim().Equals("approval_url")) { chromeBrowser.Load(link.href); hasGoodLink = true; break; } } if (!hasGoodLink) return false; } catch (PaymentsException ex) { // Get the details of this exception with ex.Details. If you have logging setup for your project, this information will also be automatically logged to your logfile. var sb = new StringBuilder(); sb.AppendLine("Error: " + ex.Details.name); sb.AppendLine("Message: " + ex.Details.message); sb.AppendLine("URI: " + ex.Details.information_link); sb.AppendLine("Debug ID: " + ex.Details.debug_id); MessageBox.Show(sb.ToString()); return false; } return true; }
//het aanmaken van een payment voor paypal van een walletorder: de te betalen payment volgens paypal vereisten. private Payment CreatePayment(APIContext apiContext, string redirectUrl, WalletOrder order) { //eff tijdelijk test ding var itemList = new ItemList() { items = new List<Item>() }; itemList.items.Add(new Item() { name = "Oplading van Wallet", currency = "EUR", price = order.TotalAmount.ToString(), quantity = "1", sku = order.OrderId.ToString() }); var payer = new Payer() { payment_method = "paypal" }; var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; var details = new Details() { tax = "0", shipping = "0", subtotal = order.TotalAmount.ToString() }; var amount = new Amount() { currency = "EUR", total = order.TotalAmount.ToString(), details = details }; var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "Betaling van een oplading", invoice_number = order.OrderId.ToString(), amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return this.payment.Create(apiContext); }
public ActionResult PaymentWithCreditCard(Donor d, string CreditCardNumber, string CreditCardType, string CreditCardExpMonth, string CreditCardExpYear) { //create and item for which you are taking payment //if you need to add more items in the list //Then you will need to create multiple item objects or use some loop to instantiate object Item item = new Item(); item.name = "Item Name"; item.currency = "USD"; item.price = d.Amount.ToString(); item.quantity = "1"; item.sku = "sku"; //Now make a List of Item and add the above item to it //you can create as many items as you want and add to this list List<Item> itms = new List<Item>(); itms.Add(item); ItemList itemList = new ItemList(); itemList.items = itms; //Address for the payment PayPal.Api.Address billingAddress = new PayPal.Api.Address(); billingAddress.city = d.City; billingAddress.country_code = "US"; billingAddress.line1 = d.Address1; billingAddress.postal_code = d.ZipCode; billingAddress.state = d.State; //Now Create an object of credit card and add above details to it //Please replace your credit card details over here which you got from paypal CreditCard crdtCard = new CreditCard(); crdtCard.billing_address = billingAddress; //crdtCard.cvv2 = "874"; //card cvv2 number //crdtCard.expire_month = 1; crdtCard.expire_month = Convert.ToInt32(CreditCardExpMonth); //crdtCard.expire_year = 2021; //card expire year crdtCard.expire_year = Convert.ToInt32(CreditCardExpYear); //crdtCard.first_name = "test"; crdtCard.first_name = d.FirstName; //crdtCard.last_name = "buyer"; crdtCard.last_name = d.LastName; //crdtCard.number = "4032033901230495"; crdtCard.number = CreditCardNumber; //crdtCard.type = "visa"; crdtCard.type = CreditCardType; // Specify details of your payment amount. Details details = new Details(); details.shipping = "0"; details.subtotal = d.Amount.ToString(); details.tax = "0"; // Specify your total payment amount and assign the details object Amount amnt = new Amount(); amnt.currency = "USD"; // Total = shipping tax + subtotal. amnt.total = d.Amount.ToString(); amnt.details = details; // Now make a transaction object and assign the Amount object Transaction tran = new Transaction(); tran.amount = amnt; tran.description = "Donation"; tran.item_list = itemList; tran.invoice_number = "your invoice number which you are generating"; // Now, we have to make a list of transaction and add the transactions object // to this list. You can create one or more object as per your requirements List<Transaction> transactions = new List<Transaction>(); transactions.Add(tran); // Now we need to specify the FundingInstrument of the Payer // for credit card payments, set the CreditCard which we made above FundingInstrument fundInstrument = new FundingInstrument(); fundInstrument.credit_card = crdtCard; // The Payment creation API requires a list of FundingIntrument List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>(); fundingInstrumentList.Add(fundInstrument); // Now create Payer object and assign the fundinginstrument list to the object Payer payr = new Payer(); payr.funding_instruments = fundingInstrumentList; payr.payment_method = "credit_card"; // finally create the payment object and assign the payer object & transaction list to it Payment pymnt = new Payment(); pymnt.intent = "sale"; pymnt.payer = payr; pymnt.transactions = transactions; try { //getting context from the paypal //basically we are sending the clientID and clientSecret key in this function //to the get the context from the paypal API to make the payment //for which we have created the object above. //Basically, apiContext object has a accesstoken which is sent by the paypal //to authenticate the payment to facilitator account. //An access token could be an alphanumeric string // Get a reference to the config var config = ConfigManager.Instance.GetProperties(); // Use OAuthTokenCredential to request an access token from PayPal var accessToken = new OAuthTokenCredential(config).GetAccessToken(); var apiContext = new APIContext(accessToken); //Create is a Payment class function which actually sends the payment details //to the paypal API for the payment. The function is passed with the ApiContext //which we received above. Payment createdPayment = pymnt.Create(apiContext); //if the createdPayment.state is "approved" it means the payment was successful else not if (createdPayment.state.ToLower() != "approved") { return View("DonationFailureView"); } } catch (PayPal.PayPalException e) { string error = e.ToString(); return View("DonationFailureView"); } return View("DonationSuccessView"); }
public IHttpActionResult PostCreatePayment([FromBody]PayPalPaymentConfirmation model) { var userName = this.User.Identity.Name; string userId = ""; try { userId = db.Users.SingleOrDefault(x => x.Email == userName).Id; } catch { return BadRequest("Unregistered user"); } List<RoomAvailability> listOfUnpaidRooms = new List<RoomAvailability>(); List<ReservationsPaymentAPI> listOfUnpaidRoomsFullDetails = new List<ReservationsPaymentAPI>(); if (userId != null) { listOfUnpaidRooms = db.RoomAvailabilities.Where(x => x.UserId == userId && x.IsPaid == false).ToList(); } if (listOfUnpaidRooms.Count > 0) { foreach (var room in listOfUnpaidRooms) { string accomodationName = db.Accomodations.Single(x => x.AccomodationId == room.AccomodationId).AccomodationName; string roomName = db.Rooms.Single(x => x.RoomId == room.RoomId).RoomType.RoomTypeName; listOfUnpaidRoomsFullDetails.Add(new ReservationsPaymentAPI { AccommodationName = accomodationName, RoomName = roomName, AccomodationId = room.AccomodationId, ArrivalDate = room.ArrivalDate, DepartureDate = room.DepartureDate, IsPaid = room.IsPaid, RoomAvailabilityId = room.RoomAvailabilityId, RoomId = room.RoomId, TotalPrice = room.TotalPrice, UserId = room.UserId, UserEmail = userName }); } } //BEGIN OF PAYPAL PAYMENT var config = ConfigManager.Instance.GetProperties(); var accessToken = new OAuthTokenCredential(config).GetAccessToken(); var apiContext = new APIContext(accessToken); apiContext.Config = config; Amount amount = new Amount(); amount.total = listOfUnpaidRoomsFullDetails.Sum(x => x.TotalPrice).ToString(); amount.currency = "USD"; Transaction transaction = new Transaction(); transaction.amount = amount; transaction.item_list = new ItemList(); transaction.item_list.items = new List<Item>(); List<Item> listOfRoomsToPay = new List<Item>(); foreach(var room in listOfUnpaidRoomsFullDetails) { listOfRoomsToPay.Add(new Item { name = room.RoomName, description = room.AccommodationName, quantity = "1", price = room.TotalPrice.ToString(), currency = "USD" }); } transaction.item_list.items.AddRange(listOfRoomsToPay); Payer payer = new Payer(); payer.payment_method = "paypal"; Payment payment = new Payment(); payment.intent = "sale"; payment.payer = payer; payment.transactions = new List<Transaction>(); payment.transactions.Add(transaction); payment.redirect_urls = new RedirectUrls(); payment.redirect_urls.return_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal?userId=" + userId); payment.redirect_urls.cancel_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal"); Payment createdPayment = payment.Create(apiContext); return Ok(createdPayment.GetApprovalUrl()); }
protected override void RunSample() { // ### Api Context // Pass in a `APIContext` object to authenticate // the call and to send a unique request id // (that ensures idempotency). The SDK generates // a request id if you do not pass one explicitly. // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext. var apiContext = Configuration.GetAPIContext(); string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { // ###Items // Items within a transaction. var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } }; // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` var payer = new Payer() { payment_method = "paypal" }; // ###Redirect URLS // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?"; 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 }; // ###Details // Let's you specify details of a payment amount. var details = new Details() { tax = "15", shipping = "10", subtotal = "75" }; // ###Amount // Let's you specify a payment amount. var amount = new Amount() { currency = "USD", total = "100.00", // Total must be equal to sum of shipping, tax and subtotal. details = details }; // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List<Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new Transaction() { description = "Transaction description.", invoice_number = Common.GetRandomInvoiceNumber(), amount = amount, item_list = itemList }); // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Create PayPal payment", payment); #endregion // Create a payment using a valid APIContext var createdPayment = payment.Create(apiContext); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(createdPayment); #endregion // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment. var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href); } } Session.Add(guid, createdPayment.id); Session.Add("flow-" + guid, this.flow); } else { var guid = Request.Params["guid"]; // ^ Ignore workflow code segment #region Track Workflow this.flow = Session["flow-" + guid] as RequestFlow; this.RegisterSampleRequestFlow(); this.flow.RecordApproval("PayPal payment approved successfully."); #endregion // Using the information from the redirect, setup the payment to execute. var paymentId = Session[guid] as string; var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new Payment() { id = paymentId }; // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Execute PayPal payment", payment); #endregion // Execute the payment. var executedPayment = payment.Execute(apiContext, paymentExecution); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(executedPayment); #endregion // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/). } }
public ActionResult PaymentWithCreditCard() { //create and item for which you are taking payment //if you need to add more items in the list //Then you will need to create multiple item objects or use some loop to instantiate object Item item = new Item(); item.name = "Demo Item"; item.currency = "EUR"; item.price = "150"; item.quantity = "1"; item.sku = "sku"; //Now make a List of Item and add the above item to it //you can create as many items as you want and add to this list List<Item> itms = new List<Item>(); itms.Add(item); ItemList itemList = new ItemList(); itemList.items = itms; //Address for the payment Address billingAddress = new Address(); billingAddress.city = "NewYork"; billingAddress.country_code = "US"; billingAddress.line1 = "23rd street kew gardens"; billingAddress.postal_code = "43210"; billingAddress.state = "NY"; //Now Create an object of credit card and add above details to it //Please replace your credit card details over here which you got from paypal CreditCard crdtCard = new CreditCard(); crdtCard.billing_address = billingAddress; crdtCard.cvv2 = "874"; //card cvv2 number crdtCard.expire_month = 1; //card expire date crdtCard.expire_year = 2020; //card expire year crdtCard.first_name = "Aman"; crdtCard.last_name = "Thakur"; crdtCard.number = "1234567890123456"; //enter your credit card number here crdtCard.type = "visa"; //credit card type here paypal allows 4 types // Specify details of your payment amount. Details details = new Details(); details.shipping = "0"; details.subtotal = "150"; details.tax = "27"; // Specify your total payment amount and assign the details object Amount amnt = new Amount(); amnt.currency = "EUR"; // Total = shipping tax + subtotal. amnt.total = "177"; amnt.details = details; // Now make a transaction object and assign the Amount object Transaction tran = new Transaction(); tran.amount = amnt; tran.description = "Description about the payment amount."; tran.item_list = itemList; tran.invoice_number = "your invoice number which you are generating"; // Now, we have to make a list of transaction and add the transactions object // to this list. You can create one or more object as per your requirements List<Transaction> transactions = new List<Transaction>(); transactions.Add(tran); // Now we need to specify the FundingInstrument of the Payer // for credit card payments, set the CreditCard which we made above FundingInstrument fundInstrument = new FundingInstrument(); fundInstrument.credit_card = crdtCard; // The Payment creation API requires a list of FundingIntrument List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>(); fundingInstrumentList.Add(fundInstrument); // Now create Payer object and assign the fundinginstrument list to the object Payer payr = new Payer(); payr.funding_instruments = fundingInstrumentList; payr.payment_method = "credit_card"; // finally create the payment object and assign the payer object & transaction list to it Payment pymnt = new Payment(); pymnt.intent = "sale"; pymnt.payer = payr; pymnt.transactions = transactions; try { //getting context from the paypal //basically we are sending the clientID and clientSecret key in this function //to the get the context from the paypal API to make the payment //for which we have created the object above. //Basically, apiContext object has a accesstoken which is sent by the paypal //to authenticate the payment to facilitator account. //An access token could be an alphanumeric string APIContext apiContext = Configuration.GetAPIContext(); //Create is a Payment class function which actually sends the payment details //to the paypal API for the payment. The function is passed with the ApiContext //which we received above. Payment createdPayment = pymnt.Create(apiContext); //if the createdPayment.state is "approved" it means the payment was successful else not if (createdPayment.state.ToLower() != "approved") { return View("FailureView"); } } catch (PayPal.PayPalException ex) { //Logger.Log("Error: " + ex.Message); return View("FailureView"); } return View("SuccessView"); }
// #Create Future Payment Using PayPal // This sample code demonstrates how you can process a future payment made using a PayPal account. /// <summary> /// Code example for creating a future payment object. /// </summary> /// <param name="correlationId"></param> /// <param name="authorizationCode"></param> private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl) { // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` Payer payer = new Payer() { payment_method = "paypal" }; // ###Amount // Let's you specify a payment amount. var amount = new Amount() { currency = "USD", // Total must be equal to sum of shipping, tax and subtotal. total = "100", // ###Details // Let's you specify details of a payment amount. details = new Details() { tax = "15", shipping = "10", subtotal = "75" } }; // # Redirect URLS var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; // ###Items // Items within a transaction. var itemList = new ItemList() { items = new List<Item>() }; itemList.items.Add(new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" }); // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List<Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new Transaction() { description = "Transaction description.", amount = amount, item_list = itemList }); var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters(); authorizationCodeParameters.setClientId(Configuration.ClientId); authorizationCodeParameters.setClientSecret(Configuration.ClientSecret); authorizationCodeParameters.SetCode(authorizationCode); // ### Api Context // Pass in a `APIContext` object to authenticate // the call and to send a unique request id // (that ensures idempotency). The SDK generates // a request id if you do not pass one explicitly. // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext. var apiContext = Configuration.GetAPIContext(); var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters); var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token); var futurePaymentApiContext = Configuration.GetAPIContext(accessToken); // ###Payment // A FuturePayment Resource var futurePayment = new FuturePayment() { intent = "authorize", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return futurePayment.Create(futurePaymentApiContext, correlationId); }
private List<Transaction> GenerateteTransactions(Cart cart) { var itemList = new ItemList() { items = new List<Item>() }; foreach(CartLine cartLine in cart.Lines) { itemList.items.Add(new Item() { name = cartLine.Product.Name, currency = "USD", price = cartLine.Product.Price.ToString(), quantity = cartLine.Quantity.ToString(), //sku = "sku" }); } var payer = new Payer() { payment_method = "paypal" }; // similar as we did for credit card, do here and create details object var details = new Details() { tax = "0", shipping = "0", subtotal = "0" }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = cart.ComputeTotalValue().ToString(), // 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 = "your invoice number", amount = amount, item_list = itemList }); return transactionList; }
public IHttpActionResult CreatePayment(object data) { string userId = this.User.Identity.GetUserId(); RemoveCart(userId); var apiContext = GetApiContext(); if (apiContext == null) return StatusCode(HttpStatusCode.NotAcceptable); Amount amount = new Amount(); amount.currency = "USD"; Transaction transaction = new Transaction(); transaction.item_list = new ItemList(); transaction.item_list.items = new List<PayPal.Api.Item>(); string json = JsonConvert.SerializeObject(data); double total = 0; RootObject root = JsonConvert.DeserializeObject<RootObject>(json); List<BitCoupon.API.Models.Item> items = root.data.items; if (items.Count == 0) return NotFound(); for (int i = 0; i < items.Count; i++) { var coupon = db.Coupons.Find(Int32.Parse(items[i].id)); //if there are no coupons to buy (qunatity of purchase is bigger then total number of coupons), return BadRequest (don't allow purchase) if (items[i].quantity * coupon.RequiredNumberOfCoupons > coupon.TotalNumberOfCoupons) return BadRequest(); total += items[i].total; transaction.item_list.items.Add(new PayPal.Api.Item() //add items to item list { name = items[i].name, description = items[i].data.DescriptionOnCoupon, quantity = items[i].quantity.ToString(), price = items[i].price.ToString(), currency = amount.currency }); } amount.total = total.ToString(); //total amount to pay transaction.amount = amount; Payer payer = new Payer(); payer.payment_method = "paypal"; Payment payment = new Payment(); payment.intent = "sale"; payment.payer = payer; payment.transactions = new List<Transaction>(); payment.transactions.Add(transaction); payment.redirect_urls = new RedirectUrls(); //create redirect urls where paypal will return depending did user finished payment payment.redirect_urls.return_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal?userId=" + this.User.Identity.GetUserId()); payment.redirect_urls.cancel_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal"); Payment createdPayment = null; try { createdPayment = payment.Create(apiContext); } catch { return StatusCode(HttpStatusCode.NotAcceptable); } CreateCart(userId, items, double.Parse(amount.total)); return Json(createdPayment.GetApprovalUrl()); }