0

If I use the API Explorer V4, and I try to create a new contribution with a Transaction ID that already exists, then the response I get back is as follows:

status: 500, statusText: Internal Server Error, xhrStatus: complete
{
  "error_code": 0,
  "error_message": "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: 100"
}

But when running an external script (CiviCRM v5.48.1 with WordPress v5.9.3), if I try to add a contribution and the Transaction ID already exists, it causes script to crash and returns the following php fatal error in the log:

PHP Fatal error:  Uncaught CRM_Core_Exception: [0: Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: 99
  thrown in /home/me/public_html/wp-content/plugins/civicrm/civicrm/CRM/Contribute/BAO/Contribution.php on line 103

My expectation was that I should still get a response/result from my call that contains the error message without crashing the script.

This is my test code to reproduce the error:

<?php

require_once '/home/me/public_html/wp-content/plugins/civicrm/civicrm/civicrm.config.php';
require_once '/home/me/public_html/wp-content/plugins/civicrm/civicrm/CRM/Core/Config.php';
$civi_config = CRM_Core_Config::singleton();

for ($i=1; $i<=3; $i++) {
    
    $transaction_id = "xyz123"; // needs to be unique but use same id to test for this bug
    $total_amount = 2*$i;
    $source = 'Test '.$i;
    $contribution_results = civicrm_api4('Contribution', 'create', [
      'checkPermissions'=>FALSE,
      'values' => [
        'contact_id' => '262', 
        'financial_type_id' => '1', 
        'payment_instrument_id' => '1', 
        'total_amount' => $total_amount, 
        'trxn_id' => $transaction_id, 
        'currency' => 'USD', 
        'source' => $source,
      ],
    ]);
    
    echo "<pre>";
    print_r($contribution_results);
    echo "</pre>";
}

?>

1 Answer 1

1

It's throwing an exception so if you don't want that to kill your script you need to enclose the api call in a try {} catch {}block. See php documentation on exceptions Eg:

try {
  $contribution_results = civicrm_api4( ...... );
}
catch (Exception $e) {
  print "Error: " . $e->getMessage();
}
1
  • Ahhh ... that's why they pay you the big bucks! ;)
    – jsherk
    Commented May 20, 2022 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.