Solved

RevenueCat Webhook endpoint php integration

  • 29 March 2022
  • 1 reply
  • 971 views

Badge +1

Hi team, 
Is there an example of a Revenuecat webhook endpoint that we can use in our backend php to fetch events data? we d'ont find a kind of information on documentation.
We need a sample like this one (used on stripe) bellow : 
<?php
// webhook.php  
\Stripe\Stripe::setApiKey('Your_Key');  
$endpoint_secret = 'whsec_...'; 
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null; 

try {
  $event = \Stripe\Webhook::constructEvent(
    $payload, $sig_header, $endpoint_secret
  );
} catch(\UnexpectedValueException $e) {
  // Invalid payload
  echo '⚠️  Webhook error while parsing basic request.';
  http_response_code(400);
  exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
  // Invalid signature
  echo '⚠️  Webhook error while validating signature.';
  http_response_code(400);
  exit();

// Handle the event
switch ($event->type) {
  case 'customer.subscription.created':
           // What to do
    break;
  case 'customer.subscription.deleted':
           // What to do
    break;
  case 'customer.subscription.updated':
           // What to do
    break; 
    case 'invoice.payment_failed':
        // What to do
    break;
  // ... handle other event types
  default:
    echo 'Received unknown event type ' . $event->type;
}  
http_response_code(200); 
?>
Thanks in advance.

icon

Best answer by CITDEV 30 March 2022, 13:50

View original

1 reply

Badge +1
So I developed this solution, if anyone needs it:  

<?php
header('Content-Type: application/json');  
$headers = apache_request_headers();
  if(isset($headers['Authorization'])){ // Add this condition just if Authorization Code is defined!
    $auth = $headers['Authorization']; 
      if ($auth == 'Your_Authorization') {  

try {
$data = json_decode(file_get_contents('php://input'), true);
$eventType = $data['event']['type']; 
} catch(\UnexpectedValueException $e) { 
  echo '⚠️  Webhook error while parsing basic request.';
  http_response_code(400);
  exit();
} catch(Exception $e) { 
  echo '⚠️  Webhook error . $e';
  http_response_code(400);
  exit();
}  
switch ($eventType) {
   case 'TEST': 
        echo '⚠️Test OK';
    break;
   case 'INITIAL_PURCHASE':
    // code...
    break;
   case 'NON_RENEWING_PURCHASE':
    // code...
    break;
   case 'RENEWAL':
    // code...
    break;
   case 'PRODUCT_CHANGE':
    // code...
    break;
   case 'CANCELLATION':
    // code...
    break;
   case 'BILLING_ISSUE':
    // code...
    break;
  case 'SUBSCRIBER_ALIAS':
    // code...
    break;
  case 'SUBSCRIPTION_PAUSED':
    // code...
    break;
  case 'TRANSFER':
    // code...
    break;
    case 'EXPIRATION':
    // code...
    break;
    // handle other events..
  default:
    // code...
    break;
}

http_response_code(200);

   }
    }

?>

Reply