public ChargeServiceTests(string _iPAddress) { _service = new StartChargeService("test_sec_k_8512e94e69d6a46c67ab2"); _customerService = new StartCustomerService("test_sec_k_8512e94e69d6a46c67ab2"); _tokenService = new StartTokenService("test_open_k_3gfew76877gy689798hc86a4"); _workingCard = new Card() { Name = "Abdullah Ahmed", Cvc = 123, ExpireMonth = 12, ExpireYear = 2020, Number = "4242424242424242" }; _createTokenRequest = new CreateTokenRequest() { Number = "4242424242424242", Exp_Month = 12, Exp_Year = 2020, Cvc = "123", Name = "Abdullah Ahmed" }; _createChargeRequest = new CreateChargeRequest() { Amount = 10000, Currency = Currency.AED, Email = "*****@*****.**", Ip = _iPAddress }; }
/// <summary> /// Resource /{merchantId}/tokens /// <a href="https://developer.globalcollect.com/documentation/api/server/#__merchantId__tokens_post">Create token</a> /// </summary> /// <param name="body">CreateTokenRequest</param> /// <param name="context">CallContext</param> /// <returns>CreateTokenResponse</returns> /// <exception cref="ValidationException">if the request was not correct and couldn't be processed (HTTP status code BadRequest)</exception> /// <exception cref="AuthorizationException">if the request was not allowed (HTTP status code Forbidden)</exception> /// <exception cref="IdempotenceException">if an idempotent request caused a conflict (HTTP status code Conflict)</exception> /// <exception cref="ReferenceException">if an object was attempted to be referenced that doesn't exist or has been removed, /// or there was a conflict (HTTP status code NotFound, Conflict or Gone)</exception> /// <exception cref="GlobalCollectException">if something went wrong at the GlobalCollect platform, /// the GlobalCollect platform was unable to process a message from a downstream partner/acquirer, /// or the service that you're trying to reach is temporary unavailable (HTTP status code InternalServerError, BadGateway or ServiceUnavailable)</exception> /// <exception cref="ApiException">if the GlobalCollect platform returned any other error</exception> public async Task <CreateTokenResponse> Create(CreateTokenRequest body, CallContext context = null) { string uri = InstantiateUri("/{apiVersion}/{merchantId}/tokens", null); try { return(await _communicator.Post <CreateTokenResponse>( uri, ClientHeaders, null, body, context)); } catch (ResponseException e) { object errorObject; switch (e.StatusCode) { case HttpStatusCode.Forbidden: errorObject = _communicator.Marshaller.Unmarshal <ErrorResponse>(e.Body); break; default: errorObject = _communicator.Marshaller.Unmarshal <ErrorResponse>(e.Body); break; } throw CreateException(e.StatusCode, e.Body, errorObject, context); } }
public Task <CreateTokenResponse> CreateToken(CreateTokenRequest request) { return(Task.FromResult <CreateTokenResponse>(new CreateTokenResponse() { Token = "fake_token" })); }
public async Task <ActionResult> CreateToken([FromBody] CreateTokenRequest request) { if (!ModelState.IsValid) { return(BadRequest()); } try { var usecase = _services.GetRequiredService <ILoginHandler>(); var response = await usecase.Handle(new LoginRequest( request.Email, request.Password, request.Fingerprint, Request.Headers[HeaderNames.UserAgent] )); if (!response.Success) { _logger.LogError($"{nameof( CreateToken )}. Email:{request.Email}, Password:{new string( '*', request.Password.Length )}, Fingerprint:{request.Fingerprint}, UserAgent:{Request.Headers[HeaderNames.UserAgent]}"); return(Forbid()); } return(Created(Request.Path, new CreateTokenResponse(response.Value.AuthToken, response.Value.RefreshToken))); } catch (ValidationException ex) { _logger.LogError($"{nameof( CreateToken )}. Validation error: {ex.Data}"); return(BadRequest()); } catch (Exception ex) { _logger.LogError(ex, $"{nameof( CreateToken )}. Email:{request.Email}, Password:{new string( '*', request.Password.Length )}, Fingerprint:{request.Fingerprint}, UserAgent:{Request.Headers[HeaderNames.UserAgent]}"); } return(StatusCode((int)HttpStatusCode.InternalServerError)); }
public async Task <IActionResult> Create(CreateTokenRequest request) { string clientId = User.Claims.First(c => c.Type == "client_id").Value; Token token = new Token { Id = Guid.NewGuid(), Name = request.Name, Value = request.Token, Expires = request.Expires.GetValueOrDefault(), RefreshToken = request.RefreshToken, TokenType = request.TokenType, ClientId = clientId }; Response <Token> response = await _tokenBusiness.Create(token); if (response.Result is null) { return(BadRequest(response)); } else { return(Ok(response)); } }
private static Expression <Func <CreateTokenRequest, bool> > MatchesRequest(CreateTokenRequest expectedRequest) { return(request => request.ClientId == expectedRequest.ClientId && request.ClientSecret == expectedRequest.ClientSecret && request.GrantType == expectedRequest.GrantType && request.DeviceCode == expectedRequest.DeviceCode); }
public void CreateTokenTest() { var createTokenRequest = new CreateTokenRequest("username", "password"); var mockNetwork = new Mock <INetwork>(MockBehavior.Strict); mockNetwork .Setup(n => n.Invoke(createTokenRequest)) .Returns(new MockHttpWebResponse("SpectraLogic.SpectraRioBrokerClient.Test.TestFiles.CreateTokenResponse", HttpStatusCode.Created, null)); var mockBuilder = new Mock <ISpectraRioBrokerClientBuilder>(MockBehavior.Strict); mockBuilder .Setup(b => b.Build()) .Returns(new SpectraRioBrokerClient(mockNetwork.Object)); var builder = mockBuilder.Object; var client = builder.Build(); var token = client.CreateToken(createTokenRequest).Token; Assert.AreEqual("token123", token); mockBuilder.VerifyAll(); mockNetwork.VerifyAll(); }
public ChargeServiceTests() { _service = new StartChargeService("test_sec_k_8512e94e69d6a46c67ab2"); _customerService = new StartCustomerService("test_sec_k_8512e94e69d6a46c67ab2"); _tokenService = new StartTokenService("test_open_k_956a1de10dba98935041"); _iPAddress = "127.0.0.1"; _workingCard = new Card() { Name = "Abdullah Ahmed", Cvc = 123, ExpireMonth = 12, ExpireYear = 2020, Number = "4242424242424242" }; _createTokenRequest = new CreateTokenRequest(_workingCard); _createChargeRequest = new CreateChargeRequest() { Amount = 10000, Currency = Currency.AED, Email = "*****@*****.**", Ip = _iPAddress }; }
/// <summary> /// Create a token in the database /// </summary> /// <param name="createTokenRequest">Token creation request data</param> /// <returns>A <see cref="Task"/> object for task synchronization</returns> public async Task CreateToken(CreateTokenRequest createTokenRequest) { using var connection = new SqlConnection(_connectionSTring); await connection.OpenAsync(); await connection.ExecuteAsync("EXEC dbo.Token_Create @Owner = @Owner, @Expires = @Expires, @Token = @Token", createTokenRequest); }
public static GetSsoTokenResponse GetSsoToken(IAmazonSSOOIDC client, GetSsoTokenRequest request, IGetSsoTokenContext context) { var registerClientRequest = new RegisterClientRequest() { ClientName = request.ClientName, ClientType = request.ClientType, }; InternalSDKUtils.ApplyValues(registerClientRequest, request.AdditionalProperties); var registerClientResponse = client.RegisterClient(registerClientRequest); var startDeviceAuthorizationRequest = new StartDeviceAuthorizationRequest() { ClientSecret = registerClientResponse.ClientSecret, ClientId = registerClientResponse.ClientId, StartUrl = request.StartUrl, }; InternalSDKUtils.ApplyValues(startDeviceAuthorizationRequest, request.AdditionalProperties); var startDeviceAuthorizationResponse = client.StartDeviceAuthorization(startDeviceAuthorizationRequest); // Spec: The expiration time must be calculated by adding the number of seconds // returned by StartDeviceAuthorization (ExpiresIn) to the current time. DateTime deviceCodeExpiration = DateTime.UtcNow.AddSeconds(startDeviceAuthorizationResponse.ExpiresIn); request.SsoVerificationCallback(new SsoVerificationArguments() { UserCode = startDeviceAuthorizationResponse.UserCode, VerificationUri = startDeviceAuthorizationResponse.VerificationUri, VerificationUriComplete = startDeviceAuthorizationResponse.VerificationUriComplete, }); var createTokenRequest = new CreateTokenRequest() { ClientId = registerClientResponse.ClientId, ClientSecret = registerClientResponse.ClientSecret, GrantType = CreateTokenGrantType, DeviceCode = startDeviceAuthorizationResponse.DeviceCode, }; InternalSDKUtils.ApplyValues(request, request.AdditionalProperties); var ssoToken = PollForSsoToken(client, createTokenRequest, startDeviceAuthorizationResponse.Interval, deviceCodeExpiration, context); return(new GetSsoTokenResponse() { AccessToken = ssoToken.AccessToken, ExpiresAt = DateTime.UtcNow.AddSeconds(ssoToken.ExpiresIn), }); }
public ActionResult CreateToken([FromBody] CreateTokenRequest request) { using (var client = GetLemmationzationServiceClient()) { var resultId = client.CreateToken(request.Token, request.Description); return(Json(resultId)); } }
public void TokensCreateTest() { // TODO uncomment below to test the method and replace null with proper value CreateTokenRequest body = null; string idempotencyKey = null; var response = instance.TokensCreate(body, idempotencyKey); Assert.IsInstanceOf <Token> (response, "response is Token"); }
/// <summary> /// Initiates the asynchronous execution of the CreateToken operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateToken operation on AmazonSSOOIDCClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateToken /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken">REST API Reference for CreateToken Operation</seealso> public virtual IAsyncResult BeginCreateToken(CreateTokenRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTokenRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTokenResponseUnmarshaller.Instance; return(BeginInvoke(request, options, callback, state)); }
public async void Example() { #pragma warning disable 0168 using (Client client = GetClient()) { Address billingAddress = new Address(); billingAddress.AdditionalInfo = "Suite II"; billingAddress.City = "Monument Valley"; billingAddress.CountryCode = "US"; billingAddress.HouseNumber = "1"; billingAddress.State = "Utah"; billingAddress.Street = "Desertroad"; billingAddress.Zip = "84536"; CompanyInformation companyInformation = new CompanyInformation(); companyInformation.Name = "Acme Labs"; PersonalNameToken name = new PersonalNameToken(); name.FirstName = "Wile"; name.Surname = "Coyote"; name.SurnamePrefix = "E."; PersonalInformationToken personalInformation = new PersonalInformationToken(); personalInformation.Name = name; CustomerToken customer = new CustomerToken(); customer.BillingAddress = billingAddress; customer.CompanyInformation = companyInformation; customer.MerchantCustomerId = "1234"; customer.PersonalInformation = personalInformation; BankAccountBban bankAccountBban = new BankAccountBban(); bankAccountBban.AccountNumber = "000000123456"; bankAccountBban.BankCode = "05428"; bankAccountBban.BranchCode = "11101"; bankAccountBban.CheckDigit = "X"; bankAccountBban.CountryCode = "IT"; TokenNonSepaDirectDebitPaymentProduct705SpecificData paymentProduct705SpecificData = new TokenNonSepaDirectDebitPaymentProduct705SpecificData(); paymentProduct705SpecificData.AuthorisationId = "123456"; paymentProduct705SpecificData.BankAccountBban = bankAccountBban; MandateNonSepaDirectDebit mandate = new MandateNonSepaDirectDebit(); mandate.PaymentProduct705SpecificData = paymentProduct705SpecificData; TokenNonSepaDirectDebit nonSepaDirectDebit = new TokenNonSepaDirectDebit(); nonSepaDirectDebit.Customer = customer; nonSepaDirectDebit.Mandate = mandate; CreateTokenRequest body = new CreateTokenRequest(); body.NonSepaDirectDebit = nonSepaDirectDebit; body.PaymentProductId = 705; CreateTokenResponse response = await client.Merchant("merchantId").Tokens().Create(body); } #pragma warning restore 0168 }
private static async Task <CreateTokenResponse> PollForSsoTokenAsync(IAmazonSSOOIDC client, CreateTokenRequest createTokenRequest, int pollingIntervalSeconds, DateTime deviceCodeExpiration, IGetSsoTokenContext context) { var logger = Logger.GetLogger(typeof(CoreAmazonSSOOIDC)); // Spec: If the Interval value is not returned as part of the StartDeviceAuthorization response, // a default Interval value of 5 seconds should be used. var intervalSec = pollingIntervalSeconds > 0 ? pollingIntervalSeconds : DefaultPollingIntervalSeconds; // Poll for Token until success, failure, or an error condition arises. while (true) { try { var response = await client.CreateTokenAsync(createTokenRequest).ConfigureAwait(false); // If we reach here, the user has completed the SSO Login authorization. return(response); } catch (AuthorizationPendingException e) { // Service is still waiting for user to complete authorization. // Repeat the loop after an interval. } catch (SlowDownException e) { // Spec: Add 5 seconds to the polling interval intervalSec += PollingSlowdownIncrementSeconds; } catch (ExpiredTokenException e) { // Spec: An exception must be raised, indicating that the SSO login window expired // and the SSO login flow must be re-initiated. throw new AmazonSSOOIDCException("Device code has expired while polling for SSO token, login flow must be re-initiated.", e); } catch (TimeoutException e) { // Spec: If the call times out then the tool should double its polling interval and then retry. intervalSec *= 2; } catch (Exception e) { logger.Error(e, "Unexpected exception while polling for SSO Token."); throw; } if (DateTime.UtcNow.AddSeconds(intervalSec) > deviceCodeExpiration) { throw new AmazonSSOOIDCException("Device code has expired while polling for SSO token, login flow must be re-initiated."); } context.Sleep(intervalSec * 1000); } // while(polling) }
/// <summary> /// Creates and returns an access token for the authorized client. The access token issued /// will be used to fetch short-term credentials for the assigned roles in the AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateToken service method.</param> /// /// <returns>The response from the CreateToken service method, as returned by SSOOIDC.</returns> /// <exception cref="Amazon.SSOOIDC.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.AuthorizationPendingException"> /// Indicates that a request to authorize a client with an access user session token is /// pending. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.ExpiredTokenException"> /// Indicates that the token issued by the service is expired and is no longer valid. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InternalServerException"> /// Indicates that an error from the service occurred while trying to process a request. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidClientException"> /// Indicates that the <code>clientId</code> or <code>clientSecret</code> in the request /// is invalid. For example, this can occur when a client sends an incorrect <code>clientId</code> /// or an expired <code>clientSecret</code>. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidGrantException"> /// Indicates that a request contains an invalid grant. This can occur if a client makes /// a <a>CreateToken</a> request with an invalid grant type. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidRequestException"> /// Indicates that something is wrong with the input to the request. For example, a required /// parameter might be missing or out of range. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidScopeException"> /// Indicates that the scope provided in the request is invalid. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.SlowDownException"> /// Indicates that the client is making the request too frequently and is more than the /// service can handle. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.UnauthorizedClientException"> /// Indicates that the client is not currently authorized to make the request. This can /// happen when a <code>clientId</code> is not issued for a public client. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.UnsupportedGrantTypeException"> /// Indicates that the grant type in the request is not supported by the service. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken">REST API Reference for CreateToken Operation</seealso> public virtual CreateTokenResponse CreateToken(CreateTokenRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTokenRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTokenResponseUnmarshaller.Instance; return(Invoke <CreateTokenResponse>(request, options)); }
/// <summary> /// Creates and returns an access token for the authorized client. The access token issued /// will be used to fetch short-term credentials for the assigned roles in the AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateToken service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateToken service method, as returned by SSOOIDC.</returns> /// <exception cref="Amazon.SSOOIDC.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.AuthorizationPendingException"> /// Indicates that a request to authorize a client with an access user session token is /// pending. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.ExpiredTokenException"> /// Indicates that the token issued by the service is expired and is no longer valid. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InternalServerException"> /// Indicates that an error from the service occurred while trying to process a request. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidClientException"> /// Indicates that the <code>clientId</code> or <code>clientSecret</code> in the request /// is invalid. For example, this can occur when a client sends an incorrect <code>clientId</code> /// or an expired <code>clientSecret</code>. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidGrantException"> /// Indicates that a request contains an invalid grant. This can occur if a client makes /// a <a>CreateToken</a> request with an invalid grant type. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidRequestException"> /// Indicates that something is wrong with the input to the request. For example, a required /// parameter might be missing or out of range. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.InvalidScopeException"> /// Indicates that the scope provided in the request is invalid. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.SlowDownException"> /// Indicates that the client is making the request too frequently and is more than the /// service can handle. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.UnauthorizedClientException"> /// Indicates that the client is not currently authorized to make the request. This can /// happen when a <code>clientId</code> is not issued for a public client. /// </exception> /// <exception cref="Amazon.SSOOIDC.Model.UnsupportedGrantTypeException"> /// Indicates that the grant type in the request is not supported by the service. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken">REST API Reference for CreateToken Operation</seealso> public virtual Task <CreateTokenResponse> CreateTokenAsync(CreateTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTokenRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTokenResponseUnmarshaller.Instance; return(InvokeAsync <CreateTokenResponse>(request, options, cancellationToken)); }
public async Task <Token> Create(CreateTokenRequest request) { var wrapped = new TokenRequestWrapper { Card = request }; return(await Requester.Request <TokenRequestWrapper, Token>( Endpoint, "POST", BasePath, wrapped )); }
async Task <AuthorizationAPIResult> INodeAPI.CreateToken(TokenGenesisBlock block) { var request = new CreateTokenRequest() { CreateTokenJson = Json(block) }; var result = await CreateTokenAsync(request); return(ToAAR(result)); }
public Task <CreateTokenResponse> CreateToken(CreateTokenRequest request) { var client = restClientBuilder.Build(); var restRequest = new RestRequest("/api/tokens"); restRequest.AddParameter("application/json", System.Text.Json.JsonSerializer.Serialize(request), ParameterType.RequestBody); return(client.PostAsync <CreateTokenResponse>(restRequest)); }
public override async Task<CreateTokenResponse> CreateToken(CreateTokenRequest createTokenRequest) { PaymentGateway.ServiceReference.SamanGateway.PaymentIFBindingSoapClient client = new PaymentIFBindingSoapClient(PaymentIFBindingSoapClient.EndpointConfiguration.PaymentIFBindingSoap); var rs= await client.RequestTokenAsync(Configuration.TerminalId, createTokenRequest.InvoiceNumber, createTokenRequest.TotalAmount, 0, 0, 0, 0, 0, 0, null, null, 0); return new CreateTokenResponse { Token = rs, IsSuccessful = rs.Length > 3, OriginalErrorId=rs.Length>3 ?0 :int.Parse( rs) }; }
public async Task <CreateTokenResponse> CreateIdentityUserToken(CreateTokenRequest request, CancellationToken cancellationToken = default) { var identityUser = await _userManager.FindByEmailAsync(request.Email); if (identityUser == null) { throw new IdentityUserNotFoundException("Неверная почта или пароль"); } var passwordCheckResult = await _userManager.CheckPasswordAsync(identityUser, request.Password); if (!passwordCheckResult) { throw new IdentityUserNotFoundException("Неверная почта или пароль"); } var emailConfirmCheck = await _userManager.IsEmailConfirmedAsync(identityUser); if (!emailConfirmCheck) { throw new IdentityUserNotFoundException("Почта не подтверждена"); } var claims = new List <Claim> { new Claim(ClaimTypes.Email, request.Email), new Claim(ClaimTypes.NameIdentifier, identityUser.Id) }; var userRoles = await _userManager.GetRolesAsync(identityUser); claims.AddRange(userRoles.Select(role => new Claim(ClaimTypes.Role, role))); var token = new JwtSecurityToken ( claims: claims, expires: DateTime.UtcNow.AddDays(60), notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:Key"])), SecurityAlgorithms.HmacSha256 ) ); return(new CreateTokenResponse { Id = identityUser.Id, Token = new JwtSecurityTokenHandler().WriteToken(token) }); }
public IActionResult CreateToken([FromBody] CreateTokenRequest request) { UserModel user = _userManager.LoginUser(request.Username, request.Password); if (user == null) { return(BadRequest("Username or password is incorrect.")); } CreateTokenResponse response = new CreateTokenResponse(); response.Token = CreateUserToken(user); response.ExpiresIn = DateTime.Now.AddMilliseconds(int.Parse(_configuration["Jwt:ExpiresInMs"])); return(Ok(response)); }
public async Task <IActionResult> CreateToken([FromBody] CreateTokenRequest request) { if (await _userService.VerifyCredentials(request.Email, request.Password)) { User user = await _userService.GetUser(request.Email); JwtSecurityToken token = CreateSecurityToken(user); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } throw new InvalidOperationException("Failed to login."); }
public async Task <ActionResult> CreateToken([FromBody] CreateTokenRequest request) { AuthenticationService.ClientId = _appSettings.Value.SpotifyClientId; AuthenticationService.ClientSecret = _appSettings.Value.SpotifyClientSecret; AuthenticationService.RedirectUri = request.RedirectUri; var accessToken = await AuthenticationService.GetAccessToken(request.Code); var user = _userService.GetUser(this.GetCurrentUserId()); var spotifyToken = accessToken.ToSpotifyToken(); spotifyToken.User = user; user.SpotifyToken = spotifyToken; _userService.UpdateUser(user); return(Ok()); }
public async Task TokensCreateCreate() { var request = new CreateTokenRequest { Name = "Somchai Prasert", Number = "4242424242424242", ExpirationMonth = 10, ExpirationYear = 2018, City = "Bangkok", PostalCode = "10320", SecurityCode = "123", }; var token = await Client.Tokens.Create(request); Assert.AreEqual("4242", token.Card.LastDigits); Assert.AreEqual("Visa", token.Card.Brand); Assert.IsFalse(token.Used); }
public IHttpActionResult CreateToken(CreateTokenRequest paramaters) { try { return(Ok( new CreateTokenResult( _tokenService.CreateToken( paramaters.Name, paramaters.UniqueId, paramaters.Payload != null ? paramaters.Payload.ToDictionary(c => c.Key, c => c.Value) : null ) ) )); } catch (Exception ex) { return(InternalServerError(ex)); } }
public async Task Test() { CreateTokenRequest createTokenRequest = new CreateTokenRequest(); createTokenRequest.PaymentProductId = (1); TokenCard card = new TokenCard(); createTokenRequest.Card = (card); CustomerToken customer = new CustomerToken(); card.Customer = (customer); Address billingAddress = new Address(); customer.BillingAddress = (billingAddress); billingAddress.CountryCode = ("NL"); TokenCardData mandate = new TokenCardData(); card.Data = (mandate); CardWithoutCvv cardWithoutCvv = new CardWithoutCvv(); mandate.CardWithoutCvv = (cardWithoutCvv); cardWithoutCvv.CardholderName = ("Jan"); cardWithoutCvv.IssueNumber = ("12"); cardWithoutCvv.CardNumber = ("4567350000427977"); cardWithoutCvv.ExpiryDate = ("0820"); using (Client client = GetClient()) { CreateTokenResponse createTokenResponse = await client .Merchant("9991") .Tokens() .Create(createTokenRequest); Assert.NotNull(createTokenResponse.Token); DeleteTokenParams deleteTokenRequest = new DeleteTokenParams(); await client .Merchant("9991") .Tokens() .Delete(createTokenResponse.Token, deleteTokenRequest); } }
/// <inheritdoc/> public async Task <CreatedTokenResponse> CreateToken(CreateTokenRequest body, CallContext context = null) { string uri = InstantiateUri("/v2/{merchantId}/tokens", null); try { return(await _communicator.Post <CreatedTokenResponse>( uri, ClientHeaders, null, body, context) .ConfigureAwait(false)); } catch (ResponseException e) { object errorObject = _communicator.Unmarshal <ErrorResponse>(e.Body); throw CreateException(e.StatusCode, e.Body, errorObject, context); } }
public IActionResult CreateToken([FromBody] CreateTokenRequest request) { try { var input = new AuthenticationInput(request.UserName, request.Password); var user = _useCase.Execute(input); var token = _tokenService.CreateToken(user); var response = new CreateTokenResponse { Token = new JwtSecurityTokenHandler().WriteToken(token), Expires = token.ValidTo }; return(Created("https://paella.com", response)); } catch (System.Exception) { return(BadRequest()); } }