Пример #1
0
        public async Task <ObtainTokenReply> ObtainToken(ObtainTokenRequest request)
        {
            var client = new TokenGen.TokenGenClient(_channel);
            var reply  = await client.ObtainAsync(request);

            return(reply);
        }
Пример #2
0
        protected override async Task HandleMessage(Message <DtoRenewAccessTokenMessage> message)
        {
            if (message == null || message.Data == null ||
                string.IsNullOrWhiteSpace(message.Data.ExternalAccessToken) ||
                string.IsNullOrWhiteSpace(message.Data.ExternalRefreshToken) ||
                message.Data.ExternalTokenExpiry == default(DateTime))
            {
                return;
            }

            try
            {
                var accessToken  = message.Data.ExternalAccessToken;
                var refreshToken = message.Data.ExternalRefreshToken;
                var tokenExpiry  = message.Data.ExternalTokenExpiry;
                var companyId    = message.Data.CompanyId;

                var client = new SquareClient.Builder()
                             .Environment(_settings.Connection.SquarePaymentsSandbox ? Square.Environment.Sandbox : Square.Environment.Production)
                             .Build();

                var body = new ObtainTokenRequest(_settings.Connection.SquareAppId, _settings.Connection.SquareAccessToken, "refresh_token", refreshToken: refreshToken);

                ObtainTokenResponse response = null;
                try
                {
                    response = await client.OAuthApi.ObtainTokenAsync(body).ConfigureAwait(false);

                    accessToken  = response.AccessToken;
                    refreshToken = response.RefreshToken;
                    var expiry = DateTime.TryParse(response.ExpiresAt, out DateTime parsedDate)? parsedDate : tokenExpiry;

                    if (!string.IsNullOrWhiteSpace(accessToken) &&
                        !string.IsNullOrWhiteSpace(refreshToken) && (expiry != null || expiry != default(DateTime)))
                    {
                        await _companies.UpdateCompany(new CompanyPatch
                        {
                            ResourceId          = companyId,
                            ExternalAccessToken = new PatchOperation <string> {
                                Operation = OperationKind.Update, Value = accessToken
                            },
                            ExternalRefreshToken = new PatchOperation <string> {
                                Operation = OperationKind.Update, Value = refreshToken
                            },
                            ExternalTokenExpiry = new PatchOperation <DateTime> {
                                Operation = OperationKind.Update, Value = expiry
                            }
                        }).ConfigureAwait(false);
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError(e, $"Unable to update company access token");
                }
            }
            catch (ApiException e)
            {
                Logger.LogError(e, $"Failed to connect to Square API");
            }
        }
Пример #3
0
 public override Task <ObtainTokenReply> Obtain(ObtainTokenRequest request, ServerCallContext context)
 {
     try
     {
         var token = _tokenGen.Obtain(request.Client);
         //Console.WriteLine($"Generated Token:- Id:{token.Id} IssuedOn:{token.IssuedOn.ToLongTimeString()} Client:{request.Client}");
         _logger?.LogInformation($"Generated Token:- Id:{token?.Id} IssuedOn:{token?.IssuedOn.ToLongTimeString()} Client:{request.Client}");
         return(Task.FromResult(new ObtainTokenReply {
             Id = token?.Id, Issuedon = Timestamp.FromDateTime(token?.IssuedOn.ToUniversalTime() ?? DateTime.MinValue)
         }));
     }
     catch (Exception ex)
     {
         _logger?.LogError(ex, $"Exception obtaining token client:{request.Client}");
         throw;
     }
 }
Пример #4
0
        public async Task <IActionResult> SubmitToken([FromQuery] string code, [FromQuery] string response_type, [FromQuery] string state)
        {
            if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(response_type) || string.IsNullOrWhiteSpace(state) || !string.Equals(response_type, "code", StringComparison.OrdinalIgnoreCase))
            {
                return(RedirectToPage("/Index"));
            }

            var employeeId = await cache.GetStringAsync($"company-square-verify-{state}").ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(employeeId))
            {
                return(RedirectToPage("/Index"));
            }

            int rawEmployeeId = -1;

            if (!int.TryParse(employeeId, out rawEmployeeId))
            {
                return(RedirectToPage("/Index"));
            }

            if (rawEmployeeId == -1)
            {
                return(RedirectToPage("/Index"));
            }

            var employee = await employees.FetchEmployee(rawEmployeeId)
                           .Ensure(e => e.HasValue, "Employee found")
                           .OnSuccess(e => e.Value)
                           .ConfigureAwait(false);

            if (employee.IsFailure)
            {
                return(RedirectToPage("/Index"));
            }

            var role = await roles.FetchEmployeeRole(employee.Value.RoleId)
                       .Ensure(r => r.HasValue, "Role found")
                       .OnSuccess(r => r.Value)
                       .ConfigureAwait(false);

            if (role.IsFailure || !role.Value.CanAdministerCompany)
            {
                return(RedirectToPage("/Index"));
            }

            var company = await companies.FetchCompany(employee.Value.CompanyId)
                          .Ensure(c => c.HasValue, "Company found")
                          .OnSuccess(c => c.Value)
                          .ConfigureAwait(false);

            if (company.IsFailure)
            {
                return(RedirectToPage("/Index"));
            }

            var client = new SquareClient.Builder()
                         .Environment(settings.Connection.SquarePaymentsSandbox ? Square.Environment.Sandbox : Square.Environment.Production)
                         .Build();

            var body = new ObtainTokenRequest(settings.Connection.SquareAppId, settings.Connection.SquareAccessToken, "authorization_code", code);

            ObtainTokenResponse response = null;

            try
            {
                response = await client.OAuthApi.ObtainTokenAsync(body).ConfigureAwait(false);
            }
            catch (Exception)
            {
                return(RedirectToPage("/Index"));
            }

            if (response == null)
            {
                return(RedirectToPage("/Index"));
            }

            var accessToken  = response.AccessToken;
            var refreshToken = response.RefreshToken;
            var expiresAt    = response.ExpiresAt;
            var merchantId   = response.MerchantId;

            DateTime tokenExpiry;

            if (!DateTime.TryParse(response.ExpiresAt, out tokenExpiry))
            {
                return(RedirectToPage("/Index"));
            }

            var companyId = company.Value.CompanyId;

            SynchVenuesWithExternalPaymentProvider(accessToken, company.Value);

            accessToken = await EncryptString(accessToken).ConfigureAwait(false);

            refreshToken = await EncryptString(refreshToken).ConfigureAwait(false);

            return(await companies.UpdateCompany(new CompanyPatch
            {
                ResourceId = companyId,
                ExternalAccessToken = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = accessToken
                },
                ExternalRefreshToken = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = refreshToken
                },
                ExternalAccountId = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = merchantId
                },
                ExternalTokenExpiry = new PatchOperation <DateTime> {
                    Operation = OperationKind.Update, Value = tokenExpiry
                }
            }).OnBoth(u => RedirectToPage("/Index")).ConfigureAwait(false));
        }
        /// <summary>
        /// ObtainTokenWithHttpInfo
        /// </summary>
        /// <remarks>
        /// If you obtained a temporary authorization code from a request to the Authorize endpoint, you exchange that code for an access token with a request to this endpoint.
        /// </remarks>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">An object containing the fields to POST for the request.\n\nSee the corresponding object definition for field details.</param>
        /// <returns>Task of ApiResponse (ObtainTokenResponse)</returns>
        public async Task <ApiResponse <ObtainTokenResponse> > ObtainTokenAsyncWithHttpInfo(ObtainTokenRequest body)
        {
            // verify the required parameter 'body' is set
            if (body == null)
            {
                throw new ApiException(400, "Missing required parameter 'body' when calling OAuthApi->ObtainToken");
            }


            var localVarPath = "/oauth2/token";

            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new Dictionary <String, String>();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");

            if (body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (localVarStatusCode >= 400)
            {
                throw new ApiException(localVarStatusCode, "Error calling Obtain Token: " + localVarResponse.Content, localVarResponse.Content);
            }
            else if (localVarStatusCode == 0)
            {
                throw new ApiException(localVarStatusCode, "Error calling Obtain Token: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
            }

            return(new ApiResponse <ObtainTokenResponse>(localVarStatusCode,
                                                         localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                         (ObtainTokenResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(ObtainTokenResponse))));
        }
        /// <summary>
        /// ObtainToken
        /// </summary>
        /// <remarks>
        /// If you obtained a temporary authorization code from a request to the Authorize endpoint, you exchange that code for an access token with a request to this endpoint.
        /// </remarks>
        /// <exception cref="T:SquareConnectApiClient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">An object containing the fields to POST for the request.\n\nSee the corresponding object definition for field details.</param>
        /// <returns>Task of ObtainTokenResponse</returns>
        public async Task <ObtainTokenResponse> ObtainTokenAsync(ObtainTokenRequest body)
        {
            ApiResponse <ObtainTokenResponse> localVarResponse = await ObtainTokenAsyncWithHttpInfo(body);

            return(localVarResponse.Data);
        }
        /// <summary>
        /// ObtainToken
        /// </summary>
        /// <remarks>
        /// If you obtained a temporary authorization code from a request to the Authorize endpoint, you exchange that code for an access token with a request to this endpoint.
        /// </remarks>
        /// <exception cref="T:SquareConnectApiClient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">An object containing the fields to POST for the request.\n\nSee the corresponding object definition for field details.</param>
        /// <returns>ObtainTokenResponse</returns>
        public ObtainTokenResponse ObtainToken(ObtainTokenRequest body)
        {
            ApiResponse <ObtainTokenResponse> localVarResponse = ObtainTokenWithHttpInfo(body);

            return(localVarResponse.Data);
        }