public Execute ( |
||
apiContext | APIContext used for the API call. | |
paymentExecution | PaymentExecution | |
return |
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"); }
//Execute payment public Payment ConfirmPayment(string payerId, string paymentId) { var paymentExecution = new PaymentExecution { payer_id = payerId }; var payment = new Payment { id = paymentId }; return payment.Execute(Api, paymentExecution); }
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 async Task<ActionResult> PaypalReturn() { string payerId = Request.Params["PayerID"]; var guid = Request.Params["guid"]; var success = Request.Params["Success"]; if (guid != null && success != null) { var isSuccess = Convert.ToBoolean(Request.QueryString["Success"]); var transactionID = Session[guid] as string; //If client buy succesful, process here if (isSuccess) { var helper = new PaypalHelper(); APIContext apiContext = helper.GetGetAPIContext(); var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new Payment() { id = transactionID }; //We need to execute to submit paypal about client's transaction //If we don't execute paypal, the transaction will be cancel, the buyer don't charge money //-------------------------------------------------------------- try { var executedPayment = payment.Execute(apiContext, paymentExecution); if (executedPayment.state.ToLower() != "approved") { //Save information of transaction into Database //when executedPayment is not approved //--------------------------------------------- var transactionId = Session["transactionId"]; var goEatApi = GoEatApi.Instance; // goEatApi.UpdateMainTransactionStatus(Int32.Parse(transactionId.ToString()), ConstantValues.S_CANCELLED); return View("PaypalFailure"); } else { //Save information of transaction into Database //State of transaction is approved //--------------------------------------------- var goEatApi = GoEatApi.Instance; var transactionId = Session["transactionId"]; var confirmTransactionResult = goEatApi.GetConfirmTokenTransactionById(Int32.Parse(transactionId.ToString())); if (confirmTransactionResult.Succeeded) { if (confirmTransactionResult.Succeeded) { goEatApi.FinishPaypalFinalTransaction( confirmTransactionResult.Data.paypal_payment_id, confirmTransactionResult.Data.id, confirmTransactionResult.Data.customer_id, confirmTransactionResult.Data.token_amount); var model = new PaypalSuccess() { amount = confirmTransactionResult.Data.token_amount }; var customer = goEatApi.GetUserById(confirmTransactionResult.Data.customer_id); //create api recording await goEatApi.RecordTokenTransaction(new GRecordTokenTransaction { username = customer.Data.Profile.account, order_id = confirmTransactionResult.Data.paypal_payment_id, gtoken_transaction_id = string.Empty, token_type = ConstantValues.S_SUGAR_TOKEN, transaction_type = ConstantValues.S_TRANSACTION_TYPE_CONSUMPTION, amount = confirmTransactionResult.Data.token_amount, description = ConstantValues.S_DESCRIPTION_TOPUP_TOKEN }); return View("PaypalSuccess", model); } } } } catch { return View("PaypalFailure"); } } //If client cancel, process here else { //Save information of transaction into Database //When client cancel, Use transactionID to trace //--------------------------------------------- var transactionId = Session["transactionId"]; var goEatApi = GoEatApi.Instance; //goEatApi.UpdateMainTransactionStatus(Int32.Parse(transactionId.ToString()), ConstantValues.S_CANCELLED); return RedirectToAction("buytoken"); } } //All params is not valid, return valid view here return View("PaypalFailure"); }
public int ProcessPayment(string paymentId, string payerId, string token) { var apiToken = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret) .GetAccessToken(); var apiContext = new APIContext(apiToken); var payment = new PayPal.Api.Payment() { id = paymentId, token = token }; var executed = payment.Execute(apiContext, new PaymentExecution() { payer_id = payerId }); if (true) { //TODO VALIDATIONS } var dbPayment = this.db.Payments.FirstOrDefault(x => x.PaymentId == paymentId); dbPayment.Status = PaymentStatus.Successfully; this.db.Payments.Update(dbPayment); this.db.SaveChanges(); return(dbPayment.CourseId); }
public void Checking() { while (true) { foreach (var gamePayment in payments.listOfPayments) { var id = gamePayment.Id; var g = Payment.Get(apiContext, id); if (g.payer != null) { if (g.state == "approved") { //gdy transakcja zostala wykonana przez paypala //GamePacket packet = new GamePacket(OperationType.GET_CREDITS,gamePayment.Name); //Connection.Send(packet); } else { //gdy transakcja zostaje zaakceptowana przez platnika var paymentExecution = new PaymentExecution(); paymentExecution.payer_id = g.payer.payer_info.payer_id; payment.Execute(apiContext, paymentExecution); } } } //PaymentExecution z = new PaymentExecution(); //payment.Execute(apiContext,) Thread.Sleep(10000); } }
public async Task ProcessPaymentAsync(PaymentBindingModel model, IEnumerable <Models.Payment> payments) { var payment = new Payment { id = model.PaymentId, token = model.Token }; var executed = payment .Execute(this.apiContext, new PaymentExecution { payer_id = model.PayerId }); foreach (var payment1 in payments) { payment1.PayPalPaymentId = model.PaymentId; payment1.Username = model.Username; payment1.StudentId = model.StudentId; } await this.repository.AddRangeAsync(payments); StudentsInCourses studentsInCourses = null; foreach (var payment2 in payments) { studentsInCourses = new StudentsInCourses { CourseId = payment2.CourseId, StudentId = payment2.StudentId }; } await this.studentsInCourseRepository.AddAsync(studentsInCourses); }
public PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId) { var paymentExecution = new PaymentExecution { payer_id = payerId }; _payment = new PayPal.Api.Payment { id = paymentId }; return(_payment.Execute(apiContext, paymentExecution)); }
public Payment ConfirmarPagamento(Guid siteId, string token, string idPagamento, string idPagador) { var apiContext = _configuradorPayPal.GetApiContext(); var paymentExecution = new PaymentExecution { payer_id = idPagador }; var payment = new Payment { id = idPagamento }; var executedPayment = payment.Execute(apiContext, paymentExecution); return executedPayment; }
/// <summary> /// Executes payment info by payerId and paymentId /// </summary> /// <param name="apiContext">PayPal API context</param> /// <param name="payerId">Payer id</param> /// <param name="paymentId">Payment id</param> /// /// <param name="cart">cart with tracks</param> /// <returns></returns> private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId) { var paymentExecution = new PaymentExecution() { payer_id = payerId }; payment = new Payment() { id = paymentId }; return(payment.Execute(apiContext, paymentExecution)); }
public static Payment ExecutePayment(string paymentId, string payerId) { // ### 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 = PaypalConfig.GetAPIContext(); var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new Payment() { id = paymentId }; // Execute the payment. var executedPayment = payment.Execute(apiContext, paymentExecution); return executedPayment; }
public PaymentResult PaymentExcution(string payerId, string paymentId) { var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new PayPal.Api.Payment { id = paymentId }; var executedPayment = payment.Execute(apiCtx, paymentExecution); return(new PaymentResult { Status = executedPayment.state == "approved", Message = executedPayment.state, Data = Newtonsoft.Json.JsonConvert.SerializeObject(executedPayment) }); }
private PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId) { try { var paymentExecution = new PaymentExecution() { payer_id = payerId }; payment = new PayPal.Api.Payment() { id = paymentId }; return(payment.Execute(apiContext, paymentExecution)); } catch (Exception ex) { throw; } }
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId) { var paymentExecution = new PaymentExecution() { payer_id = payerId }; payment = new Payment() { id = paymentId }; return payment.Execute(apiContext, paymentExecution); }
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)) { var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPalWithDiscount.aspx?"; var guid = Convert.ToString((new Random()).Next(100000)); var redirectUrl = baseURI + "guid=" + guid; // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new Payment { intent = "sale", // ###Payer // A resource representing a Payer that funds a payment // Payment Method as `paypal` payer = new Payer { payment_method = "paypal" }, transactions = new List<Transaction> { // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. new Transaction { description = "Transaction description.", invoice_number = Common.GetRandomInvoiceNumber(), // ###Amount // Let's you specify a payment amount. amount = new Amount { currency = "USD", // Total must be equal to sum of shipping, tax and subtotal. total = "92.50", // ###Details // Let's you specify details of a payment amount. details = new Details { tax = "15", shipping = "10", subtotal = "67.50" } }, // ###Items // Items within a transaction. item_list = new ItemList { items = new List<Item> { new Item { name = "Item Name", currency = "USD", price = "15.00", quantity = "5", sku = "sku" }, new Item { name = "Special 10% Discount", currency = "USD", price = "-7.50", quantity = "1", sku = "sku_discount" } } } } }, // ###Redirect URLS // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. redirect_urls = new RedirectUrls { cancel_url = redirectUrl + "&cancel=true", return_url = redirectUrl } }; // ^ 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 PaymentSucess() { //if ((string)Session["email"] == null) //{ // Response.Redirect("/Home?Login=true"); // Session.Clear(); //} try { var paymentId = Request.Params["paymentId"].ToString(); var token = Request.Params["token"].ToString(); var payerid = Request.Params["PayerID"].ToString(); // Using the information from the redirect, setup the payment to execute. var paymentExecution = new PaymentExecution() { payer_id = payerid }; var payment = new PayPal.Api.Payment() { id = paymentId }; config = PayPal.Api.ConfigManager.Instance.GetProperties(); auth = new OAuthTokenCredential(config); var apiContext = new APIContext(auth.GetAccessToken()); // BetaDB db = new BetaDB(); int UserID = Convert.ToInt32(Session[DealsNZ.Helpers.KeyList.SessionKeys.UserID].ToString()); // var login = db.Logins.Where(x => x.Email == email).FirstOrDefault(); var executedPayment = payment.Execute(apiContext, paymentExecution); if (executedPayment.failed_transactions == null) { List <Transaction> tl = executedPayment.transactions; foreach (Transaction transaction in tl) { String invoice = transaction.invoice_number; // Payment pay = db.Payments.Where(x => x.InvoiceNo == invoice).SingleOrDefault(); // pay.Status = 1; ItemList itemlist = transaction.item_list; foreach (Item i in transaction.item_list.items) { try { int id = Convert.ToInt16(i.sku); int q = Convert.ToInt32(i.quantity); Decimal p = Convert.ToDecimal(i.price); walleservice = new UserWalletServices(new DealsDB()); Wallet AddTrans = walleservice.GetCreditByUserID(Convert.ToInt32(Session[DealsNZ.Helpers.KeyList.SessionKeys.UserID].ToString())); AddTrans.UserId = Convert.ToInt32(Session[DealsNZ.Helpers.KeyList.SessionKeys.UserID].ToString()); AddTrans.WalletCredit = Convert.ToDecimal(p + Convert.ToDecimal(AddTrans.WalletCredit)); AddTrans.WalletCreditDate = System.DateTime.Now; if (walleservice.WalletUpdate(AddTrans) == true) { Session[KeyList.SessionKeys.WalletCredit] = walleservice.ShowWalletAmount(Convert.ToInt32(Session[DealsNZ.Helpers.KeyList.SessionKeys.UserID].ToString())); return(RedirectToAction("Index", "Home")); } walleservice.Dispose(); } catch (Exception er) { } } //// Send Email to user //Services.MethodHandler.Sendemail(Session["email"].ToString(), "OrderSuccess", transaction.invoice_number); //// //paymentlbl.Text = "We recieved you payment nd your order is being processed"; } } // db.SaveChanges(); } catch (Exception error) { } return(View()); }
public Payment ExecutePayPalPayment( string payerId, string paymentId) { var paymentExecution = new PaymentExecution { payer_id = payerId }; var payment = new Payment() { id = paymentId }; return payment.Execute(PayPalConfiguration.GetApiContext(), paymentExecution); }
public Payment ExecutePayment(string payerId, string paymentId) { var paymentExecution = new PaymentExecution { payer_id = payerId }; var payment = new Payment { id = paymentId }; return payment.Execute(_apiContext, paymentExecution); }
// Payment Status == 0 then payment started // == 1 them successful payment (but waitng for approval ) // == 2 payment recieved and order processing // == 3 order processed protected void Page_Load(object sender, EventArgs e) { if ((string)Session["email"] == null) { Response.Redirect("/Home?Login=true"); Session.Clear(); } try { var paymentId = Request.Params["paymentId"].ToString(); var token = Request.Params["token"].ToString(); var payerid = Request.Params["PayerID"].ToString(); // Using the information from the redirect, setup the payment to execute. var paymentExecution = new PaymentExecution() { payer_id = payerid }; var payment = new PayPal.Api.Payment() { id = paymentId }; config = PayPal.Api.ConfigManager.Instance.GetProperties(); auth = new OAuthTokenCredential(config); var apiContext = new APIContext(auth.GetAccessToken()); BetaDB db = new BetaDB(); string email = Session["email"].ToString(); var login = db.Logins.Where(x => x.Email == email).FirstOrDefault(); var executedPayment = payment.Execute(apiContext, paymentExecution); if (executedPayment.failed_transactions == null) { List <Transaction> tl = executedPayment.transactions; foreach (Transaction transaction in tl) { String invoice = transaction.invoice_number; Payment pay = db.Payments.Where(x => x.InvoiceNo == invoice).SingleOrDefault(); pay.Status = 1; ItemList itemlist = transaction.item_list; foreach (Item i in transaction.item_list.items) { try { int id = Convert.ToInt16(i.sku); int q = Convert.ToInt16(i.quantity); string size = i.description; Cart cartitem = db.Carts.Where(x => x.ProductID == id && x.UserId == login.ID && x.Quantity == q && x.Size == size).SingleOrDefault(); String _size = cartitem.Size; Stock stock = db.Stocks.Where(pro => pro.ProductID == id && pro.ProductSizeName == size).SingleOrDefault(); stock.StockCount = stock.StockCount - Convert.ToInt16(i.quantity); db.Carts.Remove(cartitem); } catch (Exception er) { } } // Send Email to user Services.MethodHandler.Sendemail(Session["email"].ToString(), "OrderSuccess", transaction.invoice_number); // paymentlbl.Text = "We recieved you payment and your order is being processed"; } } db.SaveChanges(); } catch (Exception error) { } }
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)) { // ###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 + "/SaleRefund.aspx?"; var guid = Convert.ToString((new Random()).Next(100000)); var redirectUrl = baseURI + "guid=" + guid; // ###Payment // A Payment Resource; create one using // the above types and intent as `sale` or `authorize` var payment = new Payment { intent = "sale", payer = new Payer { payment_method = "paypal" }, transactions = new List<Transaction> { new Transaction { description = "Transaction description.", invoice_number = Common.GetRandomInvoiceNumber(), amount = new Amount { currency = "USD", total = "100.00", details = new Details { tax = "15", shipping = "10", subtotal = "75" } }, item_list = new ItemList { items = new List<Item> { new Item { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } } } }, redirect_urls = new RedirectUrls { cancel_url = redirectUrl + "&cancel=true", return_url = redirectUrl } }; // ^ 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 // A refund transaction. Use the amount to create a refund object var refund = new Refund() { amount = new Amount() { currency = "USD", total = "100.00" } }; // Get the sale resource from the executed payment's list of related resources. var sale = executedPayment.transactions[0].related_resources[0].sale; // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Refund sale", refund, string.Format("URI: /v1/payments/sale/{0}/refund", sale.id)); #endregion // Refund by posting Refund object using a valid APIContext var response = sale.Refund(apiContext, refund); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(response); #endregion // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Get the details of the payment", description: "ID: " + executedPayment.id); #endregion var retrievedPayment = Payment.Get(apiContext, executedPayment.id); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(retrievedPayment); #endregion // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/). } }
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)) { // Create the web experience profile var profile = new WebProfile { name = Guid.NewGuid().ToString(), presentation = new Presentation { brand_name = "PayPal .NET SDK", locale_code = "US", logo_image = "https://raw.githubusercontent.com/wiki/paypal/PayPal-NET-SDK/images/homepage.jpg" }, input_fields = new InputFields { no_shipping = 1 } }; // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Create new web experience profile (NOTE: This only needs to be done once)", profile); #endregion var createdProfile = profile.Create(apiContext); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(createdProfile); #endregion // Setup the redirect URI to use. The guid value is used to keep the flow information. var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?"; var guid = Convert.ToString((new Random()).Next(100000)); baseURI += "guid=" + guid + "&webProfileId=" + createdProfile.id; // Create the payment var payment = new Payment { intent = "sale", experience_profile_id = createdProfile.id, payer = new Payer { payment_method = "paypal" }, transactions = new List<Transaction> { new Transaction { description = "Ticket information.", item_list = new ItemList { items = new List<Item> { new Item { name = "Concert ticket", currency = "USD", price = "20.00", quantity = "2", sku = "ticket_sku" } } }, amount = new Amount { currency = "USD", total = "45.00", details = new Details { tax = "5.00", subtotal = "40.00" } } } }, redirect_urls = new RedirectUrls { return_url = baseURI + "&return=true", cancel_url = baseURI + "&cancel=true" } }; // ^ Ignore workflow code segment #region Track Workflow this.flow.AddNewRequest("Create PayPal payment", payment); #endregion var createdPayment = payment.Create(apiContext); // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordResponse(createdPayment); #endregion // Use the returned payment's approval URL to redirect the buyer to PayPal and approve the payment. var approvalUrl = createdPayment.GetApprovalUrl(); this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", approvalUrl); Session.Add(guid, createdPayment.id); Session.Add("flow-" + guid, this.flow); } else { var guid = Request.Params["guid"]; var webProfileId = Request.Params["webProfileId"]; var isReturnSet = Request.Params["return"]; // ^ Ignore workflow code segment #region Track Workflow this.flow = Session["flow-" + guid] as RequestFlow; this.RegisterSampleRequestFlow(); this.flow.RecordApproval("PayPal payment approved successfully."); #endregion if (string.IsNullOrEmpty(isReturnSet)) { // ^ Ignore workflow code segment #region Track Workflow this.flow.RecordApproval("PayPal payment canceled by buyer."); #endregion } else { // ^ Ignore workflow code segment #region Track Workflow 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 } // Cleanup - Because there's a limit to the number of experience profile IDs you can create, // we'll delete the one that was created for this sample. WebProfile.Delete(apiContext, webProfileId); // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/). } }
/// <summary> /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal. /// </summary> /// <param name="apiContext">APIContext used for the API call.</param> /// <param name="paymentExecution">PaymentExecution</param> /// <returns>Payment</returns> public Payment Execute(APIContext apiContext, PaymentExecution paymentExecution) { return(Payment.Execute(apiContext, this.id, paymentExecution)); }
public override PaymentResponse MakePayment() { try { #region Create Payment ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.DefaultConnectionLimit = 9999; var config = ConfigManager.Instance.GetProperties(); var accessToken = new OAuthTokenCredential(config).GetAccessToken(); var apiContext = new APIContext(accessToken); apiContext.Config = ConfigManager.Instance.GetProperties(); apiContext.Config["connectionTimeout"] = "30000"; if (apiContext.HTTPHeaders == null) { apiContext.HTTPHeaders = new Dictionary<string, string>(); } //apiContext.HTTPHeaders["some-header-name"] = "some-value"; string payerId = this.PayerId; if (string.IsNullOrEmpty(payerId)) { // ###Items // Items within a transaction. var itemList = new ItemList() { items = new List<Item>() { new Item() { name = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value : "Credits", currency = "USD", price = this.Amount.ToString(), quantity = "1", sku = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value : "Credits" } } }; // ###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 baseURI = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value != null ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value : "http://www.thedesignheroes.com/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 = this.TaxAmount.ToString(), shipping = "0", subtotal = this.Amount.ToString() }; // ###Amount // Let's you specify a payment amount. var amount = new Amount() { currency = "USD", total = this.Amount.ToString(),//"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 = String.Format(String.Format("{0}:{1}", this.CompanyId.ToString(), guid)), 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 }; // ^ 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(); string responseLink = ""; while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { responseLink = link.href; //this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href); } } //Session.Add(guid, createdPayment.id); //Session.Add("flow-" + guid, this.flow); #endregion return new PaymentResponse() { AuthCode = createdPayment.state,// executePayment.token, Message = createdPayment.token, // executePayment.state, MessageCode = createdPayment.intent, ResponseCode = responseLink, TransactionId = guid, TransactionResult = createdPayment.state }; } else { #region Execute Payment //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 = this.PaymentGuid; var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new PayPal.Api.Payment() { id = this.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 #endregion return new PaymentResponse() { AuthCode = executedPayment.cart, Message = executedPayment.payer.status, MessageCode = executedPayment.intent, ResponseCode = executedPayment.links[0].href, TransactionId = executedPayment.id, TransactionResult = executedPayment.state, }; } } catch (System.Exception exc) { return new PaymentResponse() { ErrorMessage = exc.Message, Message = exc.StackTrace, TransactionResult = String.Format("Paypal Error:{0}--{1}", exc.Message, exc.StackTrace) }; } }