private static APIContext GetAPIContext(string clientId, string secretKey, string token = null) { APIContext apiContext = null; if (string.IsNullOrWhiteSpace(token)) { var accessToken = new OAuthTokenCredential(clientId, secretKey); apiContext = new APIContext(accessToken.GetAccessToken()); } else { apiContext = new APIContext(token); } var config = new Dictionary <string, string>(); config.Add("mode", "sandbox"); config.Add("clientId", clientId); config.Add("clientSecret", secretKey); apiContext.Config = config; return(apiContext); }
public APIContext GetApiContext() { config = PayPal.Api.ConfigManager.Instance.GetProperties(); auth = new OAuthTokenCredential(config); apiContext = new APIContext(auth.GetAccessToken()); return(apiContext); }
private PayPalRest.Payment CreatePayPalPayment(PaymentProcessingContext request, PayPalConfig settings) { var config = new Dictionary <string, string>(); config.Add("mode", settings.SandboxMode ? "sandbox" : "live"); var credentials = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret, config); var accessToken = credentials.GetAccessToken(); var payment = new PayPalRest.Payment { intent = "sale", payer = new Payer { payment_method = "credit_card", funding_instruments = new List <PayPalRest.FundingInstrument> { new PayPalRest.FundingInstrument { credit_card = CreateCreditCard(request) } } }, transactions = new List <Transaction> { CreateTransaction(request) } }; return(payment.Create(new APIContext(accessToken) { Config = config })); }
//Retriving the Token public static string GetPayPalToken() { OAuthTokenCredential tokenCredential = new OAuthTokenCredential(clientID, clientSecret); string accessToken = tokenCredential.GetAccessToken(); return(accessToken); }
/// <summary> /// Validates the received WebHook. /// </summary> /// <param name="context">The current <see cref="HttpRequestContext"/>.</param> /// <param name="headers">The request headers for the current <see cref="HttpRequestMessage"/>.</param> /// <param name="body">The request body for the current <see cref="HttpRequestMessage"/>.</param> /// <returns><c>true</c> if received WebHook is valid; <c>false</c> otherwise.</returns> protected virtual bool ValidateReceivedEvent(HttpRequestContext context, NameValueCollection headers, string body) { if (context == null) { throw new ArgumentNullException("context"); } // Get existing or new access token. We put a lock around it as it is not thread safe otherwise. string accessToken; lock (_thisLock) { accessToken = _credentials.GetAccessToken(); } APIContext apiContext = new APIContext(accessToken); apiContext.Config = _config; try { bool isValid = WebhookEvent.ValidateReceivedEvent(apiContext, headers, body); if (!isValid) { context.Configuration.DependencyResolver.GetLogger().Error(PaypalReceiverResources.Receiver_InvalidWebHook); } return(isValid); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, PaypalReceiverResources.Receiver_ValidationFailure, ex.Message); context.Configuration.DependencyResolver.GetLogger().Error(msg, ex); } return(false); }
public void OAuthTokenCredentialMissingClientSecretTest() { var config = ConfigManager.Instance.GetProperties(); config[BaseConstants.ClientSecret] = ""; var oauthTokenCredential = new OAuthTokenCredential(config); TestingUtil.AssertThrownException <MissingCredentialException>(() => oauthTokenCredential.GetAccessToken()); }
/// <summary> /// Helper method for getting an access token for test purposes. /// </summary> /// <param name="endpoint"></param> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <returns></returns> private string GetAccessToken(string endpoint, string clientId, string clientSecret) { Dictionary <string, string> config = new Dictionary <string, string>(); config.Add("endpoint", endpoint); OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config); return(target.GetAccessToken()); }
public void GetAccessTokenTimeoutTest() { Dictionary <string, string> config = new Dictionary <string, string>(); config[BaseConstants.ApplicationModeConfig] = BaseConstants.SandboxMode; config[BaseConstants.HttpConnectionTimeoutConfig] = "10"; OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config); string accessToken = target.GetAccessToken(); }
private string _GetAccessToken() { var config = new Dictionary <string, string>() { { "mode", mode }, { "clientId", clientId }, { "clientSecret", clientSecret } }; var authCredential = new OAuthTokenCredential(config); return(authCredential.GetAccessToken()); }
public string PayPalExecutePayment(string PaymentID, string PayerID, string intent, string orderId, string token, string returnURL, string param) { try { Payment payment = new Payment() { id = PaymentID, intent = intent, redirect_urls = new RedirectUrls() { cancel_url = Url.Action("PayPalCreatePaymentCancel"), return_url = Url.Action("PayPalCreatePaymentReturn") }, payer = new Payer() { payment_method = "paypal" }, transactions = new List <Transaction>() { { new Transaction() { amount = new Amount() { total = "2.02", currency = "USD", } } }, }, note_to_payer = "Test Payment" }; string accessToken; OAuthTokenCredential oAuth = new OAuthTokenCredential(PayPalConfig.clientId, PayPalConfig.secretKey); accessToken = oAuth.GetAccessToken(); APIContext aPIContext = new APIContext(accessToken); PaymentExecution paymentExecution = new PaymentExecution() { payer_id = PayerID }; Payment result = payment.Execute(aPIContext, paymentExecution); string resultString = result.ConvertToJson(); return(resultString); } catch (PayPalException e) { return(null); } }
public static string GetAccessToken() { // getting accesstocken from paypal Dictionary <string, string> payPalConfig = new Dictionary <string, string>(); payPalConfig.Add("mode", "sandbox"); OAuthTokenCredential tokenCredential = new OAuthTokenCredential("ASruoAku7oJbb-4zt4sLVmSSBThKIV1VZVRqMYP93_sBa8Liur4vHGP06oW52sWPUg83rk0aMQqRJP5D", "EHCjwj5usvcil1wcwfSt3KVEG4KKuIs6ZQeX4wCT3I3D51DGr5jI9WpLJiF9jPGFaLafH2axYye6g1uL", payPalConfig); string accessToken = tokenCredential.GetAccessToken(); // string accessToken = new OAuthTokenCredential //(ClientId, ClientSecret, GetConfig()).GetAccessToken(); return(accessToken); }
public void GetAccessTokenInvalidEndpointTest() { Dictionary <string, string> config = new Dictionary <string, string>(); config.Add("endpoint", "https://localhost.sandbox.paypal.com"); string clientId = "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM"; string clientSecret = "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"; OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config); string expected = string.Empty; string actual; actual = target.GetAccessToken(); Assert.AreEqual(true, actual.StartsWith("Bearer ")); }
public void OAuthTokenCredentialGetAccessTokenTest() { try { var oauthTokenCredential = new OAuthTokenCredential(); var accessToken = oauthTokenCredential.GetAccessToken(); this.RecordConnectionDetails(); Assert.IsTrue(accessToken.StartsWith("Bearer ")); } catch (ConnectionException) { this.RecordConnectionDetails(false); throw; } }
public void OAuthTokenCredentialInvalidClientSecretTest() { try { var config = ConfigManager.Instance.GetProperties(); config[BaseConstants.ClientSecret] = "abc"; var oauthTokenCredential = new OAuthTokenCredential(config); TestingUtil.AssertThrownException <IdentityException>(() => oauthTokenCredential.GetAccessToken()); this.RecordConnectionDetails(); } catch (ConnectionException) { this.RecordConnectionDetails(false); throw; } }
public string PayPalCreatePayment() { try { Payment payment = new Payment() { intent = "sale", redirect_urls = new RedirectUrls() { cancel_url = Url.Action("PayPalCreatePaymentCancel"), return_url = Url.Action("PayPalCreatePaymentReturn") }, payer = new Payer() { payment_method = "paypal" }, transactions = new List <Transaction>() { { new Transaction() { amount = new Amount() { total = "2.01", currency = "USD", } } }, }, note_to_payer = "Test Payment" }; // make the call! string accessToken; OAuthTokenCredential oAuth = new OAuthTokenCredential(PayPalConfig.clientId, PayPalConfig.secretKey); accessToken = oAuth.GetAccessToken(); APIContext aPIContext = new APIContext(accessToken); Payment result = payment.Create(aPIContext); string resultString = result.ConvertToJson(); return(resultString); } catch (PayPalException e) { return(null); } }
public static string GetPayPalAccessToken() { string ClientID = (mode == Environment.sandbox ? "ARTy9lorp45zSyhnQtvYJKstGnkqORNlXazL_0ffl8blI164XHHBlHeVA3aex0ur4byEvuThuU33zQCW" : //SANDBOX "AYDMFeIOCHQNXp-coIUc_Q1VHkPEjaPUdD6Hp94teg9-VlarHtiuTQBzE2C5f0tm37Uj6kSCu9e5GyWO"); //LIVE string Secret = (mode == Environment.sandbox ? "EKv5bZFltlefyO4E2y-634orP1D7nHG_JLgOohDpW6rBRkK4PDsk5uklcDLscf0_11yyk6D4EdZ_IWJY" : //SANDBOX "EPbGPxMUv9-WXJb_V57bZnXBnP4p0XZgFRn4jM3mE-ZHxQVtMYkvBDx46x9Rrd3b2qCwqDDVJdSf5nA1"); //LIVE Dictionary <string, string> payPalConfig = new Dictionary <string, string>(); payPalConfig.Add("mode", mode.ToString()); OAuthTokenCredential otc = new OAuthTokenCredential(ClientID, Secret, payPalConfig); return(otc.GetAccessToken()); }
public bool TestCredentials(PayPalClientCredentials payPalClientSettings, PayPalServerCredentials payPalServerSettings, bool isSandbox) { try { var payPalMode = isSandbox ? BaseConstants.SandboxMode : BaseConstants.LiveMode; var config = new Dictionary <string, string> { { BaseConstants.ApplicationModeConfig, payPalMode } }; var tokenCredentials = new OAuthTokenCredential(payPalClientSettings.ClientId, payPalServerSettings.Secret, config); var accessToken = tokenCredentials.GetAccessToken(); return(accessToken.HasValue()); } catch (Exception) { return(false); } }
public string GetAccessToken(string clientId, string clientSecret, string mode) { var config = GetConfig(mode); var credential = new OAuthTokenCredential(clientId, clientSecret, config); var accessToken = string.Empty; try { accessToken = credential.GetAccessToken(); if (string.IsNullOrEmpty(accessToken)) { throw new PayPalException("Paypal returned empty access token"); } _logger.LogInformation("Access token retrieved from Paypal"); } catch (Exception ex) { ex = ex.ToInner(); _logger.LogError(ex, ex.Message); } return(accessToken); }
/// <summary> /// Helper: Holt von PayPal ein neues Accesstoken. /// </summary> /// <returns></returns> public APIContext GetPayPalToken() { var config = new Dictionary <string, string>(); config.Add("clientId", ConfigurationManager.AppSettings["PayPal:Username"]); config.Add("clientSecret", ConfigurationManager.AppSettings["PayPal:Password"]); if (ConfigurationManager.AppSettings["PayPal:Sandbox"] != "False") { config.Add("mode", "sandbox"); } var tokenCredential = new OAuthTokenCredential( config["clientId"], config["clientSecret"], config); var apiContext = new APIContext(tokenCredential.GetAccessToken()); apiContext.Config = config; return(apiContext); }
/// <summary> /// ตัดบัตรเครดิต /// </summary> /// <param name="payment">ข้อมูลบัตรเครดิตที่ต้องการดำเนินการ</param> public PaymentResult ChargeCreditCard(PaymentInformation paymentInfo) { var tokenCredential = new OAuthTokenCredential(_appConfig.PaypalClientId, _appConfig.PaypalClientSecret, new Dictionary <string, string>()); var accessToken = tokenCredential.GetAccessToken(); var config = new Dictionary <string, string>(); config.Add("mode", "sandbox"); // HACK: Paypal mode ('live' or 'sandbox') var apiContext = new APIContext { Config = config, AccessToken = accessToken }; // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it. var transaction = new Transaction() { amount = new Amount() { currency = "USD", total = paymentInfo.TotalPrice.ToString(), details = new Details() { shipping = "0", subtotal = paymentInfo.TotalPrice.ToString(), tax = "0" } }, description = $"User { paymentInfo.UserProfileId } pay { paymentInfo.TotalPrice.ToString("C2") } for course { paymentInfo.PurchaseForCourseId }", }; // A resource representing a Payer that funds a payment. var payer = new Payer() { payment_method = "credit_card", funding_instruments = new List <FundingInstrument>() { new FundingInstrument() { credit_card = new CreditCard() { billing_address = new Address() { city = paymentInfo.City, country_code = paymentInfo.Country, line1 = paymentInfo.Address, postal_code = paymentInfo.PostalCode, state = paymentInfo.State }, cvv2 = paymentInfo.CVV, expire_month = paymentInfo.ExpiredMonth, expire_year = paymentInfo.ExpiredYear, first_name = paymentInfo.FirstName, last_name = paymentInfo.LastName, number = paymentInfo.CreditCardNumber, type = paymentInfo.CardType.ToLower() } } }, payer_info = new PayerInfo { email = paymentInfo.UserProfileId } }; // 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 = new List <Transaction>() { transaction } }; // Create a payment using a valid APIContext var createdPayment = payment.Create(apiContext); var result = PaymentResult.Unknow; return(Enum.TryParse <PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow); }
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 void GetAccessTokenTest() { Dictionary<string, string> config = new Dictionary<string, string>(); config.Add("endpoint", "https://api.sandbox.paypal.com"); string clientId = "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM"; string clientSecret = "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"; OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config); string expected = string.Empty; string actual; actual = target.GetAccessToken(); Assert.AreEqual(true, actual.StartsWith("Bearer ")); }
public String SubmitRechargeInfo(String paymentId, String amount, String paymentTime) { OAuthTokenCredential oa = new OAuthTokenCredential("AQmW6s0chChHeblhmaIYQda6Bn1gmfSSUnvUCHNCLZM_7BiLOb5BMrINuIxUswdG8Prb8K3ktHQpZuho", "ENQKqkutUnKuTGBWiNDvJ_sA131lwCU4c1eaJwFcn58M88LtjHJd9TLgvjT4nuXkruuSkD0OF0u_XP_W"); PayPal.Api.APIContext apiContext = new PayPal.Api.APIContext(oa.GetAccessToken()); try { Payment payment = PayPal.Api.Payment.Get(apiContext, paymentId); if (payment == null || String.IsNullOrEmpty(payment.id)) { return("11"); } } catch (Exception ex) { return("11"); } LoginViewModel user = Utils.GetUserInfo(); PaymentInfo pInfo = null; using (DSLEntities entity = new DSLEntities()) { pInfo = entity.PaymentInfo.Where(a => a.UserId.ToString() == user.UserId && a.PaymentId == paymentId).ToList().FirstOrDefault(); } if (pInfo != null) { return("1"); } UserInfo existingData = null; using (DSLEntities entity = new DSLEntities()) { existingData = entity.UserInfo.Where(a => a.UserId.ToString() == user.UserId).ToList().FirstOrDefault(); } if (existingData != null) { using (DSLEntities entity = new DSLEntities()) { existingData.Balance += decimal.Parse(amount); entity.Entry(existingData).State = System.Data.Entity.EntityState.Modified; entity.SaveChanges(); } } PaymentInfo addPayInfo = new PaymentInfo(); addPayInfo.Amount = Decimal.Parse(amount); addPayInfo.PaymentId = paymentId; addPayInfo.PaymentState = "Approval"; addPayInfo.PaymentType = "PayPal"; addPayInfo.UserId = int.Parse(user.UserId); addPayInfo.PaymentTime = DateTime.Parse(paymentTime); using (DSLEntities entity = new DSLEntities()) { entity.PaymentInfo.Add(addPayInfo); entity.SaveChanges(); } return("0"); }
public PaymentHandler() { Dictionary <string, string> config = PayPal.Api.ConfigManager.Instance.GetProperties(); OAuthTokenCredential auth = new OAuthTokenCredential(config); string accessToken = auth.GetAccessToken(); var apiContext = new APIContext(accessToken); var payer = new Payer() { payment_method = "paypal" }; var guid = Convert.ToString((new Random()).Next(100000)); var redirUrls = new RedirectUrls() { cancel_url = "http://localhost:3000/cancel", return_url = "http://localhost:3000/process" }; var itemList = new ItemList() { items = new List <Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } }; var details = new Details() { tax = "15", shipping = "10", subtotal = "75" }; var amount = new Amount() { currency = "USD", total = "100.00", // 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 = "123", amount = amount, item_list = itemList }); var payment = new Payment() { intent = "sale", payer = payer, redirect_urls = redirUrls, transactions = transactionList }; var createdPayment = payment.Create(apiContext); var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { // REDIRECT USER TO link.href HttpContext.Current.Response.Redirect(link.href); // } } }
private static string GetAccessToken() { var oauth = new OAuthTokenCredential(GetConfig()); return(oauth.GetAccessToken()); }
private static string GetAccessToken() { var oauth = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()); return(oauth.GetAccessToken()); }
// 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) { } }