yoco/yoco-php

Yoco PHP 库

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

This package is not auto-updated.

Last update: 2024-09-28 10:45:39 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.

简单来说,过程如下

  1. 使用 Web SDK 安全地捕获卡片详情,然后提供相应的充电令牌
  2. 将充电令牌发送到您的后端服务器,并通过 PHP 客户端库(本包)最终完成充电

Web SDK 在纯 PHP 和 Laravel 中的完整示例实现可在 此处 获取。

有关 API 的更多信息,您可以参考 Yoco API 文档

要求

PHP 7.0 及以上。

Composer

使用 Composer 安装库

composer require yoco/yoco-php

要使用库

require_once('vendor/autoload.php');

手动安装

直接从本存储库下载库,并将其解压缩到您的实现中。

依赖关系

入门

以下是一个简单的示例,假设以下条件

  • 前端 Web SDK 已按 SDK 文档 中所述用于捕获卡片详情、金额和货币。
  • 前端通过 AJAX 请求您的后端 PHP 代码进行卡片充电
// 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;
}

文档

请参阅 API 文档