Search code examples
phpbraintree

Braintree PHP Library (3.8.0) Error Handling


The PHP library returns result objects from most of the API calls. What is the official way of distinguishing between a validation error and a transaction error?

The Braintree docs seem to suggest using sizeof($result->errors) > 0 to determine if validation errors have occurred. But this is also > 0 when a transaction error has occurred.

The only other way I can think of is somehow determining whether the transaction object exists within the $result object, a bit of a hack, and then viewing the status within the transaction object


Solution

  • Full disclosure: I work at Braintree. If you have any further questions, feel free to contact our support team.

    You are correct that the suggested way to check for transaction errors is to see if there is a transaction object present. Here is a snippet of code illustrating appropriate error handling for a Braintree\Transaction::sale call.

    if ($result->success){
        $transaction = $result->transaction;
    } elseif (!is_null($result->transaction)){
        $transaction = $result->transaction;
        $_SESSION["errors"] = "Transaction status - " . $result->transaction->status;
    } else {
        $errorString = "";
    
        foreach($result->errors->deepAll() as $error) {
            $errorString .= $error->code . "-" . $error->message . "\n";
        }
    
        $_SESSION["errors"] = $errorString;
    }