Search code examples
c#amazon-pay

Pay with Amazon behaving async


I have integrated Pay with Amazon with my web app, but I have determined that capturing funds only works when I step through the code debugging, and does not happen if I don't have a break-point. To me, this indicates that a pause is necessary. I am using recurring payments. The relevant section of code is below:

...
//make checkout object
AmazonAutomaticSimpleCheckout asc = new AmazonAutomaticSimpleCheckout(billingAgreeementId);

//capture
CaptureResponse cr = asc.Capture(authId, amount, 1);

//check if capture was successful
if (cr.CaptureResult.CaptureDetails.CaptureStatus.State == PaymentStatus.COMPLETED)
{
     ...
     //give the user the things they paid for in the database
     ...

     return "success";
}
...

So, if I have a break-point at the capture line under //capture, then the function returns success. If I do not have the break-point, I get a runtime exception System.NullReferenceException: Object reference not set to an instance of an object. regarding the following if statement.

To me, this implies that I should be able to await the capture method.

Also note, the capture(...) method is calling the CaptureAction(...) method, just as the C# sample does.

//Invoke the Capture method
public CaptureResponse Capture(string authId, string captureAmount, int indicator)
{
    return CaptureAction(propertiesCollection, service, authId, captureAmount, billingAgreementId, indicator, null, null);
}

How can I await the capture call? Am I forgetting to pass a parameter to indicate that it should execute the operation immediately?


Solution

  • It seems after some experimentation, that a function that will essentially achieve the wait I was performing manually using a break-point is the function CheckAuthorizationStatus(), which is also in the C# sample provided with the documentation.

    So the fixed code simply adds CheckAuthorizationStatus() before calling the capture() method. CheckAuthorizationStatus() apparently loops until the state of the authorization changes. This seems somewhat kludgey to me, but seems to be how the Pay with Amazon APIs are meant to be used, as best I can tell. Corrected code below:

    //make checkout object
    AmazonAutomaticSimpleCheckout asc = new AmazonAutomaticSimpleCheckout(billingAgreeementId);
    
    //capture
    CaptureResponse cr;
    
    GetAuthorizationDetailsResponse gadr = asc.CheckAuthorizationStatus(authId);
    
    cr = asc.Capture(authId, amount, 1);
    
    //gadr = asc.CheckAuthorizationStatus(authId);
    
    //check if capture was succeddful
    if (cr.CaptureResult.CaptureDetails.CaptureStatus.State == PaymentStatus.COMPLETED)
    {
         ...
    
         return "success";
     }