Search code examples
c#square

Proper Way To See If Square Checkout Process Completed


I am currently working on a C# Windows Form project that requires the user to pay prior to any processing taking place. I am using the Square .Net SDK for payment processing and have successfully managed to get a payment through to the sandbox environment using the Checkout URL generated by the Checkout API. My question is whether there is a simple way to get whether the payment process has been completed. Right now, I am just polling the API with the same order (with identical idempotency keys) and waiting for it to return an error that the order is no longer valid. Here is the backbone of my current code:

var bodyOrderLineItems = new List<CreateOrderRequestLineItem>();
long totalCost = 100;
var charge0 = new Money.Builder().Amount(totalCost).Currency("USD").Build();
bodyOrderLineItems.Add(new CreateOrderRequestLineItem.Builder("1").Name("Incredibly Valuable Product").BasePriceMoney(charge0).Build());
var order = new CreateOrderRequest.Builder()
                    .ReferenceId("reference_id")
                    .LineItems(bodyOrderLineItems)
                    .Build();
var body = new CreateCheckoutRequest.Builder("Test_iKey4", order)
                    .AskForShippingAddress(false)
                    .Build();
var checkoutApi = client.CheckoutApi;

try
{
     CreateCheckoutResponse result = checkoutApi.CreateCheckout(locationsString, body);
     System.Diagnostics.Process.Start(result.Checkout.CheckoutPageUrl);
     while (true)
     {

         System.Threading.Thread.Sleep(5000);
         //while payment hasn't gone through
         try
         {
             result = checkoutApi.CreateCheckout(locationsString, body);
         }
         catch (ApiException e)
         {
             MessageBox.Show(e.Errors[0].Detail);
             break;
         }
     }
     MessageBox.Show("Payment Must Have Gone Through");
}
catch (ApiException e) { MessageBox.Show(e.Errors[0].Detail); };

Is this a valid approach? While this does seem to work, I feel like I am flooding the api with requests. I am pretty inexperienced with the Square API, so any help would be appreciated.


Solution

  • Typically the Checkout API is used within a website, as it includes a parameter redirect_url so that when the payment is complete, the user is redirected back to your side and it includes url parameters such as the transaction id. If you don't have a website, you can instead sign up for webhooks. The PAYMENT_UPDATED webhook will be sent out when a payment has been processed, so you do not need to do polling; just listen for the webhook.