Ejemplo n.º 1
0
        /// <summary>
        /// Creates a new <see cref="VirgilCard"/> by request.
        /// </summary>
        /// <param name="request">The request.</param>
        public static async Task <VirgilCard> CreateAsync(CreateCardRequest request)
        {
            var client = VirgilConfig.GetService <VirgilClient>();
            var card   = await client.CreateCardAsync(request).ConfigureAwait(false);

            return(new VirgilCard(card));
        }
Ejemplo n.º 2
0
        public async Task <Card> CreateNewCard(CreateCardRequest createCardRequest)
        {
            var s = await _unitOfWork.GetRepository <Card>().FindAsync(x => x.PatientId == createCardRequest.PatientId);

            var p = await _unitOfWork.GetRepository <Patient>().FindAsync(x => x.Id == createCardRequest.PatientId);

            if (s != null)
            {
                throw new Exception("Bệnh nhân đã có thẻ");
            }

            if (p == null)
            {
                throw new Exception("Bệnh nhân không tồn tại trong hệ thống");
            }

            var card = new Card
            {
                Id          = newCardID(),
                CardNumber  = newCardNumber(),
                Money       = createCardRequest.Money,
                CreatedDate = DateTime.Now,
                ExpiredDate = DateTime.Now.AddYears(1),
                PatientId   = createCardRequest.PatientId,
                CreatedBy   = createCardRequest.CreatedBy,
                Status      = 1
            };

            _unitOfWork.GetRepository <Card>().Add(card);
            await _unitOfWork.CommitAsync();

            return(card);
        }
Ejemplo n.º 3
0
        public async Task Should_Create_User_And_Add_Card()
        {
            string          externalUserId  = RandomGenerator.RandomId;
            CardInformation cardInformation = CardInformationBuilder
                                              .Create()
                                              .Build();

            CreateCardRequest createCardRequest = CreateCardRequestBuilder.Create()
                                                  .Card(cardInformation)
                                                  .ExternalId(externalUserId)
                                                  .Email("*****@*****.**")
                                                  .Build();

            Card card = await Card.CreateAsync(createCardRequest, Options);

            PrintResponse(card);

            Assert.AreEqual(Locale.TR.ToString(), card.Locale);
            Assert.AreEqual(Status.SUCCESS.ToString(), card.Status);
            Assert.NotNull(card.SystemTime);
            Assert.AreEqual("123456789", card.ConversationId);
            Assert.AreEqual("*****@*****.**", card.Email);
            Assert.AreEqual("552879", card.BinNumber);
            Assert.AreEqual("card alias", card.CardAlias);
            Assert.AreEqual("CREDIT_CARD", card.CardType);
            Assert.AreEqual("MASTER_CARD", card.CardAssociation);
            Assert.AreEqual("Paraf", card.CardFamily);
            Assert.AreEqual("Halk Bankası", card.CardBankName);
            Assert.True(card.CardBankCode.Equals(12L));
        }
        public async Task CreateNewVirgilCard_SignatureValidation_ShouldPassValidation()
        {
            var crypto = new VirgilCrypto();
            var client = IntergrationHelper.GetVirgilClient();

            // CREATING A VIRGIL CARD

            var appKey = crypto.ImportPrivateKey(IntergrationHelper.AppKey, IntergrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();
            var request       = new CreateCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntergrationHelper.AppID, appKey);

            var aliceCard = await client.CreateCardAsync(request);

            // VALIDATING A VIRGIL CARD

            var appPublicKey         = crypto.ExtractPublicKey(appKey);
            var exportedAppPublicKey = crypto.ExportPublicKey(appPublicKey);

            var validator = new CardValidator(crypto);

            validator.AddVerifier(IntergrationHelper.AppID, exportedAppPublicKey);

            validator.Validate(aliceCard).Should().BeTrue();

            await IntergrationHelper.RevokeCard(aliceCard.Id);
        }
        public async Task CreateNewVirgilCard_IdentityAndPublicKeyGiven_ShouldBeFoundByIdentity()
        {
            var crypto = new VirgilCrypto();
            var client = IntergrationHelper.GetVirgilClient();

            var appKey = crypto.ImportPrivateKey(IntergrationHelper.AppKey, IntergrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();

            var request = new CreateCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntergrationHelper.AppID, appKey);

            var newCard = await client.CreateCardAsync(request);

            var cards = await client.SearchCardsAsync(new SearchCriteria { Identities = new[] { aliceIdentity } });

            cards.Should().HaveCount(1);
            var foundCard = cards.Single();

            newCard.ShouldBeEquivalentTo(foundCard);
        }
Ejemplo n.º 6
0
        private static void TryCreatePrefab(CreateCardRequest request, GameObject card)
        {
            string newPrefabAssetPath = string.Format("Assets/Prefabs/Resources/Cards/{0}/{1}/{2}.prefab",
                                                      request.Classification,
                                                      request.CardType == Type.Match ? "Matches" : request.CardType + "s",
                                                      request.CardName);

            if (request.Classification == ClassificationTypes.Character || request.Classification == ClassificationTypes.Adventure)
            {
                var stringToRemove = request.Classification + "/";
                newPrefabAssetPath = newPrefabAssetPath.Replace(stringToRemove, "");
            }

            if (AssetDatabase.LoadAssetAtPath(newPrefabAssetPath, typeof(GameObject)))
            {
                string message = string.Format("A prefab already exists at\n{0}\nReplace?", newPrefabAssetPath);

                if (EditorUtility.DisplayDialog("Prefab already exists", message, "Yes", "No"))
                {
                    CreatePrefab(newPrefabAssetPath, card);
                }
            }
            else
            {
                CreatePrefab(newPrefabAssetPath, card);
            }
        }
        public async Task GetSignleVirgilCard_ByGivenId_ShouldReturnVirgilCard()
        {
            var crypto        = new VirgilCrypto();
            var client        = IntergrationHelper.GetVirgilClient();
            var requestSigner = new RequestSigner(crypto);

            var appKey = crypto.ImportPrivateKey(IntergrationHelper.AppKey, IntergrationHelper.AppKeyPassword);

            // Prepare Requests

            var aliceIdentity  = "alice-" + Guid.NewGuid();
            var aliceKeys      = crypto.GenerateKeys();
            var alicePublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceRequest = new CreateCardRequest(aliceIdentity, "member", alicePublicKey);

            requestSigner.SelfSign(aliceRequest, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(aliceRequest, IntergrationHelper.AppID, appKey);

            var aliceCard = await client.CreateCardAsync(aliceRequest);

            var foundAliceCard = await client.GetCardAsync(aliceCard.Id);

            aliceCard.ShouldBeEquivalentTo(foundAliceCard);

            await IntergrationHelper.RevokeCard(aliceCard.Id);
        }
Ejemplo n.º 8
0
        public BaseResponse <GetCardResponse> CreateCard(string customerId, CreateCardRequest request)
        {
            var method   = HttpMethod.Post;
            var endpoint = $"/customers/{customerId}/cards";

            return(this.HttpClientUtil.SendRequest <GetCardResponse>(method, endpoint, request));
        }
Ejemplo n.º 9
0
        private static void AddChosenComponents(CreateCardRequest request, GameObject card)
        {
            if (request.AddLessonRequirement)
            {
                if (request.CardType == Type.Adventure)
                {
                    var newComponent = card.AddComponent <GenericLessonRequirement>();
                    newComponent.AmountRequired = request.LessonAmtRequired;
                }
                else
                {
                    var newComponent = card.AddComponent <LessonRequirement>();
                    newComponent.AmountRequired = request.LessonAmtRequired;
                    newComponent.LessonType     = request.LessonType;
                }
            }

            if (request.AddCardLimit)
            {
                var newComponent = card.AddComponent <DeckCardLimitRequirement>();
                newComponent.MaximumAmountAllowed = request.MaxAllowedInDeck;
            }

            if (request.AddExistingScript)
            {
                var scriptType = request.AttachedScript.GetClass();

                var newComponent = (BaseCard)card.AddComponent(scriptType);
                newComponent.Classification = request.Classification;
                newComponent.Rarity         = request.Rarity;
            }
        }
        public async Task Should_Return_CreatedResult_With_Correct_Data()
        {
            // Arrange
            var request = new CreateCardRequest
            {
                Number         = "xxxx-xxxx-xxxx-xxx",
                CardHolder     = "Filipe A. L. Souza",
                ExpirationDate = new DateTime(2022, 1, 12),
            };

            var commandResult = new CreateCardCommandResult(
                id: Guid.NewGuid(),
                number: "xxxx-xxxx-xxxx-xxx",
                cardHolder: "Filipe A. L. Souza",
                expirationDate: new DateTime(2022, 1, 12),
                success: true
                );

            commandDispatcherMock
            .Setup(x => x.Dispatch(It.IsAny <CreateCardCommand>()))
            .ReturnsAsync(commandResult);

            // Act
            var actionResult = await sut.Post(request);

            // Assert
            var createdResult = Assert.IsType <CreatedAtActionResult>(actionResult);
            var response      = Assert.IsAssignableFrom <CreateCardResponse>(createdResult.Value);

            AssertResponse(commandResult, response);
        }
Ejemplo n.º 11
0
        public void AlteraCartaoEmAssinatura(string id_Api, CreateCardRequest cartaoApi, string idCartaoDb)
        {
            try
            {
                // Secret key fornecida pela Mundipagg
                string basicAuthUserName = SistemaSingleton.Instancia.TokenApi;
                // Senha em branco. Passando apenas a secret key
                string basicAuthPassword = "";

                var client = new MundiAPIClient(basicAuthUserName, basicAuthPassword);

                var assinaturaApi = new UpdateSubscriptionCardRequest
                {
                    Card = cartaoApi
                };

                var response = client.Subscriptions.UpdateSubscriptionCard(id_Api, assinaturaApi);

                var cartaoDal = new CartaoDal();

                cartaoDal.CartaoGravadoNaApiAtualizaBanco(idCartaoDb, response.Card.Id);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 12
0
        private static Material CreateNewMaterial(CreateCardRequest request)
        {
            string newMaterialAssetPath = string.Format("Assets/Materials/{0}/{1}/{2}Mat.mat",
                                                        request.CardType == Type.Match ? "Matches" : request.CardType + "s",
                                                        request.Classification,
                                                        request.CardName);

            if (request.Classification == ClassificationTypes.Character || request.Classification == ClassificationTypes.Adventure)
            {
                var stringToRemove = request.Classification + "/";
                newMaterialAssetPath = newMaterialAssetPath.Replace(stringToRemove, "");
            }

            var material = new Material(Shader.Find("Diffuse"))
            {
                mainTexture = request.CardGraphic
            };

            if (AssetDatabase.GetAllAssetPaths().Contains(newMaterialAssetPath) == false)
            {
                var path = Path.GetDirectoryName(newMaterialAssetPath);
                if (path != null && !Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                AssetDatabase.CreateAsset(material, newMaterialAssetPath);
            }
            else
            {
                Debug.LogError(string.Format("Asset at {0} already exists!", newMaterialAssetPath));
                return(null);
            }

            return(material);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Converte entidade cartao em modelo de API
        /// </summary>
        /// <param name="cartao">objeto do cartaoDb</param>
        /// <param name="cliente">objeto do clienteDb</param>
        /// <returns>requisição CreateCardRequest</returns>
        public static CreateCardRequest ConverteNovoCartaoDbEmApi(CartaoDb cartao, ClienteDb cliente)
        {
            try
            {
                var createCartao = new CreateCardRequest
                {
                    Number         = cartao.Numero_Cartao,
                    HolderName     = cartao.Nome_Cartao,
                    ExpMonth       = cartao.Val_Mes,
                    ExpYear        = cartao.Val_Ano,
                    Cvv            = cartao.Cvc,
                    BillingAddress = new CreateAddressRequest
                    {
                        Line1   = cliente.Endereco_1,
                        Line2   = cliente.Endereco_2,
                        ZipCode = cliente.Cep,
                        City    = cliente.Cidade,
                        State   = cliente.Uf,
                        Country = "BR"
                    }
                };

                return(createCartao);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 14
0
        public void Should_Create_Card()
        {
            CardInformation cardInformation = new CardInformation();

            cardInformation.CardAlias      = "myAlias";
            cardInformation.CardHolderName = "John Doe";
            cardInformation.CardNumber     = "5528790000000008";
            cardInformation.ExpireMonth    = "12";
            cardInformation.ExpireYear     = "2030";

            CreateCardRequest request = new CreateCardRequest();

            request.Locale         = Locale.TR.GetName();
            request.ConversationId = "123456789";
            request.CardUserKey    = "myCardUserKey";
            request.Card           = cardInformation;

            Card card = Card.Create(request, options);

            PrintResponse <Card>(card);

            Assert.IsNotNull(card.SystemTime);
            Assert.AreEqual(Status.SUCCESS.ToString(), card.Status);
            Assert.AreEqual(Locale.TR.GetName(), card.Locale);
            Assert.AreEqual("123456789", card.ConversationId);
        }
        public async Task SearchForVirgilCards_ValidationWithServiceKey_ShouldPassValidation()
        {
            var crypto = new VirgilCrypto();
            var client = IntergrationHelper.GetVirgilClient();

            client.SetCardValidator(new CardValidator(crypto));

            // CREATING A VIRGIL CARD

            var appKey = crypto.ImportPrivateKey(IntergrationHelper.AppKey, IntergrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();
            var request       = new CreateCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntergrationHelper.AppID, appKey);

            var aliceCard = await client.CreateCardAsync(request);

            // VALIDATING A VIRGIL CARD

            var cards = await client.SearchCardsAsync(SearchCriteria.ByIdentity(aliceIdentity));

            aliceCard.ShouldBeEquivalentTo(cards.Single());

            await IntergrationHelper.RevokeCard(aliceCard.Id);
        }
Ejemplo n.º 16
0
        private static void CreateCard(CreateCardRequest request)
        {
            GameObject card = InstantiateCardTemplate();

            try
            {
                card.transform.name = request.CardName;

                Material newMaterial = CreateNewMaterial(request);
                card.transform.FindChild("Front").gameObject.GetComponent <Renderer>().material = newMaterial;

                AddChosenComponents(request, card);

                TryCreatePrefab(request, card);

                //remove card from scene here
                DestroyImmediate(card);
            }
            catch (Exception e)
            {
                Debug.Log(string.Format("Error: {0}", e.Message));
                Debug.Log("Card was not created");
                Destroy(card);
            }
        }
Ejemplo n.º 17
0
        private async Task <CreateCardResponse> Post(CreateCardRequest request)
        {
            var response = await controller.Post(request);

            var result = Assert.IsType <OkObjectResult>(response);
            var data   = Assert.IsType <CreateCardResponse>(result.Value);

            return(data);
        }
Ejemplo n.º 18
0
        public async Task Create(CreateCardRequest request)
        {
            Card card = new Card();

            card.Value = request.Value;
            // card.Rank = request.Rank;
            // card.Suit = request.Suit;

            await _cardRepository.Add(card);
        }
Ejemplo n.º 19
0
        private CreateCardRequest GetCreateCardResquest()
        {
            var request = new CreateCardRequest();

            request.CardHolder     = "Teste";
            request.ExpirationDate = DateTime.Now.Date;
            request.Number         = "784789407238904742389";

            return(request);
        }
Ejemplo n.º 20
0
        public async Task <CreateCardResponse> Response(CreateCardRequest @request)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var reqModel = _mapper.Map <CreateCardModel>(@request);
                var card     = await scope.ServiceProvider.GetRequiredService <ICardService>().CreateCardAsync(reqModel);

                return(_mapper.Map <CreateCardResponse>(card));
            }
        }
Ejemplo n.º 21
0
        public async Task <ActionResult> Create(CreateCardRequest request)
        {
            if (ModelState.IsValid)
            {
                await service.CreateCard(request);

                return(RedirectToAction("Index"));
            }

            return(View(request));
        }
Ejemplo n.º 22
0
        private async Task <Card> CreateCard()
        {
            CardInformation cardInformation = CardInformationBuilder.Create()
                                              .Build();

            CreateCardRequest cardRequest = CreateCardRequestBuilder.Create()
                                            .Card(cardInformation)
                                            .Email("*****@*****.**")
                                            .Build();

            return(await Card.CreateAsync(cardRequest, Options));
        }
Ejemplo n.º 23
0
        public CreateCardRequest BuildCardRequest(string identity, string type, Dictionary <string, string> data = null)
        {
            var crypto = VirgilConfig.GetService <Crypto>();
            var signer = VirgilConfig.GetService <RequestSigner>();

            var exportedPublicKey = crypto.ExportPublicKey(this.KeyPair.PublicKey);
            var request           = new CreateCardRequest(identity, type, exportedPublicKey, data);

            signer.SelfSign(request, this.KeyPair.PrivateKey);

            return(request);
        }
Ejemplo n.º 24
0
        private Card CreateCard()
        {
            CardInformation cardInformation = CardInformationBuilder.Create()
                                              .Build();

            CreateCardRequest cardRequest = CreateCardRequestBuilder.Create()
                                            .Card(cardInformation)
                                            .Email("*****@*****.**")
                                            .Build();

            return(Card.Create(cardRequest, Options));
        }
        public async Task SearchForTheVirgilCards_MultipleIdentitiesGiven_ShouldReturnVirgilCards()
        {
            // Initialization

            var crypto        = new VirgilCrypto();
            var client        = IntergrationHelper.GetVirgilClient();
            var requestSigner = new RequestSigner(crypto);

            var appKey = crypto.ImportPrivateKey(IntergrationHelper.AppKey, IntergrationHelper.AppKeyPassword);

            // Prepare Requests

            var aliceIdentity  = "alice-" + Guid.NewGuid();
            var aliceKeys      = crypto.GenerateKeys();
            var alicePublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var bobIdentity  = "bob-" + Guid.NewGuid();
            var bobKeys      = crypto.GenerateKeys();
            var bobPublicKey = crypto.ExportPublicKey(bobKeys.PublicKey);

            var aliceRequest = new CreateCardRequest(aliceIdentity, "member", alicePublicKey);
            var bobRequest   = new CreateCardRequest(bobIdentity, "member", bobPublicKey);

            requestSigner.SelfSign(aliceRequest, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(aliceRequest, IntergrationHelper.AppID, appKey);

            requestSigner.SelfSign(bobRequest, bobKeys.PrivateKey);
            requestSigner.AuthoritySign(bobRequest, IntergrationHelper.AppID, appKey);

            // Publish Virgil Cards

            var aliceCard = await client.CreateCardAsync(aliceRequest);

            var bobCard = await client.CreateCardAsync(bobRequest);

            // Search for the Virgil Cards

            var foundCards = await client.SearchCardsAsync(new SearchCriteria
            {
                Identities = new[] { bobIdentity, aliceIdentity }
            });

            // Assertions

            foundCards.Should().HaveCount(2);

            foundCards.Single(it => it.Id == aliceCard.Id).ShouldBeEquivalentTo(aliceCard);
            foundCards.Single(it => it.Id == bobCard.Id).ShouldBeEquivalentTo(bobCard);

            await IntergrationHelper.RevokeCard(aliceCard.Id);

            await IntergrationHelper.RevokeCard(bobCard.Id);
        }
Ejemplo n.º 26
0
        public CreateCardRequest Build()
        {
            CreateCardRequest createCardRequest = new CreateCardRequest();

            createCardRequest.Locale         = _locale;
            createCardRequest.ConversationId = _conversationId;
            createCardRequest.ExternalId     = _externalId;
            createCardRequest.Email          = _email;
            createCardRequest.CardUserKey    = _cardUserKey;
            createCardRequest.Card           = _card;
            return(createCardRequest);
        }
Ejemplo n.º 27
0
        public async Task Should_Create_Payment_With_Registered_Card()
        {
            string          externalUserId  = RandomGenerator.RandomId;
            CardInformation cardInformation = CardInformationBuilder.Create()
                                              .Build();

            CreateCardRequest cardRequest = CreateCardRequestBuilder.Create()
                                            .Card(cardInformation)
                                            .ExternalId(externalUserId)
                                            .Email("*****@*****.**")
                                            .Build();

            Card card = await Card.CreateAsync(cardRequest, Options);

            PaymentCard paymentCard = PaymentCardBuilder.Create()
                                      .CardUserKey(card.CardUserKey)
                                      .CardToken(card.CardToken)
                                      .Build();

            CreatePaymentRequest request = CreatePaymentRequestBuilder.Create()
                                           .StandardListingPayment()
                                           .PaymentCard(paymentCard)
                                           .Build();

            Payment payment = await Payment.CreateAsync(request, Options);

            PrintResponse(payment);

            Assert.Null(payment.ConnectorName);
            Assert.AreEqual(Locale.TR.ToString(), payment.Locale);
            Assert.AreEqual(Status.SUCCESS.ToString(), payment.Status);
            Assert.NotNull(payment.SystemTime);
            Assert.AreEqual("123456789", payment.ConversationId);
            Assert.Null(payment.ErrorCode);
            Assert.Null(payment.ErrorMessage);
            Assert.Null(payment.ErrorGroup);
            Assert.NotNull(payment.PaymentId);
            Assert.NotNull(payment.BasketId);
            Assert.AreEqual("1", payment.Price);
            Assert.AreEqual("1.1", payment.PaidPrice);
            Assert.AreEqual("0.02887500", payment.IyziCommissionRateAmount);
            Assert.AreEqual("0.25000000", payment.IyziCommissionFee);
            Assert.AreEqual("10.00000000", payment.MerchantCommissionRate);
            Assert.AreEqual("0.1", payment.MerchantCommissionRateAmount);
            Assert.AreEqual(0.028875, payment.IyziCommissionRateAmount.ParseDouble());
            Assert.AreEqual(0.25, payment.IyziCommissionFee.ParseDouble());
            Assert.AreEqual(10, payment.MerchantCommissionRate.ParseDouble());
            AssertDecimal.AreEqual(0.02887500M, payment.IyziCommissionRateAmount.ParseDecimal());
            AssertDecimal.AreEqual(0.25000000M, payment.IyziCommissionFee.ParseDecimal());
            AssertDecimal.AreEqual(10.00000000M, payment.MerchantCommissionRate.ParseDecimal());
            Assert.AreEqual(1, payment.Installment);
        }
Ejemplo n.º 28
0
        public async Task <CreateCardResponse> Open(Guid id, string userId)
        {
            var pack = await _packRepository.GetAsync(id);

            var request = new CreateCardRequest(userId);

            if (pack.Position != null)
            {
                request.Position = pack.Position;
            }
            var response = await _bus.RequestAsync <CreateCardRequest, CreateCardResponse>(request);

            await _packRepository.Delete(id);

            return(response);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// создание карты
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public async Task CreateCard(CreateCardRequest request)
 {
     using (var db = new DeckContext())
     {
         if (long.TryParse(request.SelectedSuitId.ToString(), out long suitId) &&
             suitId > 0 &&
             long.TryParse(request.SelectedValueId.ToString(), out long valueId) &&
             valueId > 0)
         {
             db.Cards.Add(new Card {
                 SuitId = suitId, ValueId = valueId
             });
             await db.SaveChangesAsync();
         }
     }
 }
Ejemplo n.º 30
0
        public static GetCardResponse InitializeCard(JObject data, string customerId, string customerName)
        {
            string number           = (string)data?["cartao"]?["numero"];
            int    expiration_Month = (int)data?["cartao"]?["expiracao_mes"];
            int    expiration_Year  = (int)data?["cartao"]?["expiracao_ano"];
            string cvv = (string)data?["cartao"]?["cvv"];

            try
            {
                var cards = Client.Customers.GetCards(customerId);
                var card  = cards.Data.Find(c =>
                                            c.FirstSixDigits.Equals(number.Substring(0, 6)) &&
                                            c.LastFourDigits.Equals(number.Substring(number.Length - 4)) &&
                                            c.ExpMonth == expiration_Month &&
                                            c.ExpYear == expiration_Year
                                            );

                if (card != null)
                {
                    return(card);
                }

                var createCard = new CreateCardRequest
                {
                    Number     = number,
                    HolderName = customerName,
                    ExpMonth   = expiration_Month,
                    ExpYear    = expiration_Year,
                    Cvv        = cvv
                };

                card = Client.Customers.CreateCard(customerId, createCard);

                if (string.IsNullOrEmpty(card.Id))
                {
                    throw new InvalidOperationException("Falha em criar o cartão.");
                }

                return(card);
            }
            catch (APIException ex)
            {
                throw new InvalidOperationException("Falha em criar o cartão.", ex);
            }
        }