Download the PHP package webimpian/bayarcash-php-sdk without Composer

On this page you can find all versions of the php package webimpian/bayarcash-php-sdk. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package bayarcash-php-sdk

Bayarcash Payment Gateway PHP SDK

Latest Stable Version Total Downloads Downloads (legacy) PHP Version Require License

The Bayarcash SDK provides an expressive interface for interacting with Bayarcash's Payment Gateway API. It supports both API v2 (default) and v3, with additional features available in v3.

Table of Contents

Requirements

Installation

Install via Composer:

Note: This package was previously published as webimpian/bayarcash-php-sdk. Existing installations using the old name continue to work, but new integrations should use bayarcash/php-sdk.

You will need two credentials from your Bayarcash console:

Getting Started

Plain PHP

Laravel

The service provider is auto-discovered. Add your credentials to .env:

Then resolve the SDK from the container:

To publish the config file:

Configuration

Call useSandbox() / setApiVersion() before making requests. Omit useSandbox() in production to hit the live gateway.

Quick Start: Accept a Payment

A complete FPX payment flow, from creating the payment to verifying the result:

After payment, Bayarcash calls your callback_url (server-to-server) and redirects the payer to your return_url. Verify both — see Handling Callbacks.

Payment Channels

Pass one of these constants (or an array of them) as payment_channel:

Payment Intents

Create a payment intent, then retrieve or cancel it later.

Request fields:

Field Required Description
portal_key ✅ Your portal key.
order_number ✅ Your reference. Max 30 chars.
amount ✅ String with up to 2 decimals, e.g. '10.00'. Range 1.00–30000.00 (min differs for some channels).
payer_name ✅ Max 150 chars.
payer_email ✅ Valid email, max 250 chars.
payment_channel ➖ A Bayarcash::* channel id, or an array of ids. If omitted, the payer chooses on the Bayarcash page.
payer_telephone_number ➖ Required for e-wallet / DuitNow channels. Max 20 chars.
return_url ➖ Where the payer's browser is redirected after payment.
callback_url ➖ Server-to-server notification URL.
metadata ➖ Any extra data you want echoed back.
checksum ➖ Recommended. See below.

Checksum

The checksum protects the request from tampering. Generate it after building the request and append it as checksum:

The checksum is computed from payment_channel, order_number, amount, payer_name, and payer_email.

Idempotency (v3)

Pass a unique key (UUID v4) as the second argument to make a create safe to retry — a timed-out request can be re-sent with the same key without creating a duplicate intent:

Keys are scoped per portal and expire after 24 hours.

Payer identity verification (v3)

For a single FPX (Bayarcash::FPX) or FPX B2B (Bayarcash::FPX_B2B) intent, set verify_identity and add the payer's bank account number (fpx_eaccount_number) and ID — NRIC, passport, or business registration number (fpx_ebuyer_id):

The result comes back on the transaction as payerIdentityVerified (true/false/null) and fpxExtraInfo (account_type, account_number_verified, buyer_id_verified).

Retrieve or cancel (v3)

Handling Callbacks

Bayarcash sends two kinds of notification. Always verify them with your API secret key before trusting the data.

Notification How it arrives Read it from
callback_url (transaction) Server-to-server POST (form-encoded) $_POST / $request->all()
return_url (payer redirect) Browser redirect — POST on v2, GET query on v3 $_POST / $_GET / $request->all()

Each verifier returns true only when the checksum matches. See FPX Direct Debit for mandate-specific callback verifiers.

Payment & Transaction Status

Transaction status is an integer code. Use the Fpx helper instead of hardcoding numbers:

A validate_only save-card (see Recurring Payments) succeeds with status 6 (Fpx::STATUS_AUTHORIZED) in its callback, not 3: the card is authorized and saved, no money moves.

Transactions

The following query helpers require API v3 and throw an exception on v2:

DuitNow QR

Render a DuitNow QR on your own page instead of redirecting the payer to Bayarcash. Requires a single DuitNow QR channel and API v3.

1. Generate the QR while creating the intent (one step):

2. Poll the payment status while the payer scans:

3. Regenerate a fresh QR for an existing intent (e.g. after the previous one expired):

Both $intent->duitnowQr and regenerateDuitNowQr() return a DuitNowQrResource:

Property Description
qrImage PNG data URI — drop straight into an <img>.
qrString Raw QR payload, if you render it yourself.
qrExpiresAt When the QR expires.
transactionId Use it to poll the status.
pollUrl Full status URL, if you prefer to poll it directly.

Webhooks to your callback_url are the primary notification path — polling is only a fallback. Respect next_poll_after_ms between polls and stop once the QR expires.

FPX Direct Debit

FPX Direct Debit lets you set up a recurring mandate and later maintain or terminate it. Constants live on the FpxDirectDebit class:

1. Enrolment

2. Maintenance

Update an existing mandate (identified by its mandate id):

3. Termination

Retrieving mandates & verifying mandate callbacks

Manual Bank Transfer

Submit a manual (offline) bank transfer with proof of payment:

Update the status of an existing transfer:

Portals & FPX Banks

Error Handling

Failed API calls throw typed exceptions. Catch them to handle errors gracefully:

Exception HTTP Meaning
ValidationException 422 Invalid data. Call ->errors() for details.
FailedActionException 400 Request failed. ->getMessage() has the reason.
NotFoundException 404 Resource not found.
RateLimitExceededException 429 Rate limited. ->rateLimitResetsAt holds the reset time.
ApiErrorException any other (401, 403, 409, 5xx, ...) ->getMessage() / ->body() is the raw body, ->status() / ->getCode() the HTTP status, ->errors() the decoded JSON (or []), ->errorCode() the error.code (or null). Extends \Exception.
TimeoutException — Thrown by the optional retry() helper after a timeout.

Response Objects

API methods return typed resource objects. Common properties:

PaymentIntentResource (from createPaymentIntent / getPaymentIntent)

TransactionResource (from getTransaction / transaction queries)

Any missing field is null. Convert a resource (including nested resources) to an array:

Recurring Payments (V3 API only)

Requires $bayarcash->setApiVersion('v3'). A subscription or installment is created at the provider, pending, and comes back with redirectUrl — the provider's card page. Redirect the buyer there: the agreement is active once they complete it and the first charge is taken at that moment. An on-demand payment charges the saved card synchronously and returns the charge. Your checkout holds the recurring consent (there is no Bayarcash page); the card processor reviews every merchant before switching recurring on (403 until then).

Ids: customers rcus_, plans rpln_, subscriptions rsub_, installments rins_, charges trx_.

Creating a subscription, an installment or an on-demand charge requires your own reference (up to 36 of A-Z a-z 0-9 _ -, unique per merchant per type, forever, case-insensitive: INV-1 and inv-1 are the same reference). A reference already on file — any body, any state — throws ValidationException (422 reference_already_used, "The reference X already exists."); the record on file is never returned. Do not repeat a create to learn its outcome: read it. A first call the provider did not settle in time answers 202: an agreement as itself, pending, without redirectUrl; an on-demand charge with no charge record yet, only reference and status the string pending (id is null).

Every recurring call waits 90 seconds, saveCard() 120 (or your setTimeout() when larger; the one-off calls keep setTimeout(), 30 by default), so your own PHP and proxy limits must allow 90 seconds (120 for saveCard()). A create can still take longer: an on-demand charge with customer_id about 90 seconds, a create with an inline customer up to 227 seconds (on-demand) or 182 seconds (subscription, installment). A timeout or a transport error on a create is the same as a 202: the record may already exist and an on-demand card may already have been charged. Then:

  • Subscription / installment: getSubscription($id) / getInstallment($id) with the 202's id, or getSubscriptions(['reference' => ...]) / getInstallments(['reference' => ...]) when no answer arrived at all. While it reads pending it carries redirectUrl; the card page lives 20 minutes from createdAt. After that an installment needs a new create (with a new reference); a subscription must be canceled first (cancelSubscription()), or left until it reads expired (about 30 minutes after creation) — see "one subscription per customer per plan".
  • On-demand charge: getAllTransactions(['order_number' => $reference, 'recurring_type' => 'on_demand']) (data holds TransactionResource) once it is booked, or the charge callback. After a 202 the card may already have been charged. Wait for the callback or read the charge BEFORE ever charging again under a new reference — otherwise the customer can be charged twice. Right after the 202 an empty answer is not yet proof: Bayarcash's background check first asks about the charge 15 minutes after it was recorded, then every 5 minutes, so it is usually booked within about 20 minutes; it can take longer while the exchange is unreachable or has not settled the charge. Rely on the callback: charge again under a new reference only once the callback says the charge failed, or that lookup still finds nothing well after that.

A 401, 403 or 429, or a 502 whose body's error.code is upstream_auth, on a create is not a 202: nothing was created and no card was charged. Send it again under a new reference. After a 429, wait a short while first: the SDK does not expose Retry-After, and ->rateLimitResetsAt is set only when the API sends X-RateLimit-Reset (null otherwise). A 429 throws RateLimitExceededException; a 401, 403, 409 or 5xx throws ApiErrorException (an \Exception) whose message is the API's body, with ->status() and ->errorCode() (error.code, e.g. upstream_auth).

A 409 upstream_conflict on a create is not a 202 either: the provider refused it for the current state and nothing was created; on an update, re-read the record before trying again. Any other 5xx on a create, including a 504 page from a proxy, is the same as a timeout: read the outcome as above.

One subscription per customer per plan: while the customer holds one to the plan that has not ended (pending — including one still being created — active or paused), a new createSubscription() for the same customer and plan throws ValidationException (422 customer_already_subscribed, "The customer is already subscribed to this plan."), as the provider itself refuses it. Cancel the existing one first; one still being created must settle first. Installments have no plan and are not affected.

None of these send an Idempotency-Key, and neither do customers, plans or saved cards. A customer email you already hold is a 422 customer_email_exists: find it with getCustomers(['search' => $email]); when that finds none, the email is held at the provider outside your records — contact support. A plan requires your own code (the same rule as reference: PLAN-1 and plan-1 are the same code); a code already on file is a 422 plan_code_already_used, and getPlans(['code' => ...]) finds the plan. Every saveCard() call makes a new card link: creating one charges nothing, but every link is payable, so with capture two paid links are two sales. After a timeout, look the intent up with getPaymentIntent() if you have its id, or create a new one and send the payer only the newest link.

Status constants: Recurring::STATUS_PENDING|STATUS_ACTIVE|STATUS_PAUSED|STATUS_CANCELED|STATUS_EXPIRED|STATUS_TERMINATED|STATUS_FAILED|STATUS_COMPLETED (American spelling canceled). failed is an enrolment whose card was declined on the card page; expired one nobody completed within 30 minutes of creation; completed is for installments only - every instalment collected (a subscription ends as canceled or terminated). Recurring::isTerminalStatus() is true for canceled, expired, terminated, failed and completed; getStatusText() labels each. Charge statuses use the transaction codes in Fpx::STATUS_*.

Recurring webhook

There is one: the charge callback, record_type recurring_charge, form-encoded on the callback_url given at enrolment (or on the on-demand payment), signed with your API secret key (ksort, implode('|'), HMAC-SHA256). It is sent for every charge — subscription, installment, on-demand, the first charge of an enrolment included — on every change of its status: pending (1), then successful (3) or failed (2). The first charge callback is the activation signal; it can land before or after the buyer reaches your return_url. A declined first charge arrives as a failed charge callback and the agreement then reads failed. There is no agreement lifecycle webhook: a pause, a cancel, an expired agreement are read with getSubscription() / getInstallment().

Signed fields: the 13 transaction-callback fields (record_type, transaction_id, exchange_reference_number, exchange_transaction_id, order_number, currency, amount, payer_name, payer_email, payer_bank_name, status, status_description, datetime) plus charge_source, subscription_id, installment_id, customer_id and the card the charge ran on: card_brand, card_country, card_last4, card_exp_month, card_exp_year (never a token; absent when the provider named no card). payer_telephone_number and payment_gateway_id are sent but not signed. Form encoding drops null fields while the checksum signs them as ''; the verifier rebuilds the fixed field list, so pass the request body as you received it.

Security Recommendations

  1. Always send a checksum with payment and mandate requests.
  2. Verify every callback with the provided verification methods before acting on it.
  3. Store and check transaction ids to prevent duplicate processing.
  4. Use HTTPS for your return_url and callback_url.
  5. Keep your API token and secret key out of source control.

API Documentation

For full API details, see the Official Bayarcash API Documentation.

Support

For support questions, contact Bayarcash support or open an issue in this repository.

Changelog

See CHANGELOG.md for the version history.

License

Open-sourced software licensed under the MIT license.


All versions of bayarcash-php-sdk with dependencies

PHP Build Version
Package Version
Requires guzzlehttp/guzzle Version ^7.0|^8.0
php Version ^7.4|^8.0
ext-json Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package webimpian/bayarcash-php-sdk contains the following files

Loading the files please wait ...