yoco/yoco-php

Yoco PHP Library

v0.1.0-beta 2021-08-05 20:49 UTC

This package is not auto-updated.

Last update: 2024-05-11 08:56:32 UTC


README

The Yoco PHP client library provides access to the Yoco Payment API from PHP. It does this by providing client classes and associated method calls that abstract the underlying Yoco API requests, responses and errors.

This library is used in conjunction with the frontend Web SDK described here which securely captures the customer's card details and generates the required token.

Put simply, the process is:

  1. Securely capture card details using the Web SDK, which then provides a charge token
  2. Send the charge token to your backend server and finalise the charge via the PHP client library (this package)

A full sample implementation of the Web SDK in vanilla PHP and Laravel is available here.

For more information on the APIs, you can refer to the Yoco API Docs.

Requirements

PHP 7.0 and later.

Composer

Install the library with Composer:

composer require yoco/yoco-php

To use the library:

require_once('vendor/autoload.php');

Manual Installation

Download the library directly from this repository and extract it into your implementation.

Dependencies

Getting Started

A simple example is as follows and assumes the following:

  • The frontend Web SDK has been used to capture the card details, amount and currency as described in the SDK docs.
  • The frontend makes an AJAX request to your backend PHP code to charge the card
// variables from your HTTP request
$token = $_POST['token']; // the token generated by the frontend API
$amountInCents = $_POST['amountInCents']; // the amount (in cents to be charged)
$currency = $_POST['currency']; // the currency of the amount

// Initialize the client with your keys.
$client = new \Yoco\YocoClient('your_secret_key', 'your_public_key');

try{
    // Charge the card with the YocoClient
    $client->charge($token, $amountInCents, $currency)
} catch (\Yoco\Exceptions\DeclinedException $e) {
    // Catch the declined exception
    error_log("Failed to charge card with token $token, amount $currency $amountInCents : " . $e->getMessage());
    // Inform the requester if the bad request and pass the error back
    Header("HTTP/1.1 400 Bad Request");
    print(json_encode(['charge_error' => $e]));
    exit;
} catch (\Yoco\Exceptions\InternalException $e) {
    // Catch the general exception
    error_log("Failed to charge card with token $token, amount $currency $amountInCents : " . $e->getMessage());
    // Inform the requester if the bad request and pass the error back
    Header("HTTP/1.1 400 Bad Request");
    print(json_encode(['charge_error' => $e]));
    exit;
}

Documentation

See the API docs.