private static async Task <U> MakeRequestAsync <T, U, EX>( string method, AuthenticationDetails auth, string path, NameValueCollection queryArguments, T payload, string baseUri, string contentType) where T : class where EX : ErrorResult { try { JsonSerializerSettings serialiserSettings = new JsonSerializerSettings(); serialiserSettings.NullValueHandling = NullValueHandling.Ignore; serialiserSettings.MissingMemberHandling = MissingMemberHandling.Ignore; serialiserSettings.Converters.Add(new EmailAddressConverter()); string uri = baseUri + path + NameValueCollectionExtension.ToQueryString(queryArguments); HttpClientHandler handler = new HttpClientHandler(); handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; HttpClient client = new HttpClient(handler); if (auth != null) { if (auth is OAuthAuthenticationDetails) { OAuthAuthenticationDetails oauthDetails = auth as OAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthDetails.AccessToken); } else if (auth is ApiKeyAuthenticationDetails) { ApiKeyAuthenticationDetails apiKeyDetails = auth as ApiKeyAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(apiKeyDetails.ApiKey + ":x"))); } else if (auth is BasicAuthAuthenticationDetails) { BasicAuthAuthenticationDetails basicDetails = auth as BasicAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(basicDetails.Username + ":" + basicDetails.Password))); } } HttpContent content = null; HttpResponseMessage response = null; if (method != "GET") { Stream s = new MemoryStream(); Stream requestStream = new MemoryStream(); if (payload != null) { using (System.IO.StreamWriter os = new System.IO.StreamWriter(s)) { if (contentType == APPLICATION_FORM_URLENCODED_CONTENT_TYPE) { os.Write(payload); } else { string json = JsonConvert.SerializeObject(payload, Formatting.None, serialiserSettings); os.Write(json); } await os.FlushAsync(); s.Seek(0, SeekOrigin.Begin); await s.CopyToAsync(requestStream); os.Dispose(); } requestStream.Seek(0, SeekOrigin.Begin); content = new StreamContent(requestStream); response = await client.PostAsync(uri, content); } else { response = await client.PostAsync(uri, null); } } else { response = await client.GetAsync(uri); } if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsStreamAsync(); if (resp == null) { return(default(U)); } { using (var sr = new System.IO.StreamReader(resp)) { var type = typeof(U); if (type.GetGenericTypeDefinition() == typeof(RateLimited <>)) { var responseType = type.GenericTypeArguments[0]; var result = JsonConvert.DeserializeObject(sr.ReadToEnd().Trim(), responseType, serialiserSettings); var status = new RateLimitStatus { Credit = response.Headers.Contains("X-RateLimit-Limit") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Limit").First()) : 0, Remaining = response.Headers.Contains("X-RateLimit-Remaining") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Remaining").First()) : 0, Reset = response.Headers.Contains("X-RateLimit-Reset") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Reset").First()) : 0 }; return((U)Activator.CreateInstance(type, result, status)); } return(JsonConvert.DeserializeObject <U>(sr.ReadToEnd().Trim(), serialiserSettings)); } } } else { switch (response.StatusCode) { case System.Net.HttpStatusCode.BadRequest: case System.Net.HttpStatusCode.Unauthorized: throw ThrowReworkedCustomException <EX>(response); case System.Net.HttpStatusCode.NotFound: default: throw new HttpRequestException(response.Content.ReadAsStringAsync().Result); } } } catch (Exception ex) { throw; } }
static U MakeRequest<T, U, EX>( string method, AuthenticationDetails auth, string path, NameValueCollection queryArguments, T payload, string baseUri, string contentType) where T : class where EX : ErrorResult { JsonSerializerSettings serialiserSettings = new JsonSerializerSettings(); serialiserSettings.NullValueHandling = NullValueHandling.Ignore; serialiserSettings.MissingMemberHandling = MissingMemberHandling.Ignore; #if SUPPORTED_FRAMEWORK_VERSION serialiserSettings.Converters.Add(new EmailAddressConverter()); #endif string uri = baseUri + path + NameValueCollectionExtension.ToQueryString(queryArguments); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); req.Method = method; req.ContentType = contentType; req.AutomaticDecompression = DecompressionMethods.GZip; if (auth != null) { if (auth is OAuthAuthenticationDetails) { OAuthAuthenticationDetails oauthDetails = auth as OAuthAuthenticationDetails; req.Headers["Authorization"] = "Bearer " + oauthDetails.AccessToken; } else if (auth is ApiKeyAuthenticationDetails) { ApiKeyAuthenticationDetails apiKeyDetails = auth as ApiKeyAuthenticationDetails; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(apiKeyDetails.ApiKey + ":x")); } else if (auth is BasicAuthAuthenticationDetails) { BasicAuthAuthenticationDetails basicDetails = auth as BasicAuthAuthenticationDetails; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(basicDetails.Username + ":" + basicDetails.Password)); } } req.UserAgent = string.Format("createsend-dotnet-#{0} .Net: {1} OS: {2} DLL: {3}", CreateSendOptions.VersionNumber, Environment.Version, Environment.OSVersion, Assembly.GetExecutingAssembly().FullName); if (method != "GET") { if (payload != null) { using (System.IO.StreamWriter os = new System.IO.StreamWriter(req.GetRequestStream())) { if (contentType == APPLICATION_FORM_URLENCODED_CONTENT_TYPE) os.Write(payload); else os.Write(JsonConvert.SerializeObject(payload, Formatting.None, serialiserSettings)); os.Close(); } } else req.ContentLength = 0; } try { using (var resp = (HttpWebResponse)req.GetResponse()) { if (resp == null) return default(U); else { using (var sr = new System.IO.StreamReader(resp.GetResponseStream())) { #if SUPPORTED_FRAMEWORK_VERSION var type = typeof(U); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RateLimited<>)) { var responseType = type.GetGenericArguments()[0]; var response = JsonConvert.DeserializeObject(sr.ReadToEnd().Trim(), responseType, serialiserSettings); var status = new RateLimitStatus { Credit = resp.Headers["X-RateLimit-Limit"].UInt(0), Remaining = resp.Headers["X-RateLimit-Remaining"].UInt(0), Reset = resp.Headers["X-RateLimit-Reset"].UInt(0) }; return (U)Activator.CreateInstance(type, response, status); } #endif return JsonConvert.DeserializeObject<U>(sr.ReadToEnd().Trim(), serialiserSettings); } } } } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { switch ((int)((HttpWebResponse)we.Response).StatusCode) { case 400: case 401: throw ThrowReworkedCustomException<EX>(we); case 404: default: throw we; } } else { throw we; } } }
public ActionResult SubscribeTour(TourShow tourShow) { try { if (!ModelState.IsValid) { foreach (var value in ModelState.Values.ToList()) { foreach (var error in value.Errors) { ModelState.AddModelError(string.Empty, error.ErrorMessage); } } tourShow.IsTripBooked = false; return PartialView("_Coming Soon", tourShow); } tourShow.IsTripBooked = true; if (tourShow.MailingListID != null) { AuthenticationDetails auth = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]); Subscriber objSubscriber = new Subscriber(auth, tourShow.MailingListID); string newSubscriberID = objSubscriber.Add(tourShow.EmailToSubscribe.ToString(), null, null, false); } return PartialView("_Coming Soon", tourShow); } catch (Exception e) { Elmah.ErrorSignal.FromCurrentContext().Raise(e); return PartialView("_Coming Soon"); } }
public void Authorize() { var auth = new ApiKeyAuthenticationDetails(_key); var general = new General(auth); }
public CampaignMonitorController() { _listID = ConfigurationManager.AppSettings["campaignMonitorListID"]; _auth = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["campaignMonitorAPIKey"]); }
public ActionResult AuthorizeNetSimGift(FormCollection post) { _logger.Info("keys: {0}", string.Join(", ", post.AllKeys)); var orderId = Convert.ToInt32(post["GiftOrderId"]); var userId = Convert.ToInt32(post["UserId"]); var order = _giftCardOrderService.FindOrder(orderId, userId); _logger.Info("Authorizing SIM..."); //the URL to redirect to- this MUST be absolute var successUrl = Url.RouteUrl("giftconfirmation", new { orderId = order.Id }, SecureProtocol); var failureUrl = Url.RouteUrl("billing-giftdetails", new { orderId = order.Id }, SecureProtocol); var redirectUrl = successUrl; var response = new SIMResponse(post); _logger.Info("Approved: {0}", response.Approved); _logger.Info("Code: {0}", response.ResponseCode); _logger.Info("Message: {0}", response.Message); _logger.Info("Authorization Code: {0}", response.AuthorizationCode); _logger.Info("Card Number: {0}", response.CardNumber); _logger.Info("Card Type: {0}", response.CardType); _logger.Info("Invoice Number: {0}", response.InvoiceNumber); _logger.Info("MD5 Hash: {0}", response.MD5Hash); _logger.Info("Transaction ID: {0}", response.TransactionID); //first order of business - validate that it was Authorize.Net that posted this using the //MD5 hash that was passed back to us var isValid = response.Validate(AuthorizeNetConfig.Md5HashValue, AuthorizeNetConfig.ApiLogin); _logger.Info("Valid: {0}", isValid); if (isValid && response.Approved) { _giftorderConfirmationMailer.SendGiftOrderConfirmationEmail(order); _giftCardOrderService.CompleteOrder(order, response.TransactionID); //Campaign Monitor -Adding subscriber to Gift card recipients List AuthenticationDetails auth = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]); Subscriber objSubscriber = new Subscriber(auth, ConfigurationManager.AppSettings["CampaignMonitorListID"]); for (int i = 0; i < order.GiftOrderDetail.Count; i++) { List<SubscriberCustomField> customFields = new List<SubscriberCustomField>(); customFields.Add(new SubscriberCustomField() { Key = "Amount", Value = order.GiftOrderDetail[i].Amount.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Your Name", Value = order.GiftOrderDetail[i].YourName.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Gift Code", Value = order.GiftOrderDetail[i].RecipientGiftCode.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Message", Value = order.GiftOrderDetail[i].Message.ToString() }); string newSubscriberID = objSubscriber.Add(order.GiftOrderDetail[i].RecipientEmail.ToString(), null, customFields, false); } } else { _giftCardOrderService.FailOrder(order, response.Message); redirectUrl = failureUrl; } return Content(AuthorizeNet.Helpers.CheckoutFormBuilders.Redirecter(redirectUrl)); }
public ActionResult Billing(Britespokes.Services.GiftCards.BillingDetails billingDetails) { //decimal GiftAmount = 0; //int OrderDetailId = 0; var order = _giftCardOrderService.FindOrder(billingDetails.GiftOrderId, UserContext.UserId); if (!billingDetails.AcceptedTermsAndConditions) ModelState.AddModelError("AcceptedTermsAndConditions", "you must accept the terms and conditions to purchase a tour"); if (order.OrderStatus != _giftCardOrderService.StatusPending()) ModelState.AddModelError("", "This order is no longer pending"); if (UserContext.IsGuest && string.IsNullOrEmpty(billingDetails.Password)) ModelState.AddModelError("Password", "required"); if (string.CompareOrdinal(billingDetails.Password, billingDetails.ConfirmPassword) != 0) ModelState.AddModelError("ConfirmPassword", "doesn't match"); if (ModelState.IsValid) { if (UserContext.IsGuest) { var user = _userService.Find(UserContext.UserId); _registrationService.PromoteGuest(user, billingDetails.Email, billingDetails.Password); _userMailer.SendWelcomeEmail(UserContext.Organization, user); } _giftCardOrderService.UpdateBillingDetails(billingDetails); //Campaign Monitor -Adding subscriber to Gift card recipients List AuthenticationDetails auth = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]); Subscriber objSubscriber = new Subscriber(auth, ConfigurationManager.AppSettings["CampaignMonitorListID"]); for (int i = 0; i < order.GiftOrderDetail.Count; i++) { List<SubscriberCustomField> customFields = new List<SubscriberCustomField>(); customFields.Add(new SubscriberCustomField() { Key = "Amount", Value = order.GiftOrderDetail[i].Amount ==null? "":order.GiftOrderDetail[i].Amount.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Your Name", Value = order.GiftOrderDetail[i].YourName == null ? "" : order.GiftOrderDetail[i].YourName.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Gift Code", Value = order.GiftOrderDetail[i].RecipientGiftCode == null ? "" : order.GiftOrderDetail[i].RecipientGiftCode.ToString() }); customFields.Add(new SubscriberCustomField() { Key = "Message", Value = order.GiftOrderDetail[i].Message == null ? "" : order.GiftOrderDetail[i].Message.ToString() }); string newSubscriberID = objSubscriber.Add(order.GiftOrderDetail[i].RecipientEmail.ToString(), null, customFields, false); } return Json(new { BillingDetails = billingDetails, Errors = new object[0] }); } billingDetails.BillingOverview = _giftCardOrderService.BuildBillingOverview(order); billingDetails.PaymentRequest = new PaymentRequest(order.Total, AuthorizeNetConfig.ApiLogin, AuthorizeNetConfig.TransactionKey, AuthorizeNetConfig.TestMode); return Json(new { BillingDetails = billingDetails, Errors = ModelStateErrorsForJson() }); }