示例#1
0
 public static List <T> MapCollectionFromJson(
     string json,
     string token = "data",
     StripeResponse stripeResponse = null)
 {
     return(JObject.Parse(json).SelectToken(token).Select(tkn => Mapper <T> .MapFromJson(tkn.ToString(), null, stripeResponse)).ToList());
 }
示例#2
0
        public static T MapFromJson(string json, string parentToken = null, StripeResponse stripeResponse = null)
        {
            T val = JsonConvert.DeserializeObject <T>(string.IsNullOrEmpty(parentToken) ? json : JObject.Parse(json).SelectToken(parentToken) !.ToString());

            applyStripeResponse(json, stripeResponse, val);
            return(val);
        }
        public void StripeResponse_NotSuccess()
        {
            var stripeResponse = new StripeResponse <string>();

            stripeResponse.Error = new StripeError();
            stripeResponse.Success.Should().BeFalse();
        }
示例#4
0
        private static StripeException BuildStripeException(StripeResponse response, HttpStatusCode statusCode, string requestUri, string responseContent)
        {
            var stripeError = requestUri.Contains("oauth")
                ? Mapper <StripeError> .MapFromJson(responseContent, null, response)
                : Mapper <StripeError> .MapFromJson(responseContent, "error", response);

            return(new StripeException(statusCode, stripeError, stripeError.Message));
        }
示例#5
0
        public static T MapFromJson(string json, string parentToken = null, StripeResponse stripeResponse = null)
        {
            var obj = JsonConvert.DeserializeObject <T>(String.IsNullOrEmpty(parentToken) ? json : JObject.Parse(json).SelectToken(parentToken).ToString());

            Mapper <T> .applyStripeResponse(json, stripeResponse, obj);

            return(obj);
        }
示例#6
0
 private static StripeException BuildInvalidResponseException(StripeResponse response)
 {
     return(new StripeException(
                response.StatusCode,
                null,
                $"Invalid response object from API: \"{response.Content}\"")
     {
         StripeResponse = response,
     });
 }
示例#7
0
        public async Task <StripeResponse> ChargeCustomer(StripeCharge charge)
        {
            //Dictionary<string, string> parameters = new Dictionary<string, string>();
            //parameters.Add("customerId", customerId);

            StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeCharge, StripeResponse>("StripeCharge", charge);

            StripeCard card = JsonConvert.DeserializeObject <StripeCard>(temp.ObjectJson);

            return(temp);
        }
示例#8
0
        private static StripeResponse BuildResponseData(HttpResponseMessage response, string responseText)
        {
            var result = new StripeResponse
            {
                RequestId    = response.Headers.Contains("Request-Id") ? response.Headers.GetValues("Request-Id").First() : "n/a",
                RequestDate  = Convert.ToDateTime(response.Headers.GetValues("Date").First(), CultureInfo.InvariantCulture),
                ResponseJson = responseText
            };

            return(result);
        }
示例#9
0
        private static StripeResponse BuildResponseData(HttpResponseMessage response, string responseText)
        {
            var result = new StripeResponse
            {
                RequestId = response.Headers.GetValues("Request-Id").First(),
                RequestDate = Convert.ToDateTime(response.Headers.GetValues("Date").First()),
                ResponseJson = responseText
            };

            return result;
        }
示例#10
0
        public async Task <StripeCard> RetreiveCreditCard(string customerId)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("customerId", customerId);

            StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeResponse>("Stripe", HttpMethod.Get, parameters);

            StripeCard card = JsonConvert.DeserializeObject <StripeCard>(temp.ObjectJson);

            return(card);
        }
示例#11
0
        public async Task <StripeResponse> CreateBankAccount(StripeBankAccount token)
        {
            try
            {
                StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeBankAccount, StripeResponse>("StripeBank", token);

                return(temp);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Stripe Failure", ex.Message, "OK");
            }
            return(null);
        }
示例#12
0
 private static void applyStripeResponse(string json, StripeResponse stripeResponse, object obj)
 {
     if (stripeResponse == null)
     {
         return;
     }
     foreach (var runtimeProperty in obj.GetType().GetRuntimeProperties())
     {
         if (runtimeProperty.Name == "StripeResponse")
         {
             runtimeProperty.SetValue(obj, stripeResponse);
         }
     }
     stripeResponse.ObjectJson = json;
 }
示例#13
0
        private static StripeException BuildStripeException(StripeResponse response, HttpStatusCode statusCode, string requestUri, string responseContent)
        {
            var stripeError = requestUri.Contains("oauth")
                ? Mapper <StripeError> .MapFromJson(responseContent, null, response)
                : Mapper <StripeError> .MapFromJson(responseContent, "error", response);

            string message = !string.IsNullOrEmpty(stripeError.Message)
                ? stripeError.Message
                : stripeError.ErrorDescription;

            return(new StripeException(statusCode, stripeError, message)
            {
                StripeResponse = response
            });
        }
示例#14
0
        public static PaymentResponseDao ToStripeResponseDao(this StripeResponse stripeResponse)
        {
            if (stripeResponse != null)
            {
                var stripeResponseDao = new PaymentResponseDao
                {
                    Content   = stripeResponse.Content,
                    RequestId = stripeResponse.RequestId,
                };

                return(stripeResponseDao);
            }

            return(null);
        }
示例#15
0
        public async Task RequestAsync_OkResponse()
        {
            var response = new StripeResponse(HttpStatusCode.OK, null, "{\"id\": \"ch_123\"}");

            this.httpClient.Response = response;

            var charge = await this.stripeClient.RequestAsync <Charge>(
                HttpMethod.Post,
                "/v1/charges",
                this.options,
                this.requestOptions);

            Assert.NotNull(charge);
            Assert.Equal("ch_123", charge.Id);
            Assert.Equal(response, charge.StripeResponse);
        }
示例#16
0
        public async Task <StripeResponse> CreateCreditCard(StripeTempToken token)
        {
            string JToken = JsonConvert.SerializeObject(token);
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("posttoken", JToken);
            try
            {
                StripeResponse temp = await cloudService.client.InvokeApiAsync <string, StripeResponse>("Stripe", JToken, HttpMethod.Post, parameters);

                return(temp);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Stripe Failure", ex.Message, "OK");
            }
            return(null);
        }
示例#17
0
        public async Task RequestAsync_OkResponse_InvalidJson()
        {
            var response = new StripeResponse(HttpStatusCode.OK, null, "this isn't JSON");

            this.httpClient.Response = response;

            var exception = await Assert.ThrowsAsync <StripeException>(async() =>
                                                                       await this.stripeClient.RequestAsync <Charge>(
                                                                           HttpMethod.Post,
                                                                           "/v1/charges",
                                                                           this.options,
                                                                           this.requestOptions));

            Assert.NotNull(exception);
            Assert.Equal(HttpStatusCode.OK, exception.HttpStatusCode);
            Assert.Equal("Invalid response object from API: \"this isn't JSON\"", exception.Message);
            Assert.Equal(response, exception.StripeResponse);
        }
示例#18
0
        public async Task <StripeBankAccount> RetreiveBankAccount(string customerId)
        {
            //string JToken = JsonConvert.SerializeObject(token);
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("customerId", customerId);
            try
            {
                StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeResponse>("StripeBank", HttpMethod.Get, parameters);

                StripeBankAccount bankAccount = JsonConvert.DeserializeObject <StripeBankAccount>(temp.ObjectJson);
                return(bankAccount);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Stripe Failure", ex.Message, "OK");
            }
            return(null);
        }
示例#19
0
        public async Task ExecuteSaveCardDetailsCommand()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;
            card   = new Card
            {
                Number      = _cardNumber,
                ExpiryMonth = int.Parse(_expirationDateM),
                ExpiryYear  = int.Parse(_expirationDateY),
                CVC         = _CVC.ToString()
            };
            try
            {
                var token = await StripeClient.CreateToken(card);

                var stripeService = (StripeService)ServiceLocator.Instance.Resolve <IStripeProvider>();

                StripeTempToken stripeToken = new StripeTempToken(token);
                StripeResponse  response    = await stripeService.CreateCreditCard(stripeToken);

                var loginProvider = DependencyService.Get <ILoginProvider>();

                Account acc = loginProvider.RetreiveAccountFromSecureStore();
                acc.Properties.Add(Constants.stripeAccountIdPropertyName, response.ObjectJson);
                loginProvider.SaveAccountInSecureStore(acc);

                Console.WriteLine("Response: " + response.RequestDate);
                // Slightly different for non-Apple Pay use, see
                // 'Sending the token to your server' for more info
                //await CreateBackendCharge(token);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Items Not Loaded", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
示例#20
0
        public async Task RequestAsync_Error_InvalidErrorObject()
        {
            var response = new StripeResponse(
                HttpStatusCode.InternalServerError,
                null,
                "{}");

            this.httpClient.Response = response;

            var exception = await Assert.ThrowsAsync <StripeException>(async() =>
                                                                       await this.stripeClient.RequestAsync <Charge>(
                                                                           HttpMethod.Post,
                                                                           "/v1/charges",
                                                                           this.options,
                                                                           this.requestOptions));

            Assert.NotNull(exception);
            Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
            Assert.Equal("Invalid response object from API: \"{}\"", exception.Message);
            Assert.Equal(response, exception.StripeResponse);
        }
示例#21
0
        public async Task RequestAsync_OAuthError()
        {
            var response = new StripeResponse(
                HttpStatusCode.BadRequest,
                null,
                "{\"error\": \"invalid_request\"}");

            this.httpClient.Response = response;

            var exception = await Assert.ThrowsAsync <StripeException>(async() =>
                                                                       await this.stripeClient.RequestAsync <OAuthToken>(
                                                                           HttpMethod.Post,
                                                                           "/oauth/token",
                                                                           this.options,
                                                                           this.requestOptions));

            Assert.NotNull(exception);
            Assert.Equal(HttpStatusCode.BadRequest, exception.HttpStatusCode);
            Assert.Equal("invalid_request", exception.StripeError.Error);
            Assert.Equal(response, exception.StripeResponse);
        }
示例#22
0
        public async Task RequestAsync_ApiError()
        {
            var response = new StripeResponse(
                HttpStatusCode.PaymentRequired,
                null,
                "{\"error\": {\"type\": \"card_error\"}}");

            this.httpClient.Response = response;

            var exception = await Assert.ThrowsAsync <StripeException>(async() =>
                                                                       await this.stripeClient.RequestAsync <Charge>(
                                                                           HttpMethod.Post,
                                                                           "/v1/charges",
                                                                           this.options,
                                                                           this.requestOptions));

            Assert.NotNull(exception);
            Assert.Equal(HttpStatusCode.PaymentRequired, exception.HttpStatusCode);
            Assert.Equal("card_error", exception.StripeError.ErrorType);
            Assert.Equal(response, exception.StripeResponse);
        }
示例#23
0
        private async Task ExecuteSaveBankDetailsCommand()
        {
            //Get account details
            string id;
            var loginProvider = DependencyService.Get<ILoginProvider>();
            Account acc = loginProvider.RetreiveAccountFromSecureStore();
            acc.Properties.TryGetValue("stripe_account_id", out id);

            var stripeService = (StripeService)ServiceLocator.Instance.Resolve<IStripeProvider>();

            StripeBankAccount stripeBankAccount = new StripeBankAccount()
            {
                account_holder_name = _accountHolderName,
                account_number = _accountNumber,
                currency = _currency,
                country = _country,
                customerId = id
            };

            StripeResponse response = await stripeService.CreateBankAccount(stripeBankAccount);
        }
示例#24
0
        private static StripeException BuildStripeException(StripeResponse response)
        {
            JObject jObject = null;

            try
            {
                jObject = JObject.Parse(response.Content);
            }
            catch (Newtonsoft.Json.JsonException)
            {
                return(BuildInvalidResponseException(response));
            }

            // If the value of the `error` key is a string, then the error is an OAuth error
            // and we instantiate the StripeError object with the entire JSON.
            // Otherwise, it's a regular API error and we instantiate the StripeError object
            // with just the nested hash contained in the `error` key.
            var errorToken = jObject["error"];

            if (errorToken == null)
            {
                return(BuildInvalidResponseException(response));
            }

            var stripeError = errorToken.Type == JTokenType.String
                ? StripeError.FromJson(response.Content)
                : StripeError.FromJson(errorToken.ToString());

            stripeError.StripeResponse = response;

            return(new StripeException(
                       response.StatusCode,
                       stripeError,
                       stripeError.Message ?? stripeError.ErrorDescription)
            {
                StripeResponse = response,
            });
        }
示例#25
0
        private static T ProcessResponse <T>(StripeResponse response)
            where T : IStripeEntity
        {
            if (response.StatusCode != HttpStatusCode.Created)
            {
                throw BuildStripeException(response);
            }

            T obj;

            try
            {
                obj = StripeEntity.FromJson <T>(response.Content);
            }
            catch (Newtonsoft.Json.JsonException)
            {
                throw BuildInvalidResponseException(response);
            }

            obj.StripeResponse = response;

            return(obj);
        }
示例#26
0
        internal async Task <StripeResponse <T> > GetStripeResponse <T>(HttpRequestMessage httpRequestMessage,
                                                                        CancellationToken cancellationToken)
        {
            var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(_configuration.SecretKey));

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            _httpClient.DefaultRequestHeaders.Add("Stripe-Version", _stripeVersion);
            using (var response = await _httpClient.SendAsync(httpRequestMessage, cancellationToken))
            {
                var content = await response.Content.ReadAsStringAsync();

                var stripeResponse = new StripeResponse <T>();
                if (response.IsSuccessStatusCode)
                {
                    stripeResponse.Model = Deserialize <T>(content);
                }
                else
                {
                    var errorEnvelope = Deserialize <StripeErrorEnvelope>(content);
                    stripeResponse.Error = errorEnvelope.Error;
                }
                return(stripeResponse);
            }
        }
 public void StripeResponse_Success()
 {
     var stripeResponse = new StripeResponse<string>();
     stripeResponse.Success.Should().BeTrue();
 }
 public void StripeResponse_NotSuccess()
 {
     var stripeResponse = new StripeResponse<string>();
     stripeResponse.Error = new StripeError();
     stripeResponse.Success.Should().BeFalse();
 }
        public void StripeResponse_Success()
        {
            var stripeResponse = new StripeResponse <string>();

            stripeResponse.Success.Should().BeTrue();
        }
示例#30
0
 public static T MapFromJson(StripeResponse stripeResponse, string parentToken = null)
 {
     return(Mapper <T> .MapFromJson(stripeResponse.ResponseJson, parentToken, stripeResponse));
 }
示例#31
0
 public static List <T> MapCollectionFromJson(StripeResponse stripeResponse, string token = "data")
 {
     return(Mapper <T> .MapCollectionFromJson(stripeResponse.ResponseJson, token, stripeResponse));
 }