Forum

PHP

Webhooks

For days now i coud'nt solved the problem of Webhooks, i'm using https://paystack.com, therefore an offline payment can be made using USSD solution to send a payment to a created virtual account, the i read the documentation via https://paystack.com/docs/payments/webhooks/ i found the following code which set to make a request to the server to get notified whenever an event happend (i.e. the payment),

<?php
    // Retrieve the request's body and parse it as JSON
    $input = @file_get_contents("php://input");
    $event = json_decode($input);
    // Do something with $event
    http_response_code(200); // PHP 5.4 or greater
?>

from the above, i tried the print the event as:

<?php
    print_r($event);
?>

Still showing null at https://daddyone.com.ng/test where the URL is a POST Request.

I was totally confused did'nt know how to solve this problem, @general help me out please, how to make the request and how to get the request and store it in the database.

aymmuazu
0
3
354
aymmuazu

No one responded, but i solved the problem.

Haz
Moderator

Maybe it will be useful for others if you share the solution.

0
aymmuazu

The event works perfectly, but it happends within a seconds to notified the server whenever an event occur, therefore, i use switch statement to switch whenever an event occur e.g. 'charge.success' i then save the event in the database, otherwise return null and json data, that's all, i tried it and make a testing payment and it works perfectly, the platform was build based on USSD payment that's why i got stucked.

if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) ) { // only a post with paystack signature header gets our attention exit(); } // Retrieve the request's body $input = @file_get_contents("php://input"); define('PAYSTACK_SECRET_KEY', getenv('LIVE_PAYSTACK_API_KEY'));

if(!$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] || ($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))){
// silently forget this ever happened
exit();
}
http_response_code(200);
// parse event (which is json string) as object
// Do something - that will not take long - with $event
$event = json_decode($input);

switch($event->event){
    // subscription.create
    case 'subscription.create':
        break;
    // charge.success
    case 'charge.success':
        //Store event in the database.
    break;
    // subscription.disable
    case 'subscription.disable':
        break;

    // invoice.create and invoice.update
    case 'invoice.create':
        break;
    case 'invoice.update':
        break;
}
exit();
0