I am trying to implement Authorize.net webhook on a Laravel project. From merchant interface, I added a webhook endpoint. But when I try to retrieve events it throws invalid JSON error. What am I doing wrong in the code below?
namespace App\Http\Controllers\Api\Anet;
use Illuminate\Http\Request;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use App\Http\Controllers\Controller;
use JohnConde\Authnet\AuthnetWebhook;
class xxxController extends Controller
{
public function webhook(){
$headers = getallheaders();
$payload = file_get_contents("php://input");
$webhook = new AuthnetWebhook(hex2bin('XXXXXD4FF0A6060E23DBCD9AE507E20XXXXX'), $payload, $headers);
if ($webhook->isValid()) {
// Get the transaction ID
$transactionId = $webhook->payload->id;
// Here you can get more information about the transaction
$request = AuthnetApiFactory::getJsonApiHandler('services.authorize.login', 'services.authorize.key');
$response = $request->getTransactionDetailsRequest(array(
'transId' => $transactionId
));
/* You can put these response values in the database or whatever your business logic dictates.
$response->transaction->transactionType
$response->transaction->transactionStatus
$response->transaction->authCode
$response->transaction->AVSResponse
*/
}
}
}
Error:
"message": "Invalid JSON sent in the Webhook notification",
"exception": "JohnConde\\Authnet\\AuthnetInvalidJsonException",
"file": "/var/www/html/staging/vendor/stymiee/authnetjson/src/authnet/AuthnetWebhook.php",
"line": 67,
Your problem is that you are not getting a webhook notification. The code you are using is purposed for validating a webhook notification, rather than making a webhooks request. You have to make a request to get a webhook.
When you set up your endpoint, you can use that code (although I don't think the hex2bin() is required) to validate webhooks and then extract information from them.
To create a webhooks request, you can use code like this-
This will enroll you in events, which will automatically be sent to your endpoint i.e
https://{yourserver.com}/{your path}/{your endpoint}
.Then you can use your code above to validate the webhooks when they hit your endpoint. Once you are enrolled in events and webhooks are being sent to your endpoint, you can retrieve the history using code like this-
You can retrieve a specific webhook like this-
Where $webhookId is the id tied to the webhook you wish to retrieve. You can search through the namespace to see the other method calls for specific webhook actions.