in Engineering

A Second Look at the GoCardless PHP Library

This post relates to the Legacy GoCardless API. If you're starting a new integration, you'll need to use the new GoCardless API - for help getting started, check out our guide.

In our first blog post about our PHP library we looked at how to create a payment URL and then confirm the payment once it had been created. Examples of this are included in the repo itself (in the /examples folder) and detailed in our documentation too. Now let's look at a couple of other features available with the library.

Passing a variable through the payment process

Very often when the user arrives at the Redirect URI (where you must confirm the new payment object) you will want a way to refer to what the payment was for. We have a variable for that called 'state'. You can pass in 'state' as a variable when you generate a new payment link:

<?php
// The parameters for the payment
$subscription_details = array(
 'amount' => '10.00',
 'interval_length' => 1,
 'interval_unit' => 'month',
 'state' => $reference
);

// Generate the url
$subscription_url = GoCardless::new_subscription_url($subscription_details);

// Display the link
echo '<a href="'.$subscription_url.'">New subscription</a>';
?>

It then gets passed back to the Redirect URI page as a GET variable which you can access like this:

<?php
$reference = $_GET['state'];
?>

Creating bills within a pre-authorization

Our pre-authorization payment type lets you bill your customer whenever you want to up to an agreed limit. To create a bill within a pre-authroization, you can do the following:

<?php
// Load your pre-authorization
$pre_auth = GoCardless_PreAuthorization::find($pre_auth_id);

// Details of the bill to create
$bill_details = array(
 'amount' => '5.00'
);

// Create the bill
$bill = $pre_auth->create_bill($bill_details);
?>

Cancelling a subscription

<?php
// Load the subscription
$subscription = GoCardless_Subscription::find($subscription_id);

// Call the cancel method
$subscription = $subscription->cancel();
?>

Webhooks

We fire off a webhook a few days after a payment is made to confirm whether the payment was successful or not. In the most recent version of the PHP library we included a webhook listener demo. The webhook content is sent in the body of the request (rather than in the headers) which you can extract like this:

<?php
// Use this line to fetch the body of the HTTP request
$webhook = file_get_contents('php://input');

// Convert json blog to array
$webhook_array = json_decode($webhook, true);

// Validate webhook
if (GoCardless::validate_webhook($webhook_array['payload'])) {
 // Send a success header
 header('HTTP/1.1 200 OK');
}
?>
By using this site you agree to the use of cookies for analytics, personalised content and ads. Learn more