コード例 #1
0
        public bool TryValidateToken(string authorizationParameter, out Audience audience)
        {
            audience = null;
            var token = _accessTokenRepository.GetAccessToken(Guid.Parse(authorizationParameter));
            var valid = Validate(token);

            if (!valid)
            {
                return(false);
            }
            var resourceId = token.AudienceId;

            //update the accesstoken expiredOn
            _accessTokenRepository.UpdateToken(token);
            audience = UserAudienceMapper(_accessTokenRepository.GetUser(long.Parse(resourceId)));
            return(true);
        }
コード例 #2
0
        public void Payment(string userId, string storeId, string cartId)
        {
            try
            {
                var customers = new StripeCustomerService();
                var charges   = new StripeChargeService();

                var userCardDetails = _receiptRepository.GetUserCardDetails(userId);
                if (userCardDetails == null)
                {
                    throw new Exception("Kreditkortsuppgifter existerar inte.");
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(userCardDetails.CreditCardId))
                    {
                        StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripPublishKey"]);
                        var tokenService = new StripeTokenService();


                        // Get token if user card is not created
                        var cardnumber = _cryptoGraphy.DecryptString(userCardDetails.CardNumber);

                        var token = tokenService.Create(new StripeTokenCreateOptions {
                            Card = new StripeCreditCardOptions {
                                Cvc = userCardDetails.CVC.ToString(), Number = cardnumber.Replace(" ", ""), ExpirationMonth = userCardDetails.ExpiredMonth, ExpirationYear = userCardDetails.ExpiredYear
                            }
                        });

                        // Create customer in stripe
                        StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]);
                        var customerId = customers.Create(new StripeCustomerCreateOptions {
                            SourceToken = token.Id
                        });

                        _receiptRepository.UpdateUserCreditCardId(customerId.Id, userId); //update customer id in database for future reference

                        var cartAmount     = _receiptRepository.GetCartAmount(cartId);
                        var tmpTotalAmount = (int)cartAmount;

                        var vat1        = (tmpTotalAmount * CommonConstants.Vat1InPercentage) / 100;
                        var vat2        = (tmpTotalAmount * CommonConstants.Vat2InPercentage) / 100;
                        var totalAmount = tmpTotalAmount + vat1 + vat2;

                        // Payment process
                        if (totalAmount > 0)
                        {
                            var paymentResponse = charges.Create(new StripeChargeCreateOptions {
                                Amount = totalAmount, Description = "Lifvs purchase item payment", Currency = "SEK", CustomerId = customerId.Id
                            });

                            if (paymentResponse.Status.Equals("succeeded", StringComparison.CurrentCultureIgnoreCase) && string.IsNullOrWhiteSpace(paymentResponse.FailureMessage))
                            {
                                var receiptId = _receiptRepository.AddReceiptItems(userId, storeId, cartId);
                                if (receiptId > 0)
                                {
                                    _receiptRepository.CreateTransaction(userId, paymentResponse.Status, paymentResponse.Id, paymentResponse.StripeResponse.ResponseJson, receiptId.ToString());
                                }

                                var receiptItmes = _receiptRepository.GetAllReceiptItems(receiptId.ToString());
                                var user         = _user.GetUser(Convert.ToInt64(userId));
                                SendEmail(user.Email, paymentResponse.Id, DateTime.Now.Date, storeId, receiptItmes);
                            }
                            else
                            {
                                throw new Exception(paymentResponse.FailureMessage);
                            }
                        }
                    }
                    else
                    {
                        StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]);

                        var cartAmount     = _receiptRepository.GetCartAmount(cartId);
                        var tmpTotalAmount = (int)cartAmount;
                        var vat1           = (tmpTotalAmount * CommonConstants.Vat1InPercentage) / 100;
                        var vat2           = (tmpTotalAmount * CommonConstants.Vat2InPercentage) / 100;
                        var totalAmount    = tmpTotalAmount + vat1 + vat2;

                        // Payment process
                        if (totalAmount > 0)
                        {
                            var paymentResponse = charges.Create(new StripeChargeCreateOptions {
                                Amount = totalAmount, Description = "Lifvs purchase item payment", Currency = "SEK", CustomerId = userCardDetails.CreditCardId
                            });

                            if (paymentResponse.Status.Equals("succeeded", StringComparison.CurrentCultureIgnoreCase) && string.IsNullOrWhiteSpace(paymentResponse.FailureMessage))
                            {
                                var receiptId = _receiptRepository.AddReceiptItems(userId, storeId, cartId);
                                if (receiptId > 0)
                                {
                                    _receiptRepository.CreateTransaction(userId, paymentResponse.Status, paymentResponse.Id, paymentResponse.StripeResponse.ResponseJson, receiptId.ToString());
                                }

                                var receiptItmes = _receiptRepository.GetAllReceiptItems(receiptId.ToString());
                                var user         = _user.GetUser(Convert.ToInt64(userId));
                                SendEmail(user.Email, paymentResponse.Id, DateTime.Now.Date, storeId, receiptItmes);
                            }
                            else
                            {
                                throw new Exception(paymentResponse.FailureMessage);
                            }
                        }
                    }
                }
            }
            catch (StripeException ex)
            {
                switch (ex.StripeError.ErrorType)
                {
                case "card_error":
                    throw new Exception(ex.StripeError.Message);

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
            }
        }
コード例 #3
0
ファイル: UserService.cs プロジェクト: dev-ips/Lifvs-Server
        public bool AddUserCardDetails(UserCardDetailModel model)
        {
            try
            {
                _userCardDetailValidators.Validate(model);
                var errorMessage        = string.Empty;
                var userCardDetailModel = new UserCardDetailModel();
                var user = _accessTokenRepository.GetUser(model.UserId.Value);

                if (user == null)
                {
                    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Användare finns inte.");
                }

                //var cardExist = _userRepository.GetUserCardDetailByCardNumber(model.CardNumber, model.UserId.Value);

                //if (cardExist != null)
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Kortnummer finns redan.");


                //if (response.CvcCheck.ToLower() != "pass")
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Card is not valid.");

                //var isValidCard = CreditCardHelper.IsCardNumberValid(model.CardNumber, out errorMessage);
                //if (!isValidCard)
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", errorMessage);


                var updateCard = UpdateUserCard(model);
                if (!updateCard)
                {
                    var customers = new StripeCustomerService();

                    StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripPublishKey"]);
                    var tokenService = new StripeTokenService();

                    var token = tokenService.Create(new StripeTokenCreateOptions {
                        Card = new StripeCreditCardOptions {
                            Cvc = model.CVC.ToString(), Number = model.CardNumber.Replace(" ", ""), ExpirationMonth = model.ExpiredMonth, ExpirationYear = model.ExpiredYear
                        }
                    });

                    StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]);
                    var customerId = customers.Create(new StripeCustomerCreateOptions {
                        SourceToken = token.Id
                    });
                    var cardType           = CreditCardHelper.GetCardType(model.CardNumber);
                    StripeCardService card = new StripeCardService();
                    var cardToken          = CreditCardHelper.GetCardTokens(token.StripeCard.Brand);
                    var response           = card.Create(customerId.Id, new StripeCardCreateOptions {
                        SourceToken = cardToken
                    });

                    var userCardDetails = new UserCardDetails
                    {
                        UserId       = model.UserId,
                        CardNumber   = _cryptoGraphy.EncryptString(model.CardNumber),
                        CardType     = cardType.ToString(),
                        ExpiredMonth = model.ExpiredMonth,
                        ExpiredYear  = model.ExpiredYear,
                        CVC          = model.CVC,
                        CreditCardId = customerId.Id,
                        PhoneNumber  = model.PhoneNumber,
                        CreatedDate  = DateTime.Now,
                        ModifiedDate = DateTime.Now
                    };
                    var userCardDetailId = _userRepository.AddUserCardDetails(userCardDetails);
                }
            }
            catch (StripeException ex)
            {
                switch (ex.StripeError.ErrorType)
                {
                case "card_error":
                    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", ex.StripeError.Message);

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
            }
            return(true);
        }