public async Task <PayPal.Api.APIContext> GetPayPalApiContextAsync(string requestId) { try { payPalConfiguration = await payPalConfigurationGrain.GetPayPalConfigurationAsync(); } catch (Exception ex) { throw; } var clientId = payPalConfiguration["clientId"]; var clientSecret = payPalConfiguration["clientSecret"]; var accessToken = new PayPal.Api.OAuthTokenCredential( clientId, clientSecret, payPalConfiguration).GetAccessToken(); PayPal.Api.APIContext payPalApiContext = new PayPal.Api.APIContext(); try { payPalApiContext = new PayPal.Api.APIContext(accessToken, requestId); // requestID is required. } catch (OrleansException ex) { throw; } payPalApiContext.Config = payPalConfiguration; return(await Task.FromResult(payPalApiContext)); }
public static PayPal.Api.APIContext GetAPIContext() { // return apicontext object by invoking it with the accesstoken PayPal.Api.APIContext apiContext = new PayPal.Api.APIContext(GetAccessToken()); apiContext.Config = GetConfig(); return(apiContext); }
private async Task GetTokenAsync() { RespuestaPaypalToken Respuesta = new RespuestaPaypalToken(); Respuesta = await Task.Run(() => Paypal.GetTokenPaypal()); PayPal.Api.APIContext apiContext = Paypal.GetApiContext(Respuesta.access_token); int n = Metodo.ObtenerNumeroDePago(); }
/// <summary> /// excute payment /// </summary> /// <returns></returns> /// private PayPal.Api.Payment ExecutePayment(PayPal.Api.APIContext apiContext, string payerId, string paymentId) { var paymentExecution = new PayPal.Api.PaymentExecution() { payer_id = payerId }; this.payment = new PayPal.Api.Payment() { id = paymentId }; return(this.payment.Execute(apiContext, paymentExecution)); }
// Returns APIContext object public static APIContext GetAPIContext() { // ### Api Context // Pass in a `APIContext` object to authenticate // the call and to send a unique request id // (that ensures idempotency). The SDK generates // a request id if you do not pass one explicitly. var apiContext = new APIContext(GetAccessToken()) { Config = GetConfig() , SdkVersion = new SDKVersion { } }; // Use this variant if you want to pass in a request id // that is meaningful in your application, ideally // a order id. // String requestId = Long.toString(System.nanoTime(); // APIContext apiContext = new APIContext(GetAccessToken(), requestId )); return(apiContext); }
public ActionResult SaveOrder(FormCollection fc) { if (IsCardNumberValid(NormalizeCardNumber(fc["cardNumber"]))) { bool res = false; switch (GetCardType(fc["cardNumber"])) { case (CardType.Amex): fc["cardType"] = "amex"; res = true; break; case (CardType.Discover): fc["cardType"] = "discover"; res = true; break; case (CardType.MasterCard): fc["cardType"] = "mastercard"; res = true; break; case (CardType.VISA): fc["cardType"] = "visa"; res = true; break; default: res = false; break; } if (res) { List <Item> cart = (List <Item>)Session["cart"]; Invoice invoice = new Invoice(); invoice.CustomerName = fc["customerName"]; invoice.CustomerAddress = fc["customerAddress"]; invoice.Name = "New Invoice"; PayPal.Api.Item paitem; List <Item> lstItem = (List <Item>)Session["cart"]; List <PayPal.Api.Item> itms = new List <PayPal.Api.Item>(); PayPal.Api.ItemList itemList = new PayPal.Api.ItemList(); decimal totalPrice = 0; foreach (var item in lstItem) { paitem = new PayPal.Api.Item(); paitem.name = item.pr.ProductName; paitem.currency = "USD"; paitem.price = item.pr.Price.ToString();// "5"; paitem.quantity = "1"; paitem.sku = "sku"; if (item.Quantity > 0) { for (int i = 0; i < Convert.ToInt16(item.Quantity); i++) { itms.Add(paitem); } itemList.items = new List <PayPal.Api.Item>(); foreach (var itm in itms) { itemList.items.Add(itm); } totalPrice = totalPrice + item.pr.Price * item.Quantity; } } //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 //Address for the payment PayPal.Api.Address billingAddress = new PayPal.Api.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 PayPal.Api.CreditCard crdtCard = new PayPal.Api.CreditCard(); crdtCard.billing_address = billingAddress; crdtCard.cvv2 = fc["CVV"]; //card cvv2 number crdtCard.expire_month = Convert.ToInt32(fc["expMonth"]); //card expire date crdtCard.expire_year = Convert.ToInt32(fc["expYear"]); //card expire year crdtCard.first_name = fc["nameOnCardFirstName"]; crdtCard.last_name = fc["nameOnCardLastName"]; crdtCard.number = fc["cardNumber"]; //enter your credit card number here crdtCard.type = fc["cardType"]; //credit card type here paypal allows 4 types // Specify details of your payment amount. PayPal.Api.Details details = new PayPal.Api.Details(); details.shipping = (1 * Convert.ToInt32(0)).ToString(); details.subtotal = totalPrice.ToString(); details.tax = (1 * Convert.ToInt32(0)).ToString(); // Specify your total payment amount and assign the details object PayPal.Api.Amount amnt = new PayPal.Api.Amount(); amnt.currency = "USD"; // Total = shipping tax + subtotal. amnt.total = (Convert.ToInt32(totalPrice) + Convert.ToInt32(details.shipping) + Convert.ToInt32(details.tax)).ToString(); amnt.details = details; // Now make a transaction object and assign the Amount object Random random = new Random(); PayPal.Api.Transaction tran = new PayPal.Api.Transaction(); tran.amount = amnt; tran.description = "Description about the payment amount."; tran.item_list = itemList; tran.invoice_number = random.Next().ToString(); // 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 <PayPal.Api.Transaction> transactions = new List <PayPal.Api.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 PayPal.Api.FundingInstrument fundInstrument = new PayPal.Api.FundingInstrument(); fundInstrument.credit_card = crdtCard; // The Payment creation API requires a list of FundingIntrument List <PayPal.Api.FundingInstrument> fundingInstrumentList = new List <PayPal.Api.FundingInstrument>(); fundingInstrumentList.Add(fundInstrument); // Now create Payer object and assign the fundinginstrument list to the object PayPal.Api.Payer payr = new PayPal.Api.Payer(); payr.funding_instruments = fundingInstrumentList; payr.payment_method = "credit_card"; // finally create the payment object and assign the payer object & transaction list to it PayPal.Api.Payment pymnt = new PayPal.Api.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 PayPal.Api.APIContext apiContext = PayPalIntegration.Models.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. PayPal.Api.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) { ViewBag.Error = "Error: " + ex.Message; return(View("FailureView")); } return(View("Thanks")); } else { ViewBag.Error = "Please provide valid card"; return(View("FailureView")); } } else { ViewBag.Error = "Please provide valid credit card number"; return(View("FailureView")); } }
public async Task <PayPal.Api.Payment> GetPayPalPaymentAsync(Order order, Card card, string requestId = null) { // TODO: Put null handling on non-required fields // TODO: Put error handling on required fields. PayPal.Api.ItemList payPalItemList = new PayPal.Api.ItemList(); payPalItemList.items = new List <PayPal.Api.Item>(); foreach (var orderItem in order.OrderItems) { payPalItemList.items.Add( new PayPal.Api.Item() { currency = String.IsNullOrEmpty(orderItem.Currency) ? "USD" : orderItem.Currency, // Required description = orderItem.Description, price = orderItem.Price.ToString("n2", CultureInfo.InvariantCulture), name = String.IsNullOrEmpty(orderItem.Name) ? "Product Name" : orderItem.Name, // Required quantity = orderItem.Quantity.ToString("n0", CultureInfo.InvariantCulture), sku = orderItem.ProductSKU, //url = cartItem.ProductUrl, // Not defined for this resource type }); } ; var transaction = new PayPal.Api.Transaction() { amount = new PayPal.Api.Amount() { currency = "USD", total = order.Total.ToString(), // Required, and must be the sum of the item totals. details = new PayPal.Api.Details() { shipping = order.ShippingTotal.ToString("n2", CultureInfo.InvariantCulture), subtotal = order.Subtotal.ToString("n2", CultureInfo.InvariantCulture), tax = order.TaxTotal.ToString("n2", CultureInfo.InvariantCulture), } }, invoice_number = order.OrderId.ToString(), item_list = payPalItemList, }; var payer = new PayPal.Api.Payer() { payment_method = "credit_card", // required? funding_instruments = new List <PayPal.Api.FundingInstrument>() { new PayPal.Api.FundingInstrument() { credit_card = new PayPal.Api.CreditCard() { first_name = card.FirstName, last_name = card.LastName, billing_address = new PayPal.Api.Address() { line1 = card.BillingAddress.AddressLine1, line2 = card.BillingAddress.AddressLine2, city = card.BillingAddress.City, country_code = card.BillingAddress.Country == null ? "US" : card.BillingAddress.Country.ToString().ToUpper(), state = card.BillingAddress.StateProvince, postal_code = card.BillingAddress.ZipPostalCode, }, type = card.CardType.ToLowerInvariant(), number = card.CardNumber, cvv2 = card.CardCvvCode, expire_month = Convert.ToInt32(card.ExpirationMonth), expire_year = Convert.ToInt32(card.ExpirationYear), } } } }; PayPal.Api.Payment paymentRequest = new PayPal.Api.Payment() { intent = "sale", payer = payer, transactions = new List <PayPal.Api.Transaction>() { transaction } }; if (order == null) { throw new ArgumentException("GetPayPalPaymentAsync: Cart can't be null."); } if (order == null) { throw new ArgumentException("GetPayPalPaymentAsync: Card can't be null."); } if (String.IsNullOrEmpty(requestId)) { throw new ArgumentException("GetPayPalPaymentAsync: RequestID can't be null."); } PayPal.Api.APIContext apiContext = new PayPal.Api.APIContext(); try { apiContext = await GetPayPalApiContextAsync(requestId); } catch (Exception ex) { throw; } //https://developer.paypal.com/docs/api/#create-a-payment PayPal.Api.Payment response = new PayPal.Api.Payment(); try { // Wrap this in a Task so it's awaitable. response = paymentRequest.Create(apiContext); } catch (PayPal.HttpException ex) { throw; } catch (InvalidCastException ex) { throw; } catch (Exception ex) { throw; } State.Payment = response; await State.WriteStateAsync(); return(await Task.FromResult(response)); }
//PLACE ORDER--LAST STEP public ActionResult PlaceOrder(FormCollection getCheckoutDetails) { if (Convert.ToInt32(getCheckoutDetails["PayMethod"]) == 1) { int shpID = 1; if (db.ShippingDetails.Count() > 0) { shpID = db.ShippingDetails.Max(x => x.ShippingID) + 1; } int payID = 1; if (db.Payments.Count() > 0) { payID = db.Payments.Max(x => x.PaymentID) + 1; } int orderID = 1; if (db.Orders.Count() > 0) { orderID = db.Orders.Max(x => x.OrderID) + 1; } ShippingDetail shpDetails = new ShippingDetail(); shpDetails.ShippingID = shpID; shpDetails.FirstName = getCheckoutDetails["FirstName"]; shpDetails.LastName = getCheckoutDetails["LastName"]; shpDetails.Email = getCheckoutDetails["Email"]; shpDetails.Mobile = getCheckoutDetails["Mobile"]; shpDetails.Address = getCheckoutDetails["Address"]; shpDetails.Province = getCheckoutDetails["Province"]; shpDetails.City = getCheckoutDetails["City"]; shpDetails.PostCode = getCheckoutDetails["PostCode"]; db.ShippingDetails.Add(shpDetails); db.SaveChanges(); Payment pay = new Payment(); pay.PaymentID = payID; pay.Type = Convert.ToInt32(getCheckoutDetails["PayMethod"]); db.Payments.Add(pay); db.SaveChanges(); Order o = new Order(); o.OrderID = orderID; o.CustomerID = TempShpData.UserID; o.PaymentID = payID; o.ShippingID = shpID; o.Discount = Convert.ToInt32(getCheckoutDetails["discount"]); o.TotalAmount = Convert.ToInt32(getCheckoutDetails["totalAmount"]); o.isCompleted = true; o.OrderDate = DateTime.Now; db.Orders.Add(o); db.SaveChanges(); foreach (var OD in TempShpData.items) { OD.OrderID = orderID; OD.Order = db.Orders.Find(orderID); OD.Product = db.Products.Find(OD.ProductID); db.OrderDetails.Add(OD); db.SaveChanges(); } SendMail.GuiEmail("Xác nhận đặt hàng thành công", getCheckoutDetails["Email"], "Cảm ơn bạn đã đặt hàng, mã đơn hàng của bạn là: " + o.OrderID); return(RedirectToAction("Index", "ThankYou")); } //Paypal else { PayPal.Api.APIContext apiContext = Configuration.GetAPIContext(); try { string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { int shpID = 1; if (db.ShippingDetails.Count() > 0) { shpID = db.ShippingDetails.Max(x => x.ShippingID) + 1; } int payID = 1; if (db.Payments.Count() > 0) { payID = db.Payments.Max(x => x.PaymentID) + 1; } int orderID = 1; if (db.Orders.Count() > 0) { orderID = db.Orders.Max(x => x.OrderID) + 1; } ShippingDetail shpDetails = new ShippingDetail(); shpDetails.ShippingID = shpID; shpDetails.FirstName = getCheckoutDetails["FirstName"]; shpDetails.LastName = getCheckoutDetails["LastName"]; shpDetails.Email = getCheckoutDetails["Email"]; shpDetails.Mobile = getCheckoutDetails["Mobile"]; shpDetails.Address = getCheckoutDetails["Address"]; shpDetails.Province = getCheckoutDetails["Province"]; shpDetails.City = getCheckoutDetails["City"]; shpDetails.PostCode = getCheckoutDetails["PostCode"]; db.ShippingDetails.Add(shpDetails); db.SaveChanges(); Payment pay = new Payment(); pay.PaymentID = payID; pay.Type = Convert.ToInt32(getCheckoutDetails["PayMethod"]); db.Payments.Add(pay); db.SaveChanges(); Order o = new Order(); o.OrderID = orderID; o.CustomerID = TempShpData.UserID; o.PaymentID = payID; o.ShippingID = shpID; o.Discount = Convert.ToInt32(getCheckoutDetails["discount"]); o.TotalAmount = Convert.ToInt32(getCheckoutDetails["totalAmount"]); o.isCompleted = true; o.OrderDate = DateTime.Now; db.Orders.Add(o); db.SaveChanges(); string tenSp = ""; foreach (var OD in TempShpData.items) { OD.OrderID = orderID; OD.Order = db.Orders.Find(orderID); OD.Product = db.Products.Find(OD.ProductID); tenSp += db.Products.Find(OD.ProductID).Name + ", "; db.OrderDetails.Add(OD); db.SaveChanges(); } SendMail.GuiEmail("Xác nhận đặt hàng thành công", getCheckoutDetails["Email"], "Cảm ơn bạn đã đặt hàng, mã đơn hàng của bạn là: " + o.OrderID); //this section will be executed first because PayerID doesn't exist //it is returned by the create function call of the payment class // Creating a payment // baseURL is the url on which paypal sendsback the data. // So we have provided URL of this controller only string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/CheckOut/PlaceOrder?"; //guid we are generating for storing the paymentID received in session //after calling the create function and it is used in the payment execution var guid = Convert.ToString((new Random()).Next(100000)); //CreatePayment function gives us the payment approval url //on which payer is redirected for paypal account payment var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, tenSp, o.TotalAmount); //get links returned from paypal in response to Create function call var links = createdPayment.links.GetEnumerator(); string paypalRedirectUrl = null; while (links.MoveNext()) { PayPal.Api.Links lnk = links.Current; if (lnk.rel.ToLower().Trim().Equals("approval_url")) { //saving the payapalredirect URL to which user will be redirected for payment paypalRedirectUrl = lnk.href; } } // saving the paymentID in the key guid Session.Add(guid, createdPayment.id); return(Redirect(paypalRedirectUrl)); } else { // This section is executed when we have received all the payments parameters // from the previous call to the function Create // Executing a payment var guid = Request.Params["guid"]; var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string); if (executedPayment.state.ToLower() != "approved") { return(View("FailureView")); } } } catch (Exception ex) { Logger.Log("Error" + ex.Message); return(View("FailureView")); } return(RedirectToAction("Index", "ThankYou")); } }
/// <summary> /// Create payment /// </summary> /// <returns></returns> /// private PayPal.Api.Payment CreatePayment(PayPal.Api.APIContext apiContext, string redirectUrl, string tenSp, int?price) { var itemList = new PayPal.Api.ItemList() { items = new List <PayPal.Api.Item>() }; //Các giá trị bao gồm danh sách sản phẩm, thông tin đơn hàng //Sẽ được thay đổi bằng hành vi thao tác mua hàng trên website var items = new PayPal.Api.Item() { //Thông tin đơn hàng name = tenSp, currency = "USD", price = String.Format("{0:0.00}", price / 23000), quantity = "1", sku = "sku" }; itemList.items.Add(items); var subtotal = float.Parse(items.price) * float.Parse(items.quantity); //Hình thức thanh toán qua paypal var payer = new PayPal.Api.Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new PayPal.Api.RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; //các thông tin trong đơn hàng var details = new PayPal.Api.Details() { tax = "1", shipping = "1", subtotal = subtotal.ToString() }; var total = subtotal + float.Parse(details.tax) + float.Parse(details.shipping); //Đơn vị tiền tệ và tổng đơn hàng cần thanh toán var amount = new PayPal.Api.Amount() { currency = "USD", total = total.ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List <PayPal.Api.Transaction>(); //Tất cả thông tin thanh toán cần đưa vào transaction transactionList.Add(new PayPal.Api.Transaction() { description = "Transaction description.", invoice_number = Guid.NewGuid().ToString(), amount = amount, item_list = itemList }); this.payment = new PayPal.Api.Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return(this.payment.Create(apiContext)); }
public ActionResult AddressAndPayment(OrderViewModel orderViewModel) { if (!ModelState.IsValid) { ViewBag.Months = PayPalHelper.Months; ViewBag.Years = PayPalHelper.Years; ViewBag.CreditCardTypes = PayPalHelper.CreditCardTypes; ViewBag.Countries = PayPalHelper.Countries; return(View(orderViewModel)); } try { //create the order to store information in our database var cart = ShoppingCart.GetCart(this.HttpContext); Order order = new Order(); decimal orderTotal = 0; order.Username = User.Identity.Name; order.OrderDate = DateTime.Now; order.OrderDetails = new List <OrderDetail>(); var cartProducts = cart.GetCartProducts(); // Iterate over the products in the cart, // adding the order details for each foreach (var product in cartProducts) { var orderDetail = new OrderDetail { ProductId = product.ProductId, OrderId = order.OrderId, UnitPrice = product.Product.Price, Quantity = product.Count }; // Set the order total of the shopping cart orderTotal += (product.Count * product.Product.Price); order.OrderDetails.Add(orderDetail); } // Set the order's total to the orderTotal count order.Total = orderTotal; //add everything to the DB dbContext.Orders.Add(order); dbContext.OrderDetails.AddRange(order.OrderDetails); //proccess to paypal List <PayPal.Api.Item> items = new List <PayPal.Api.Item>(); foreach (OrderDetail orderDetail in order.OrderDetails) { PayPal.Api.Item item = new PayPal.Api.Item(); item.name = dbContext.Products.Single(p => p.ProductId == orderDetail.ProductId).Name; item.currency = "USD"; item.price = orderDetail.UnitPrice.ToString(); item.quantity = orderDetail.Quantity.ToString(); item.sku = orderDetail.ProductId.ToString(); items.Add(item); } PayPal.Api.ItemList itemList = new PayPal.Api.ItemList(); itemList.items = items; PayPal.Api.Address address = new PayPal.Api.Address(); address.city = orderViewModel.City; address.country_code = orderViewModel.Country; address.line1 = orderViewModel.Address; address.postal_code = orderViewModel.PostalCode.ToString(); address.state = orderViewModel.State; PayPal.Api.CreditCard creditCard = new PayPal.Api.CreditCard(); creditCard.billing_address = address; creditCard.cvv2 = orderViewModel.CSC.ToString(); creditCard.expire_month = Int32.Parse(orderViewModel.ExpirationMonth); creditCard.expire_year = Int32.Parse(orderViewModel.ExpirationYear); creditCard.first_name = orderViewModel.FirstName; creditCard.last_name = orderViewModel.LastName; creditCard.number = orderViewModel.CreditCardNumber; creditCard.type = orderViewModel.CcType; PayPal.Api.Details details = new PayPal.Api.Details(); details.shipping = "1"; details.subtotal = order.Total.ToString(); details.tax = "1"; PayPal.Api.Amount amount = new PayPal.Api.Amount(); amount.currency = "USD"; amount.total = (order.Total + 2).ToString(); amount.details = details; PayPal.Api.Transaction transaction = new PayPal.Api.Transaction(); transaction.amount = amount; transaction.description = "Description goes here"; transaction.item_list = itemList; transaction.invoice_number = order.OrderId.ToString(); List <PayPal.Api.Transaction> transactionList = new List <PayPal.Api.Transaction>(); transactionList.Add(transaction); PayPal.Api.FundingInstrument fundInstrument = new PayPal.Api.FundingInstrument(); fundInstrument.credit_card = creditCard; List <PayPal.Api.FundingInstrument> fundingList = new List <PayPal.Api.FundingInstrument>(); fundingList.Add(fundInstrument); PayPal.Api.Payer payer = new PayPal.Api.Payer(); payer.funding_instruments = fundingList; payer.payment_method = "credit_card"; PayPal.Api.Payment payment = new PayPal.Api.Payment(); payment.intent = "sale"; payment.payer = payer; payment.transactions = transactionList; 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 PayPal.Api.APIContext apiContext = PayPalConfig.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. PayPal.Api.Payment createdPayment = payment.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")); } cart.EmptyCart(); return(RedirectToAction("Complete", new { id = order.OrderId })); } catch (Exception ex) { //Invalid - redisplay with errors //return View(order); } return(View()); }