PHPackages                             ratapay/ratapayphp - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. ratapay/ratapayphp

ActiveLibrary[Payment Processing](/categories/payments)

ratapay/ratapayphp
==================

Ratapay PHP Integration

v1.0.16(3y ago)13524MITPHPPHP &gt;=7.2.0CI failing

Since Jan 16Pushed 3y ago1 watchersCompare

[ Source](https://github.com/Ratapay/ratapayphp)[ Packagist](https://packagist.org/packages/ratapay/ratapayphp)[ Docs](https://github.com/ratapay/ratapay-php)[ RSS](/packages/ratapay-ratapayphp/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (2)Versions (19)Used By (0)

Ratapay PHP Library
===================

[](#ratapay-php-library)

A simple library to integrate laravel with your PHP Code. Be aware that this library is in the very early stage of development, only the most fundamental features available and no thorough test has been carried out to ensure reliable functionality.

Install
-------

[](#install)

Via Composer

```
$ composer require ratapay/ratapayphp
```

Then require the autoload in your project

```
require_once "vendor/autoload.php";
```

The above require usually not necessary when using a framework such as Laravel. As the framework already has their package loader in place.

Usage
-----

[](#usage)

### **1. Keys and Secrets**

[](#1-keys-and-secrets)

Before you can use this library, you need to have a Ratapay account with at least Personal level Account.

The Keys and Secrets can be obtained from the account page -&gt; profile -&gt; view credentials menu

### **2. Invoice**

[](#2-invoice)

Invoice is the primary requirement to create transaction in Ratapay. The transaction will be created with just the invoice being defined.

Instantiated with

```
$invoice = new \ratapay\ratapayphp\Invoice($data);
```

where `$data` is an array with key value format containing the data defined in the properties below

**Properties**

PropertytypeRequiredLengthDefaultNotenoteStringY255 CharNullGeneral note of the invoiceemailStringY64 CharNullPayer email addressinvoice\_idStringY25 CharNullMerchant invoice IDamountIntegerY8 BytesNullPayment amountnameStringN64 CharNullPayer namepaysystemStringN16 CharNullPayment System ID which will be used for this invoicesecond\_amountIntegerN8 Bytes0Total amount of each recurring paymentfirst\_periodStringN4 CharNullPeriod between the initial payment with the first recurring paymentsecond\_periodStringN4 CharNullPeriod between each recurring paymentrebill\_timesIntegerN4 Bytes0How many recurring payment will occurrefundableBooleanN1 ByteFalseIs the invoice will be refundablerefund\_thresholdStringN4 CharNullHow long will the invoice be refundable after successful paymenturl\_callbackStringN255 CharNullMerchant URL where Ratapay will send notification data about the invoice activityurl\_successStringN255 CharNullURL where user will be redirected after succesful paymenturl\_failedStringN255 CharNullURL where user will ber redirected if the payment failed or cancelledexpired\_timeStringN32 CharNullTime the invoice expired in iso 8601 format, e.g. 2022-01-01T10:00:00+07:00The first\_period, second\_period, and refund\_threshold use a period format defined as:

\[1-9\]\[D/M/Y\]

where the first part is the nominator and the second part is the unit in either day (D), month (M), or Year (Y)

for example a 7 day period would be 7D

To see the list of available Payment System ID (paysystem) send a GET request to  for production or  for sandbox

**Method**

MethodParameterReturnNoteaddItemItem ObjectBooleanAdd Item to InvoiceaddItemsArrayBooleanAdd Multiple Items at once to the Invoice, each item data must conform to Invoice data requirementsclearItemNoneBooleanClear Invoice itemsaddBeneficiaryBeneficiary ObjectBooleanAdd Beneficiary to InvoiceaddBeneficiariesArrayBooleanAdd Multiple Benficiaries at once to the Invoice, each beneficiary data must conform to Beneficiary data requirementsclearBeneficiaryNoneBooleanClear Invoice beneficiariesgetAmountStringIntegerGet Invoice amount, use 'first' as parameter for amount and 'second' for second\_amountgetBeneficiariesNoneArray of Beneficiary ObjectGet all Invoice beneficiariesgetItemsNoneArray of Item ObjectGet all Invoice itemspayloadNoneArray of Mixed DataGenerate array formatted Invoice data that will be submitted### **3. Item**

[](#3-item)

Item defines the content of the invoice in more detail.

Instantiated with

```
$item = new \ratapay\ratapayphp\Item($data);
```

where `$data` is an array with key value format containing the data defined in the properties below

**Properties**

PropertyTypeRequiredLengthDefaultNoteidStringY32 CharNullID of the item in merchant systemqtyIntegerY4 Bytes1Item quantity in the invoicesubtotalIntegerY8 BytesNullSubtotal amount of the item with all the qtynameStringY128 CharNullItem NametypeStringN64 CharNullItem TypecategoryStringN64 CharNullItem CategorybrandStringN64 CharNullItem BrandrefundableBooleanN1 BytefalseIs Item Refundablerefund\_thresholdStringN4 CharNullItem Refund Period### **4. Beneficiary**

[](#4-beneficiary)

Beneficiary defines who will get the share from the invoice transaction.

Instantiated with

```
$beneficiary = new \ratapay\ratapayphp\Beneficiary($data);
```

where `$data` is an array with key value format containing the data defined in the properties below

**Properties**

PropertyTypeRequiredLengthDefaultNoteemailStringY64 CharNullBeneficary EmailnameStringY64 CharNullBeneficary NameusernameStringN64 CharNullBeneficary Username in merchant systemshare\_amountIntegerY8 BytesNullBeneficary share on paymentrebill\_share\_amountIntegerN8 BytesNullBeneficary share on recurring paymentshare\_item\_idIntegerConditional4 BytesNullitem\_id related to this share, required if item is defined in invoice### **5. Client**

[](#5-client)

Client will process the request to Ratapay

Instantiated with

```
$client = new \ratapay\ratapayphp\Client($merchant_id, $merchant_secret, $api_key, $api_secret, $sandbox);
```

Data on each parameter except `$sandbox` can be obtained from point 1. Keys and Secrets.

Whereas the `$sandbox` is a flag to define wether to use sandbox mode or not, default is true.

#### **A. Creating Transaction**

[](#a-creating-transaction)

```
$result = $client->createTransaction($invoice);
```

Where `$invoice` is an invoice object which already been defined before

The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating transaction creation result status
2. `message` : an error message of the reason why the transaction creation failed, only available if status is failed
3. `payment_url` : url for the payment process for the payer, only available if status is success
4. `data` : array of string indicating which invoice that the transaction is based on, containing: invoice\_id, note, and ref as the reference number from Ratapay, only available if status is success

#### **B. Listing Transaction**

[](#b-listing-transaction)

```
$result = $client->listTransaction($reference = '', $invoice_id = '', $creation_time = [], $paid_time = [], $offset = 0, $limit = 5);
```

PropertyTypeRequiredDefaultNotereferenceStringN''Transaction reference codeinvoice\_idStringN''Merchant Invoice IDcreation\_timeStringN\[\]range of transaction creation time in seconds \[start\_time, end\_time\] example \[1622540704, 1623663904\]paid\_timeIntegerN\[\]range of transaction paid time in seconds \[start\_time, end\_time\] example \[1622540704, 1623663904\]offsetIntegerN0listing offsetlimitIntegerN5listing limit, maximum 30The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating transaction listing result status
2. `list` : list of retrieved transaction data
3. `count` : total count of transaction records with specified conditions
4. `totalAmount` : total amount of transaction records retrieved

#### **C. Execute Split**

[](#c-execute-split)

Normally, the refundable invoice fund will be split automatically if it is already past the refund threshold. However, if there is need to split it earlier, this function can be used.

```
$result = $client->confirmSplit($reference, $item_ids = []);
```

PropertyTypeRequiredDefaultNotereferenceStringY''Transaction reference codeitem\_idsArrayN\[\]List of specific invoice item id to be splittedIf item\_ids is specified, only item matched item will be splitted.

#### **D. Extend Refund**

[](#d-extend-refund)

It can be used to extend the refund threshold.

```
$result = $client->extendRefund($reference, $period, $item_ids = []);
```

PropertyTypeRequiredDefaultNotereferenceStringY''Transaction reference codeperiodStringY''How long is the extension, format \[1-9\]\[D/M/Y\], e.g. 7Ditem\_idsArrayN\[\]List of specific invoice item id to extend its refund thresholdIf item\_ids is specified, only item matched item will have its refund threshold extended.

#### **E. Execute Refund**

[](#e-execute-refund)

It can be used to execute refund before refund threshold.

```
$result = $client->confirmRefund($reference, $params);
```

The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating refund request status

PropertyTypeRequiredDefaultNotereferenceStringY''Transaction reference codeparamsArrayNnullSpecify refund rulesIf doing full refund, the params is not used. But if doing partial refund, the params should be filled using these structures:

- params structure to refund partially for the whole invoice, use item ID 0

```
$params = [
        0 => [
            'type' => {% or $}
            'value' => {value}
        ]
]
```

- params structure to refund partially for each specific item

```
$params = [
        {item_id_1} => [
            'type' => {% or $} // optional, default $, will be ignored if specified but using qty
            'value' => {value}, // required if no qty specified
            'qty' => {qty} // required if no value specified
        ],
        {item_id_n} => [
            'type' => {% or $}, // optional, default $, will be ignored if specified but using qty
            'value' => {value}, // required if no qty specified
            'qty' => {qty} // required if no value specified
        ]
]
```

% means in percentage, maximum 100,

$ means in value, up to item subtotal value

#### **F. Getting Own Account Info**

[](#f-getting-own-account-info)

```
$result = $client->getAccount();
```

The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating account info fetching status
2. `account` : account info details

#### **G. Registering New Account**

[](#g-registering-new-account)

```
$result = $client->registerAccount(['email'=>$email,'name'=>$name,'password'=>$password]);
```

The `$result` will be an object which contain data as follow:

1. `status` : success or failed, failed means account with the email already exist
2. `account` : account info details if account creation status is success
3. `error` : short info about the error
4. `message` : long error message info

#### **H. Getting Another Account Info**

[](#h-getting-another-account-info)

```
$result = $client->getAccount(['email' => $email]);
```

The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating account info fetching status
2. `account` : account info details if request status is success
3. `error` : short info about the error
4. `message` : long error message info

If the `error` is 'none' or 'waiting' then you have to ask user consent to link their account to your merchant data by executing following method

```
$result = $client->linkAccount($email, $username);
```

`$username` is optional, it can be used to track the user if your system identify user by their username and the user change their email. The `$result` will be an object which contain data as follow:

1. `status` : success or failed, indicating account info fetching status
2. `link` : link to ratapay consent page to approve the linkage
3. `error` : short info about the error
4. `message` : long error message info

#### **I. Add New Beneficiaries**

[](#i-add-new-beneficiaries)

New beneficiaries can only be added to an existing invoice item. Hence, make sure to prepare item that have left over share amount or item specifically prepared for new beneficiaries.

```
$result = $client->addBeneficiaries($ref, $beneficiaries);
```

`$ref` is the transaction reference code

`$beneficiaries` is the list of new beneficiaries data to be added

The `$result` will be an object which contain data as follow:

1. `status` : success or failed

Sandbox
-------

[](#sandbox)

When using sandbox mode, the payment can be simulated by visiting [Sandbox Payment Simulation Page](https://dev.ratapay.co.id/simulate).

Enter the payment reference number then click pay to simulate the transaction payment.

The default payment method will use Ratapay balance, so if the tested account did not have balance in their account, the payment will fail. Hence, open the payment instruction first by visiting `payment_url` defined in transaction creation result, then choose the preferred payment method before attempting to simulate the payment.

Callback
--------

[](#callback)

Ratapay sends a POST callback on certain event which contains these data:

propertytypenotedataStringA json encoded data of the callbackhashStringHash of the dataTo verify the data againts the hash, use `hash_hmac` function with sha256 algo and merchant secret as the hash key.

example:

```
$valid = hash_equals($_POST['hash'], hash_hmac('sha256', $_POST['data'], $merchant_key));
```

The data contains following information

PropertyTypeNoteactionIntegerRefer to Action List below\*invoice\_idStringInvoice ID from merchant systempaysystemStringPayment channel used to pay the transactionamountIntegerAmount of paymentunique\_codeIntegerUnique code applied to paymentgateway\_chargeIntegerGateway charge applied to paymentmerchant\_idIntegerMerchant IDrefStringTransaction reference number### \*Action List

[](#action-list)

ActionEvent1Payment Success2-3-4Recurring Payment Failed5Recurring Payment Success6Refund Success7Split Fund SuccessTesting
-------

[](#testing)

```
$ phpunit
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/ratapay/ratapay-php/blob/master/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Ratapay](https://github.com/ratapay)
- [All Contributors](https://github.com/ratapay/ratapay-php/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 63% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Recently: every ~8 days

Total

18

Last Release

1282d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/38a46f5afc39615495d5be629cdc22599b0b204e6eb287e835d3cf1cd80248c5?d=identicon)[ratapay](/maintainers/ratapay)

---

Top Contributors

[![izzul02](https://avatars.githubusercontent.com/u/11586414?v=4)](https://github.com/izzul02 "izzul02 (29 commits)")[![izzul](https://avatars.githubusercontent.com/u/6128960?v=4)](https://github.com/izzul "izzul (17 commits)")

---

Tags

ratapayratapayphp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ratapay-ratapayphp/health.svg)

```
[![Health](https://phpackages.com/badges/ratapay-ratapayphp/health.svg)](https://phpackages.com/packages/ratapay-ratapayphp)
```

###  Alternatives

[chargebee/chargebee-php

ChargeBee API client implementation for PHP

768.0M9](/packages/chargebee-chargebee-php)[imdhemy/google-play-billing

Google Play Billing

491.3M5](/packages/imdhemy-google-play-billing)[bitpay/sdk

Complete version of the PHP library for the new cryptographically secure BitPay API

42337.5k4](/packages/bitpay-sdk)[buckaroo/sdk

Buckaroo payment SDK

12189.1k9](/packages/buckaroo-sdk)[contica/facturador-electronico-cr

Un facturador de código libre para integrar facturación electrónica en Costa Rica a un proyecto PHP

2128.8k](/packages/contica-facturador-electronico-cr)[karson/mpesa-php-sdk

172.2k](/packages/karson-mpesa-php-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
