vivekjadaun/paystack-php

帮助您通过stdClass对象进行Paystack API调用。

v2.2 2019-11-13 14:18 UTC

README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Paystack提供的PHP API包装器。

Paystack

要求

  • Curl 7.34.0或更高版本(除非使用Guzzle)
  • PHP 5.4.0或更高版本
  • OpenSSL v1.0.1或更高版本

安装

通过Composer

    $ composer require yabacon/paystack-php

通过下载

发布页面下载一个发布版本。解压缩,然后

    require 'path/to/src/autoload.php';

重要

版本2与版本1的代码不兼容!如果cURL或Paystack API在响应体中返回错误状态,它将引发错误。

使用方法

将重定向到从调用交易/初始化端点收到的授权URL。此URL只能使用一次,因此请确保为每笔交易生成一个新的URL。

当支付成功时,我们将调用您的回调URL(在您的仪表板中设置或在初始化交易时设置)并返回第一步中发送的引用作为查询参数。

如果您使用测试密钥,我们将调用您的测试回调URL,否则,我们将调用您的实时回调URL。

0. 先决条件

确认您的服务器可以与Paystack服务器建立TLSv1.2连接。大多数最新的软件都具备此功能。如果您有任何SSL错误,请联系您的服务提供商以获得指导。不要禁用SSL端点验证!

1. 准备参数

emailamount 是最常见的必填参数。请为每位客户发送唯一的电子邮件。如果您的客户不提供唯一的电子邮件,请为每个客户制定一个策略来设置一个。以下任何一种都可以正常工作。我们接受的端点金额以科博为单位,必须是整数。例如,为了接受 456奈拉,78科博,请发送 45678 作为金额。

2. 初始化交易

通过调用我们的API来初始化交易。

    $paystack = new Yabacon\Paystack(SECRET_KEY);
    try
    {
      $tranx = $paystack->transaction->initialize([
        'amount'=>$amount,       // in kobo
        'email'=>$email,         // unique to customers
        'reference'=>$reference, // unique to transactions
      ]);
    } catch(\Yabacon\Paystack\Exception\ApiException $e){
      print_r($e->getResponseObject());
      die($e->getMessage());
    }

    // store transaction reference so we can query in case user never comes back
    // perhaps due to network issue
    save_last_transaction_reference($tranx->data->reference);

    // redirect to page so User can pay
    header('Location: ' . $tranx->data->authorization_url);

当用户输入他们的卡详细信息时,Paystack将验证并扣费卡。它将执行以下所有操作

重定向回在初始化交易时设置的回调URL或您的仪表板中的: https://dashboard.paystack.co/#/settings/developer 。如果两者都没有设置,客户将看到“交易成功”的消息。

向在: https://dashboard.paystack.co/#/settings/developer 设置的Webhook URL发送charge.success事件

如果未关闭收据,将向客户的电子邮件发送HTML收据。

在向客户付款之前,请通过我们的验证端点进行服务器端调用,以确认交易的状态和属性。

3. 处理charge.success事件

我们将向为交易域设置的Webhook URL发送charge.success事件。如果是实时交易,我们将向您的实时Webhook URL发送,反之亦然。

  • 如果使用 .htaccess,请记住在您设置的URL末尾添加尾随的/。
  • 对您的URL进行测试POST,并确保脚本获取POST正文。
  • 公开可用的URL(https:// 无法接收!)
    // Retrieve the request's body and parse it as JSON
    $event = Yabacon\Paystack\Event::capture();
    http_response_code(200);

    /* It is a important to log all events received. Add code *
     * here to log the signature and body to db or file       */
    openlog('MyPaystackEvents', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR);
    syslog(LOG_INFO, $event->raw);
    closelog();

    /* Verify that the signature matches one of your keys*/
    $my_keys = [
                'live'=>'sk_live_blah',
                'test'=>'sk_test_blah',
              ];
    $owner = $event->discoverOwner($my_keys);
    if(!$owner){
        // None of the keys matched the event's signature
        die();
    }

    // Do something with $event->obj
    // Give value to your customer but don't give any output
    // Remember that this is a call from Paystack's servers and
    // Your customer is not seeing the response here at all
    switch($event->obj->event){
        // charge.success
        case 'charge.success':
            if('success' === $event->obj->data->status){
                // TIP: you may still verify the transaction
                // via an API call before giving value.
            }
            break;
    }

4. 验证交易

在我们重定向到您的回调URL后,请在付款之前验证交易。

    $reference = isset($_GET['reference']) ? $_GET['reference'] : '';
    if(!$reference){
      die('No reference supplied');
    }

    // initiate the Library's Paystack Object
    $paystack = new Yabacon\Paystack(SECRET_KEY);
    try
    {
      // verify using the library
      $tranx = $paystack->transaction->verify([
        'reference'=>$reference, // unique to transactions
      ]);
    } catch(\Yabacon\Paystack\Exception\ApiException $e){
      print_r($e->getResponseObject());
      die($e->getMessage());
    }

    if ('success' === $tranx->data->status) {
      // transaction was successful...
      // please check other things like whether you already gave value for this ref
      // if the email matches the customer who owns the product etc
      // Give value
    }

5. 结束说明

通常,在构建Paystack对象后进行API请求,可以这样调用资源/方法:$paystack->{resource}->{method}();对于GET操作,使用$paystack->{resource}(id),要列出资源,使用$paystack->{resource}s()

目前,我们支持:'customer'、'page'、'plan'、'subscription'、'transaction'和'subaccount'。查看我们的API参考(link-paystack-api-reference),了解支持的函数。要指定参数,发送一个数组。

查看SAMPLES获取更多示例调用。

附加功能

有一些类可以帮助开发者完成在Paystack上经常需要完成的任务。

费用

该类用于处理金额和Paystack费用。要使用,创建一个新的Fee对象。

    $fee = new Yabacon\Paystack\Fee();

配置它

    $fee->withPercentage(0.015);        // 1.5%
    $fee->withAdditionalCharge(10000);  // plus 100 NGN
    $fee->withThreshold(250000);        // when total is above 2,500 NGN
    $fee->withCap(200000);              // capped at 2000

计算费用

    $chargeOn300naira = $fee->calculateFor(30000);
    $chargeOn7000naira = $fee->calculateFor(700000);

要知道在您想结算特定金额时向API发送什么信息。

    $iWant100Naira = $fee->addFor(10000);
    $iWant4000Naira = $fee->addFor(400000);

事件

该类可以帮助您捕获和我们的事件。

    $event = Yabacon\Paystack\Event::capture();

通过密钥验证它

    if($event->validFor($mySecretKey))
    {
        // awesome
    }

发现拥有它的密钥(如果同一个webhook接收了多个集成)。这在多租户系统中可能很有用。或者,如果您想使用相同的测试和实时webhook URL。

    $my_keys = [
                'live'=>'sk_live_blah',
                'test'=>'sk_test_blah',
              ];
    $owner = $event->discoverOwner($my_keys);
    if(!$owner){
        // None of my keys matched the event's signature
        die();
    }

将事件转发到另一个URL。如果您想通知其他系统有关相同的事件。

    $evt->forwardTo('http://another-webhook.url');

MetadataBuilder

该类可以帮助您构建在发起交易请求时要发送的有效JSON元数据字符串。

    $builder = new MetadataBuilder();

添加元数据

通过调用withKeyName魔法函数添加元数据(这些将在仪表板上显示)。不要使用CustomFields作为键名。

    $builder->withQuoteId(10); // will add as quote_id: 10 unless you turn auto_snake_case off
    $builder->withMobileNumber(08012345678); // will add as mobile_number: 08012345678
    $builder->withCSRF('dontacceptpaymentunlessthismatches');

要关闭键名的自动蛇形命名,执行以下操作:

    MetadataBuilder::$auto_snake_case = false;

在开始向$builder添加元数据之前。

添加自定义字段

通过调用withCustomField函数添加自定义字段(这些将在仪表板上显示)。

    $builder->withCustomField('Mobile Number', '080123456789');
    $builder->withCustomField('See Me', 'I\'m Visible on your Dashboard');

构建JSON

最后,调用build()以获取您的JSON元数据字符串。

变更日志

请参阅CHANGELOG以获取最近更改的更多信息。

测试

    $ composer test

贡献

请参阅CONTRIBUTINGCONDUCT以获取详细信息。查看我们的待办事项列表以了解已计划的功能。

安全性

如果您发现任何与安全相关的问题,请通过电子邮件yabacon.valley@gmail.com联系,而不是使用问题跟踪器。

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件