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"); } }
public async Task <IActionResult> ProcessPaymentAsync(string nonce) { try { Square.Environment environment = appSettings.Environment == "sandbox" ? Square.Environment.Sandbox : Square.Environment.Production; // Build base client SquareClient client = new SquareClient.Builder() .Environment(environment) .AccessToken(this.appSettings.AccessToken) .Build(); IPaymentsApi PaymentsApi = client.PaymentsApi; CreatePaymentRequest request_body = new CreatePaymentRequest(nonce, this.NewIdempotencyKey(), new Money(100, "USD")); CreatePaymentResponse responce = await PaymentsApi.CreatePaymentAsync(request_body); if (responce?.Payment?.Status == "COMPLETED") { //this.UpdateCart(new CartModel()); return(this.Ok()); } else { return(this.BadRequest($"STATUS: {responce?.Payment?.Status}")); } } catch (Exception ex) { return(this.BadRequest($"PaymentError: { ex.Message }")); } }
public IActionResult Paid() { Square.Environment environment = this.appSettings.Environment == "sandbox" ? Square.Environment.Sandbox : Square.Environment.Production; // Build base client SquareClient client = new SquareClient.Builder() .Environment(environment) .AccessToken(this.appSettings.AccessToken) .Build(); string nonce = Request.Form["nonce"]; IPaymentsApi PaymentsApi = client.PaymentsApi; // Every payment you process with the SDK must have a unique idempotency key. // If you're unsure whether a particular payment succeeded, you can reattempt // it with the same idempotency key without worrying about double charging // the buyer. string uuid = this.NewIdempotencyKey(); // Monetary amounts are specified in the smallest unit of the applicable currency. // This amount is in cents. It's also hard-coded for $1.00, // which isn't very useful. Money amount = new Money.Builder() .Amount(500L) .Currency("USD") .Build(); // To learn more about splitting payments with additional recipients, // see the Payments API documentation on our [developer site] // (https://developer.squareup.com/docs/payments-api/overview). CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(nonce, uuid, amount) .Note("From Square Visit Cart App") .Build(); try { CreatePaymentResponse response = PaymentsApi.CreatePayment(createPaymentRequest); PaymentResultModel model = new PaymentResultModel { ResultMessage = "Payment complete! " + response.Payment.Note }; return(View(model)); } catch (ApiException ex) { return(View("PaymentError", new ErrorViewModel { Message = ex.Message })); } }
public PaymentController(Microsoft.Extensions.Configuration.IConfiguration configuration) { iConfig = configuration; // Get environment Square.Environment environment = configuration["AppSettings:Environment"] == "sandbox" ? Square.Environment.Sandbox : Square.Environment.Production; // Build base client client = new SquareClient.Builder() .Environment(environment) .AccessToken(configuration["AppSettings:AccessToken"]) .Build(); //locationId = configuration["AppSettings:LocationId"]; }
public void TestV2APIException() { SquareClient badClient = new SquareClient.Builder() .Environment(Environment.Sandbox) .AccessToken("BAD_TOKEN") .Build(); var api = badClient.LocationsApi; var ex = Assert.Throws <ApiException>(() => api.ListLocations()); Assert.AreEqual(ex.ResponseCode, 401); var errors = ex.Errors; Assert.AreEqual(errors[0].Category, "AUTHENTICATION_ERROR"); Assert.AreEqual(errors[0].Code, "UNAUTHORIZED"); }
/* * public (Payment, string) CreatePayment(CreatePaymentRequest paymentRequest, int storeId) * { * if (paymentRequest == null) * throw new ArgumentNullException(nameof(paymentRequest)); * * var client = CreateSquareClient(storeId); * * try * { * var paymentResponse = client.PaymentsApi.CreatePayment(paymentRequest); * if (paymentResponse == null) * throw new NopException("No service response"); * * ThrowErrorsIfExists(paymentResponse.Errors); * * return (paymentResponse.Payment, null); * } * catch (Exception exception) * { * return (null, CatchException(exception)); * } * } * public (bool, string) CompletePayment(string paymentId, int storeId) * { * if (string.IsNullOrEmpty(paymentId)) * return (false, null); * * var client = CreateSquareClient(storeId); * * try * { * var paymentResponse = client.PaymentsApi.CompletePayment(paymentId, null); * if (paymentResponse == null) * throw new NopException("No service response"); * * ThrowErrorsIfExists(paymentResponse.Errors); * * //if there are no errors in the response, payment was successfully completed * return (true, null); * } * catch (Exception exception) * { * return (false, CatchException(exception)); * } * } * public (bool, string) CancelPayment(string paymentId, int storeId) * { * if (string.IsNullOrEmpty(paymentId)) * return (false, null); * * var client = CreateSquareClient(storeId); * * try * { * var paymentResponse = client.PaymentsApi.CancelPayment(paymentId); * if (paymentResponse == null) * throw new NopException("No service response"); * * ThrowErrorsIfExists(paymentResponse.Errors); * * //if there are no errors in the response, payment was successfully canceled * return (true, null); * } * catch (Exception exception) * { * return (false, CatchException(exception)); * } * } * public (PaymentRefund, string) RefundPayment(RefundPaymentRequest refundPaymentRequest, int storeId) * { * if (refundPaymentRequest == null) * throw new ArgumentNullException(nameof(refundPaymentRequest)); * * var client = CreateSquareClient(storeId); * * try * { * var refundPaymentResponse = client.RefundsApi.RefundPayment(refundPaymentRequest); * if (refundPaymentResponse == null) * throw new NopException("No service response"); * * ThrowErrorsIfExists(refundPaymentResponse.Errors); * * return (refundPaymentResponse.Refund, null); * } * catch (Exception exception) * { * return (null, CatchException(exception)); * } * } * public (string AccessToken, string RefreshToken) ObtainAccessToken(string authorizationCode, int storeId) * { * return _squareAuthorizationHttpClient.ObtainAccessTokenAsync(authorizationCode, storeId).Result; * } * public (string AccessToken, string RefreshToken) RenewAccessToken(int storeId) * { * return _squareAuthorizationHttpClient.RenewAccessTokenAsync(storeId).Result; * } * public bool RevokeAccessTokens(int storeId) * { * return _squareAuthorizationHttpClient.RevokeAccessTokensAsync(storeId).Result; * } */ private void Main() { SquareClient client = new SquareClient.Builder() .Environment(Square.Environment.Sandbox) .AccessToken("YOUR_SANDBOX_ACCESS_TOKEN") .Build(); var api = client.LocationsApi; try { var locations = api.ListLocations().Locations; Console.WriteLine("Successfully called ListLocations"); // Your business logic here } catch (ApiException e) { var errors = e.Errors; var statusCode = e.ResponseCode; var httpContext = e.HttpContext; Console.WriteLine("ApiException occurred:"); Console.WriteLine("Headers:"); foreach (var item in httpContext.Request.Headers) { //Display all the headers except Authorization if (item.Key != "Authorization") { Console.WriteLine("\\t{0}: \\{1}", item.Key, item.Value); } } Console.WriteLine("Status Code: \\{0}", statusCode); foreach (Error error in errors) { Console.WriteLine("Error Category:{0} Code:{1} Detail:{2}", error.Category, error.Code, error.Detail); } // Your error handling code } catch (Exception e) { Console.WriteLine("Exception occurred"); // Your error handling code } }
public void TestV1APIException() { SquareClient badClient = new SquareClient.Builder() .Environment(Environment.Production) .AccessToken("BAD_TOKEN") .Build(); var api = badClient.V1LocationsApi; var ex = Assert.Throws <ApiException>(() => api.ListLocations()); Assert.AreEqual(ex.ResponseCode, 401); var errors = ex.Errors; Assert.AreEqual(errors[0].Category, "V1_ERROR"); Assert.AreEqual(errors[0].Code, "service.not_authorized"); Assert.AreEqual(errors[0].Detail, "Not Authorized"); }
public void TestV2APIException() { SquareClient badClient = new SquareClient.Builder() .Environment(Environment.Sandbox) .AccessToken("BAD_TOKEN") .Build(); var api = badClient.CustomersApi; var ex = Assert.Throws <ApiException>(() => api.ListCustomers()); Assert.AreEqual(ex.ResponseCode, 401); var errors = ex.Errors; Assert.AreEqual(errors[0].Category, "AUTHENTICATION_ERROR"); Assert.AreEqual(errors[0].Code, "UNAUTHORIZED"); Assert.AreEqual(errors[0].Detail, "The `Authorization` http header of your request was malformed. The header value is expected to be of the format \"Bearer TOKEN\" (without quotation marks), where TOKEN is to be replaced with your access token (e.g. \"Bearer ABC123def456GHI789jkl0\"). For more information, see https://docs.connect.squareup.com/api/connect/v2/#requestandresponseheaders. If you are seeing this error message while using one of our officially supported SDKs, please report this to [email protected]."); }
private async Task SynchVenuesWithExternalPaymentProvider(string accessToken, Company company) { if (company == null) { return; } try { var client = new SquareClient.Builder() .Environment(_settings.Connection.SquarePaymentsSandbox ? Square.Environment.Sandbox : Square.Environment.Production) .AccessToken(accessToken) .Build(); ListLocationsResponse result = await client.LocationsApi.ListLocationsAsync().ConfigureAwait(false); var companyVenues = await _venues.FetchCompanyVenues(company.CompanyId, 0, int.MaxValue) .OnSuccess(c => c.Value.ToList()) .ConfigureAwait(true); if (companyVenues.IsSuccess) { foreach (var item in companyVenues.Value) { try { var matchedLocation = result.Locations .FirstOrDefault( x => NormaliseString(x.Name) == NormaliseString(item.VenueName) && NormaliseString(x.Address.PostalCode) == NormaliseString(item.VenuePostCode)); // need to find a match in Square location if (matchedLocation != null) { if (string.IsNullOrWhiteSpace(item.ExternalLocationId) && matchedLocation != null) { // We have a match and need to update local Database await _venues.UpdateVenue(new VenuePatch { ResourceId = item.VenueId, ExternalLocationId = new PatchOperation <string> { Operation = OperationKind.Update, Value = matchedLocation.Id }, }).ConfigureAwait(false); } } else if (matchedLocation == null) { // we have a location in our system that does not exist in sqaure. Need to add one var createLocation = new CreateLocationRequest(new Location( name: item.VenueName, address: new Address( addressLine1: string.IsNullOrWhiteSpace(item.VenueAddress) ? "Not supplied" : item.VenueAddress, addressLine2: item.VenueAddress2, addressLine3: item.VenueAddress3, postalCode: string.IsNullOrWhiteSpace(item.VenuePostCode) ? "Not supplied" : item.VenuePostCode, locality: string.IsNullOrWhiteSpace(item.VenueCounty) ? "Not supplied" : item.VenueCounty, firstName: item.VenueContact), status: "ACTIVE", phoneNumber: GetVenuePhoneNumber(company, item))); var newLocation = client.LocationsApi.CreateLocation(createLocation); if (newLocation.Location != null) { await _venues.UpdateVenue(new VenuePatch { ResourceId = item.VenueId, ExternalLocationId = new PatchOperation <string> { Operation = OperationKind.Update, Value = newLocation.Location.Id }, }).ConfigureAwait(false); } } } catch (ApiException e) { Logger.LogError(e, $"Failed to create business location for venue {item.VenueName}"); } } } } catch (ApiException e) { Logger.LogError(e, $"Failed to connect to Square API"); } }
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)); }