PHP code example of shinidev / paymongo-php

1. Go to this page and download the library: Download shinidev/paymongo-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shinidev / paymongo-php example snippets






use Paymongo\PaymongoClient;

$client = new PaymongoClient('sk_test_YOUR_SECRET_KEY');


$paymentIntent = $client->paymentIntents->create([
    'amount' => 15000, // 150.00 PHP
    'currency' => 'PHP',
    'payment_method_allowed' => ['card', 'paymaya', 'gcash'],
    'description' => 'My Test Payment Intent'
]);

echo "Created Payment Intent: " . $paymentIntent->id;


// Retrieve a single resource by its ID
$retrievedIntent = $client->paymentIntents->retrieve($paymentIntent->id);
echo "Retrieved Status: " . $retrievedIntent->status;

// Retrieve a list of resources
$paymentsList = $client->payments->all(['limit' => 5]);
foreach ($paymentsList->data as $payment) {
    echo "Payment ID: " . $payment->id;
}


use Paymongo\Exceptions\InvalidRequestException;
use Paymongo\Exceptions\AuthenticationException;
use Paymongo\Exceptions\ApiException;

try {
    // Attempt an API call that will fail
    $client->payments->create([ 'amount' => 50 ]); // Missing ssage() . "\n";
    
    // Use getErrors() to see detailed validation messages
    foreach ($e->getErrors() as $error) {
        echo " - Field `{$error->source->attribute}`: {$error->detail}\n";
    }

} catch (ApiException $e) {
    // Handle any other generic API error
    echo "API Error: " . $e->getMessage();
}


use Paymongo\Exceptions\SignatureVerificationException;

// These values come from the HTTP request sent by PayMongo to your server
$payload = file_get_contents('php://input');
$signatureHeader = $_SERVER['HTTP_PAYMONGO_SIGNATURE'] ?? '';
$webhookSecretKey = 'whsec_test_YOUR_WEBHOOK_SECRET_KEY';

try {
    $event = $client->webhooks->constructEvent(
        $payload,
        $signatureHeader,
        $webhookSecretKey
    );

    echo "Webhook signature verified! Event type: {$event->type}\n";
    
    // Now you can safely handle the event
    switch ($event->type) {
        case 'payment.succeeded':
            $payment = $event->resource;
            // Fulfill the customer's order, send an email, etc.
            break;
        // ... handle other event types
    }

    // Respond to PayMongo with a 200 OK status to acknowledge receipt
    http_response_code(200);

} catch (SignatureVerificationException $e) {
    // The signature was invalid or the timestamp was too old. Do not trust the payload.
    // Respond with a 400 Bad Request status to tell PayMongo not to retry.
    http_response_code(400);
    echo "Webhook verification failed: {$e->getMessage()}\n";
}
bash
composer