PHPackages                             carllee1983/tappay-payment-backend - 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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. carllee1983/tappay-payment-backend

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

carllee1983/tappay-payment-backend
==================================

Type-safe PHP 8.1+ library for TapPay Backend Payment APIs. Supports Pay by Prime, Pay by Token, Refund, and Record Query with injectable HTTP client for easy testing.

v1.1.0(4mo ago)01[1 PRs](https://github.com/CarlLee1983/tappay-payment-backend-php/pulls)MITPHPPHP ^8.1CI passing

Since Dec 14Pushed 4mo agoCompare

[ Source](https://github.com/CarlLee1983/tappay-payment-backend-php)[ Packagist](https://packagist.org/packages/carllee1983/tappay-payment-backend)[ Docs](https://github.com/CarlLee1983/tappay-payment-backend-php)[ GitHub Sponsors](https://github.com/sponsors/CarlLee1983)[ RSS](/packages/carllee1983-tappay-payment-backend/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (4)Used By (0)

TapPay Payment PHP Client
=========================

[](#tappay-payment-php-client)

[![CI](https://github.com/CarlLee1983/tappay-backend-payment-php/actions/workflows/ci.yml/badge.svg)](https://github.com/CarlLee1983/tappay-backend-payment-php/actions/workflows/ci.yml)[![PHP Version](https://camo.githubusercontent.com/04744bae0a61d2ffe29c26f07a9612eae20445fc6feaeb77b3af1f0e9be6447c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d3838393242462e737667)](https://www.php.net/)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

[繁體中文](./README_ZH.md) | English

A type-safe, PSR-4 compliant PHP library for TapPay Backend Payment APIs. Supports Pay by Prime, Pay by Token, Refund, and Record Query operations with injectable HTTP client for easy testing.

Features
--------

[](#features)

- 🚀 **PHP 8.1+** with strict types and readonly properties
- 📦 **PSR-4 Autoloading** with `TapPay\Payment` namespace
- 🔌 **Injectable HTTP Client** for easy mocking and testing
- ✅ **Type-safe DTOs** for requests and responses
- 🛡️ **Comprehensive Error Handling** with custom exceptions
- 📝 **Full PHPDoc Documentation** for IDE support

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- ext-json
- (Optional) ext-curl for `CurlHttpClient`

Installation
------------

[](#installation)

```
composer require carllee1983/tappay-payment-backend
```

Quick Start
-----------

[](#quick-start)

### Basic Configuration

[](#basic-configuration)

```
use TapPay\Payment\ClientConfig;
use TapPay\Payment\TapPayClient;

// Sandbox environment (default)
$client = new TapPayClient(new ClientConfig(
    partnerKey: getenv('TAPPAY_PARTNER_KEY'),
    merchantId: getenv('TAPPAY_MERCHANT_ID')
));

// Production environment
$client = new TapPayClient(new ClientConfig(
    partnerKey: getenv('TAPPAY_PARTNER_KEY'),
    merchantId: getenv('TAPPAY_MERCHANT_ID'),
    baseUri: 'https://prod.tappaysdk.com'
));
```

### Optional: Use Environment Enum

[](#optional-use-environment-enum)

```
use TapPay\Payment\ClientConfig;
use TapPay\Payment\Enum\TapPayEnvironment;

$config = ClientConfig::forEnvironment(
    TapPayEnvironment::Sandbox,
    partnerKey: getenv('TAPPAY_PARTNER_KEY'),
    merchantId: getenv('TAPPAY_MERCHANT_ID')
);
```

### Optional: Use cURL HTTP Client

[](#optional-use-curl-http-client)

```
use TapPay\Payment\ClientConfig;
use TapPay\Payment\TapPayClient;
use TapPay\Payment\Http\CurlHttpClient;

$client = new TapPayClient(
    new ClientConfig(
        partnerKey: getenv('TAPPAY_PARTNER_KEY'),
        merchantId: getenv('TAPPAY_MERCHANT_ID')
    ),
    new CurlHttpClient()
);
```

### Optional: Use PSR-18 HTTP Client

[](#optional-use-psr-18-http-client)

```
use TapPay\Payment\ClientConfig;
use TapPay\Payment\TapPayClient;
use TapPay\Payment\Http\Psr18HttpClientAdapter;

// Requires PSR-18 + PSR-17 + a PSR-7 implementation, e.g.:
// composer require psr/http-client psr/http-factory nyholm/psr7

$psr18Client = /* \Psr\Http\Client\ClientInterface */;
$requestFactory = /* \Psr\Http\Message\RequestFactoryInterface */;
$streamFactory = /* \Psr\Http\Message\StreamFactoryInterface */;

$client = new TapPayClient(
    new ClientConfig(
        partnerKey: getenv('TAPPAY_PARTNER_KEY'),
        merchantId: getenv('TAPPAY_MERCHANT_ID')
    ),
    new Psr18HttpClientAdapter($psr18Client, $requestFactory, $streamFactory)
);
```

### Pay by Prime

[](#pay-by-prime)

Process a payment using a Prime token from the TapPay frontend SDK:

```
use TapPay\Payment\Dto\Money;
use TapPay\Payment\Dto\PrimePaymentRequest;

$response = $client->payByPrime(new PrimePaymentRequest(
    prime: 'prime_from_frontend',
    amount: 100,
    currency: 'TWD',
    details: 'Order #12345',
    orderNumber: 'ORDER-12345',
    cardholder: [
        'phone_number' => '+886912345678',
        'name' => 'Test User',
        'email' => 'test@example.com',
    ],
    remember: true  // Save card for future payments
));

if ($response->isSuccess()) {
    // Save rec_trade_id for refunds or queries
    $recTradeId = $response->recTradeId;

    // If remember=true, save card tokens for Pay by Token
    $cardKey = $response->cardSecret['card_key'] ?? null;
    $cardToken = $response->cardSecret['card_token'] ?? null;
}
```

Tip: for non-TWD currencies, pass a `Money` object to avoid manual conversion:

```
$response = $client->payByPrime(new PrimePaymentRequest(
    prime: 'prime_from_frontend',
    amount: Money::USD(10.99),
    details: 'Order #12345'
));
```

### Pay by Token

[](#pay-by-token)

Process a payment using saved card tokens:

```
use TapPay\Payment\Dto\TokenPaymentRequest;

$response = $client->payByToken(new TokenPaymentRequest(
    cardKey: $savedCardKey,
    cardToken: $savedCardToken,
    amount: 200,
    currency: 'TWD',
    details: 'Subscription renewal',
    orderNumber: 'SUB-12345'
));

if ($response->isSuccess()) {
    echo "Payment successful: " . $response->recTradeId;
}
```

### Refund

[](#refund)

Process a full or partial refund:

```
use TapPay\Payment\Dto\RefundRequest;

// Full refund
$response = $client->refund(new RefundRequest(
    recTradeId: $transactionId
));

// Partial refund
$response = $client->refund(new RefundRequest(
    recTradeId: $transactionId,
    amount: 50  // Refund 50 out of original amount
));

if ($response->isSuccess()) {
    echo "Refund successful: " . $response->refundId;
}
```

### Query Records

[](#query-records)

Query transaction records:

```
use TapPay\Payment\Dto\RecordQueryRequest;

$response = $client->queryRecords(new RecordQueryRequest(
    recordsPerPage: 50,
    page: 0,
    filters: [
        'time' => [
            'start_time' => strtotime('-30 days') * 1000,
            'end_time' => time() * 1000,
        ],
    ],
    orderBy: [
        'attribute' => 'time',
        'is_descending' => true,
    ]
));

foreach ($response->tradeRecords as $record) {
    echo $record['rec_trade_id'] . ': ' . $record['amount'] . "\n";
}
```

API Reference
-------------

[](#api-reference)

### TapPayClient

[](#tappayclient)

MethodDescription`payByPrime(PrimePaymentRequest $request)`Process payment using Prime token`payByToken(TokenPaymentRequest $request)`Process payment using saved card tokens`refund(RefundRequest $request)`Process full or partial refund`queryRecords(RecordQueryRequest $request)`Query transaction records### Request DTOs

[](#request-dtos)

#### PrimePaymentRequest

[](#primepaymentrequest)

PropertyTypeRequiredDescription`prime`stringYesPrime token from frontend`amount`int|MoneyYesPayment amount (if `Money` is used, `currency` is ignored)`currency`stringNoCurrency code (default: TWD)`details`stringNoTransaction description`orderNumber`stringNoMerchant order number`bankTransactionId`stringNoBank transaction ID`cardholder`arrayNoCardholder information`remember`boolNoSave card for future use`instalment`intNoInstalment period`delayCaptureInDays`intNoDays to delay capture`threeDomainSecure`boolNoEnable 3D Secure`resultUrl`arrayNo3D Secure result URLs#### TokenPaymentRequest

[](#tokenpaymentrequest)

PropertyTypeRequiredDescription`cardKey`stringYesCard key from previous payment`cardToken`stringYesCard token from previous payment`amount`int|MoneyYesPayment amount (if `Money` is used, `currency` is ignored)`currency`stringNoCurrency code (default: TWD)`details`stringNoTransaction description`orderNumber`stringNoMerchant order number`threeDomainSecure`boolNoEnable 3D Secure`resultUrl`arrayNo3D Secure result URLs### Exceptions

[](#exceptions)

ExceptionDescription`TapPayException`Base exception class`SignatureException`Invalid API key (401/403)`ValidationException`Input validation errors`HttpException`HTTP-level errorsError Handling
--------------

[](#error-handling)

```
use TapPay\Payment\Exception\SignatureException;
use TapPay\Payment\Exception\ValidationException;
use TapPay\Payment\Exception\HttpException;

try {
    $response = $client->payByPrime($request);
} catch (SignatureException $e) {
    // Invalid partner key
    error_log('API key error: ' . $e->getMessage());
} catch (ValidationException $e) {
    // Missing required fields
    error_log('Validation error: ' . $e->getMessage());
} catch (HttpException $e) {
    // TapPay service unavailable
    error_log('HTTP error: ' . $e->getMessage());
}
```

Testing
-------

[](#testing)

This library includes an injectable HTTP client interface for easy testing:

```
use TapPay\Payment\Http\HttpClientInterface;
use TapPay\Payment\Http\HttpResponse;

// Create a mock HTTP client
$mockClient = new class implements HttpClientInterface {
    public function request(
        string $method,
        string $url,
        array $headers = [],
        array $body = []
    ): HttpResponse {
        return new HttpResponse(200, json_encode([
            'status' => 0,
            'msg' => 'success',
            'rec_trade_id' => 'test_trade_id',
        ]));
    }
};

// Inject mock client for testing
$client = new TapPayClient($config, $mockClient);
```

HTTP Client Options
-------------------

[](#http-client-options)

- Default: `TapPay\Payment\Http\NativeHttpClient` (stream-based, no extra extensions)
- Optional: `TapPay\Payment\Http\CurlHttpClient` (requires `ext-curl`)
- Optional: `TapPay\Payment\Http\Psr18HttpClientAdapter` (requires PSR-18 + PSR-17 + PSR-7 implementation)

Running Tests
-------------

[](#running-tests)

```
composer install
composer test
```

Documentation
-------------

[](#documentation)

For a library-specific API overview, see [doc/API/README.md](./doc/API/README.md).

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

[](#contributing)

Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for details.

Security
--------

[](#security)

For security vulnerabilities, please see [SECURITY.md](./SECURITY.md).

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

Links
-----

[](#links)

- [TapPay Official Documentation](https://docs.tappaysdk.com/tutorial/zh/back.html)
- [GitHub Repository](https://github.com/CarlLee1983/tappay-backend-payment-php)
- [Packagist](https://packagist.org/packages/carllee1983/tappay-payment-backend)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance74

Regular maintenance activity

Popularity1

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.3% 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 ~0 days

Total

2

Last Release

149d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6cc3f5bb28af8b207b65843e86f3b3e9feb1efd05b8ba888e1fa223a370ab822?d=identicon)[Carl Lee](/maintainers/Carl%20Lee)

---

Top Contributors

[![CarlLee1983](https://avatars.githubusercontent.com/u/8252510?v=4)](https://github.com/CarlLee1983 "CarlLee1983 (10 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

paymentPSR-4e-commercepayment gatewayrefundTaiwanphp8credit-cardtappaypay-by-primepay-by-token

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/carllee1983-tappay-payment-backend/health.svg)

```
[![Health](https://phpackages.com/badges/carllee1983-tappay-payment-backend/health.svg)](https://phpackages.com/packages/carllee1983-tappay-payment-backend)
```

###  Alternatives

[mage2pro/stripe

Stripe integration with Magento 2

605.3k](/packages/mage2pro-stripe)[enupal/stripe

Allows customers sign up for recurring and one-time payments with Stripe, perfect for orders, donations, subscriptions, and events. Create simple payment forms in seconds easily without coding. For Craft CMS 3.x

3416.5k1](/packages/enupal-stripe)

PHPackages © 2026

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