### Hash Generation Examples
Source: https://payheredoc.theepankaja.website/llms.txt
Code examples in Node.js, Python, Java, and C# demonstrating how to generate the MD5 hash required for payment processing.
```APIDOC
### Node.js Example
```javascript
const crypto = require('crypto');
function generateHash(merchantId, orderId, amount, currency, merchantSecret) {
const hashedSecret = crypto.createHash('md5')
.update(merchantSecret)
.digest('hex')
.toUpperCase();
const amountFormatted = parseFloat(amount).toFixed(2);
const hash = crypto.createHash('md5')
.update(merchantId + orderId + amountFormatted + currency + hashedSecret)
.digest('hex')
.toUpperCase();
return hash;
}
```
### Python Example
```python
import hashlib
def generate_hash(merchant_id, order_id, amount, currency, merchant_secret):
hashed_secret = hashlib.md5(merchant_secret.encode()).hexdigest().upper()
amount_formatted = f"{float(amount):.2f}"
raw = merchant_id + order_id + amount_formatted + currency + hashed_secret
return hashlib.md5(raw.encode()).hexdigest().upper()
```
### Java Example
```java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
public static String generateHash(String merchantId, String orderId, double amount, String currency, String merchantSecret) {
DecimalFormat df = new DecimalFormat("0.00");
String amountFormatted = df.format(amount);
String hash = getMd5(merchantId + orderId + amountFormatted + currency + getMd5(merchantSecret));
return hash;
}
public static String getMd5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) hashtext = "0" + hashtext;
return hashtext.toUpperCase();
} catch (Exception e) { throw new RuntimeException(e); }
}
```
### C# Example
```csharp
using System.Security.Cryptography;
using System.Text;
static string GenerateHash(string merchantId, string merchantSecret, string orderId, double amount, string currency) {
string hashedSecret = ComputeMD5(merchantSecret);
string amountFormatted = amount.ToString("####0.00");
return ComputeMD5(merchantId + orderId + amountFormatted + currency + hashedSecret);
}
static string ComputeMD5(string s) {
StringBuilder sb = new StringBuilder();
using (MD5 md5 = MD5.Create()) {
byte[] hashValue = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
foreach (byte b in hashValue) sb.Append($"{b:X2}");
}
return sb.ToString();
}
```
```
--------------------------------
### Install React Native PayHere SDK
Source: https://payheredoc.theepankaja.website/llms.txt
Commands to install the PayHere React Native SDK and link it to your project. This is the initial step for integrating PayHere payments into a React Native application.
```bash
npm install @payhere/payhere-mobilesdk-reactnative
react-native link @payhere/payhere-mobilesdk-reactnative
```
--------------------------------
### Configure Flutter Dependencies and Platform Setup
Source: https://payheredoc.theepankaja.website/llms.txt
Configuration steps for integrating the PayHere SDK, including Gradle settings for Android and Podfile modifications for iOS.
```yaml
dependencies:
payhere_mobilesdk_flutter: ^3.2.2
```
```groovy
allprojects {
repositories {
mavenLocal()
maven { url 'https://jitpack.io' }
}
}
```
```ruby
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
```
--------------------------------
### Checkout API - HTML Form Example
Source: https://payheredoc.theepankaja.website/llms.txt
An example of an HTML form used to initiate a checkout process with PayHere. This form includes essential fields for payment processing.
```APIDOC
## POST /pay/checkout
### Description
This endpoint is used to initiate a one-time payment process. It typically involves submitting an HTML form with various payment and customer details.
### Method
POST
### Endpoint
`https://sandbox.payhere.lk/pay/checkout` (Sandbox)
`https://www.payhere.lk/pay/checkout` (Live)
### Parameters
#### Request Body (HTML Form Fields)
- **merchant_id** (string) - Required - Your PayHere merchant ID.
- **return_url** (string) - Required - URL to redirect the customer after payment.
- **cancel_url** (string) - Required - URL to redirect the customer if they cancel the payment.
- **notify_url** (string) - Required - URL to receive payment status notifications.
- **order_id** (string) - Required - Unique identifier for the order.
- **items** (string) - Required - Name of the item being purchased.
- **currency** (string) - Required - Currency code (e.g., LKR).
- **amount** (decimal) - Required - The total amount to be charged.
- **first_name** (string) - Optional - Customer's first name.
- **last_name** (string) - Optional - Customer's last name.
- **email** (string) - Optional - Customer's email address.
- **phone** (string) - Optional - Customer's phone number.
- **address** (string) - Optional - Customer's street address.
- **city** (string) - Optional - Customer's city.
- **country** (string) - Optional - Customer's country.
- **hash** (string) - Required - A security hash generated from the request parameters.
#### Optional Parameters
- **delivery_address** (string) - Delivery address.
- **delivery_city** (string) - Delivery city.
- **delivery_country** (string) - Delivery country.
- **custom_1** (string) - Custom field 1.
- **custom_2** (string) - Custom field 2.
- **platform** (string) - Platform identifier.
- **item_number_X** (string) - Item number for item X (1-indexed).
- **item_name_X** (string) - Item name for item X.
- **quantity_X** (int) - Quantity for item X.
- **amount_X** (decimal) - Unit amount for item X.
### Request Example
```html
```
### Response
#### Success Response (200)
Upon successful submission, the user is redirected to the PayHere payment gateway. The actual payment confirmation is received via the `notify_url`.
#### Response Example
(Redirection to PayHere gateway)
```
--------------------------------
### Configure PayHere Android SDK
Source: https://payheredoc.theepankaja.website/llms.txt
Covers the Gradle dependencies, repository configuration, and ActivityResultLauncher setup required to integrate PayHere into an Android application.
```groovy
implementation 'lk.payhere:android-sdk:4.0.18'
```
```xml
```
```java
ActivityResultLauncher launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
String paymentId = result.getData().getStringExtra("paymentId");
} else if (result.getResultCode() == Activity.RESULT_CANCELED) {
}
}
);
```
--------------------------------
### Integrate PayHere JavaScript SDK
Source: https://payheredoc.theepankaja.website/llms.txt
Provides the setup for the PayHere JS SDK to enable onsite payment popups. Includes event handlers and the payment object configuration, emphasizing that the hash must be generated server-side.
```html
```
```javascript
payhere.onCompleted = function onCompleted(orderId) {
console.log("Payment completed. OrderID:" + orderId);
};
payhere.onDismissed = function onDismissed() {
console.log("Payment dismissed");
};
payhere.onError = function onError(error) {
console.log("Error:" + error);
};
var payment = {
"sandbox": true,
"merchant_id": "121XXXX",
"return_url": undefined,
"cancel_url": undefined,
"notify_url": "http://sample.com/notify",
"order_id": "ItemNo12345",
"items": "Door bell wireless",
"amount": "1000.00",
"currency": "LKR",
"hash": "GENERATED_HASH_FROM_BACKEND",
"first_name": "Saman",
"last_name": "Perera",
"email": "samanp@gmail.com",
"phone": "0771234567",
"address": "No.1, Galle Road",
"city": "Colombo",
"country": "Sri Lanka"
};
payhere.startPayment(payment);
```
--------------------------------
### Troubleshoot CocoaPods Spec Repo Errors
Source: https://payheredoc.theepankaja.website/llms.txt
A command-line sequence to resolve issues with CocoaPods spec repositories, typically used when encountering errors during pod installation or updates. It involves removing the master repo, setting it up again, and then installing pods.
```bash
pod repo remove master
pod setup
pod install
```
--------------------------------
### Configure iOS Podfile for PayHere SDK
Source: https://payheredoc.theepankaja.website/llms.txt
Modifies the `Podfile` in your iOS project to include the PayHere SDK and its dependencies. This setup ensures that the necessary libraries are correctly linked for the React Native application on iOS.
```ruby
platform :ios, '11.0'
use_react_native!(:path => config["reactNativePath"])
pod 'payHereSDK', :git => 'https://github.com/PayHereLK/payhere-mobilesdk-ios.git'
pod 'payhere-mobilesdk-reactnative', :path => '../node_modules/@payhere/payhere-mobilesdk-reactnative'
use_frameworks!
pod 'SDWebImage', :modular_headers => true
```
--------------------------------
### HTML Form for PayHere Checkout
Source: https://payheredoc.theepankaja.website/llms.txt
An example HTML form demonstrating how to submit payment details to PayHere's checkout endpoint. It includes hidden input fields for essential transaction data and optional parameters.
```html
```
--------------------------------
### PayHere Refund Request Body (JSON)
Source: https://payheredoc.theepankaja.website/llms.txt
These JSON objects demonstrate the request body for the PayHere Refund API. One example shows refunding a payment by `payment_id`, and the other shows refunding an authorization hold using `authorization_token`.
```json
{
"payment_id": "320027150501",
"description": "Item is out of stock"
}
```
```json
{
"authorization_token": "74d7f304-7f9d-481d-b47f-6c9cad32d3d5",
"description": "Customer cancelled order"
}
```
--------------------------------
### Configure Item-Wise Details in React Native (v3.0.0+)
Source: https://payheredoc.theepankaja.website/llms.txt
Illustrates how to provide item-specific details for payments in the PayHere React Native SDK, starting from version 3.0.0. This feature supports one-time, subscription, and authorization payments, but not preapproval. It requires defining parameters like `item_number`, `item_name`, `amount`, and `quantity` for each item.
```javascript
"item_number_1": "001",
"item_name_1": "Test Item #1",
"amount_1": "15.00",
"quantity_1": "2",
"item_number_2": "002",
"item_name_2": "Test Item #2",
"amount_2": "20.00",
"quantity_2": "1"
```
--------------------------------
### Configure Preapproval/Tokenization (Swift)
Source: https://payheredoc.theepankaja.website/llms.txt
Explains how to set up preapproval or tokenization for recurring payments in Swift. This involves creating a `PHInitialRequest` with minimal fields, which generates a `customer_token` for subsequent charges via the Charging API.
```swift
Create a PHInitialRequest with minimal fields (no amount required). The payment generates a `customer_token` for future charges via the Charging API.
```
--------------------------------
### Initiate One-Time Payment in React Native
Source: https://payheredoc.theepankaja.website/llms.txt
Demonstrates how to initiate a one-time payment using the PayHere React Native SDK. It defines a payment object with all necessary details and calls the `startPayment` function, providing callbacks for completion, failure, and dismissal.
```javascript
import PayHere from '@payhere/payhere-mobilesdk-reactnative';
const paymentObject = {
"sandbox": true,
"merchant_id": "1211149",
"notify_url": "http://sample.com/notify",
"order_id": "ItemNo12345",
"items": "Hello from React Native!",
"amount": "50.00",
"currency": "LKR",
"first_name": "Saman",
"last_name": "Perera",
"email": "samanp@gmail.com",
"phone": "0771234567",
"address": "No.1, Galle Road",
"city": "Colombo",
"country": "Sri Lanka",
"delivery_address": "No.2, Galle Road",
"delivery_city": "Colombo",
"delivery_country": "Sri Lanka",
"custom_1": "",
"custom_2": ""
};
PayHere.startPayment(
paymentObject,
(paymentId) => { console.log("Payment Completed", paymentId); },
(errorData) => { console.log("Payment Failed", errorData); },
() => { console.log("Payment Dismissed"); }
);
```
--------------------------------
### POST /payment/initiate
Source: https://payheredoc.theepankaja.website/llms.txt
Initializes a payment request using the PayHere SDK. Supports one-time payments, recurring subscriptions, preapprovals, and authorization holds.
```APIDOC
## POST /payment/initiate
### Description
Initiates a payment flow via the PayHere Mobile SDK. The request object encapsulates merchant details, customer information, and payment-specific parameters.
### Method
POST
### Parameters
#### Request Body
- **merchantID** (String) - Required - Merchant account identifier
- **orderID** (String) - Required - Unique order reference
- **currency** (Enum) - Required - Currency (e.g., LKR)
- **amount** (Double) - Conditional - Payment amount (not required for PreApproval)
- **itemsMap** (Array) - Required - Array of Item objects
- **firstName/lastName** (String) - Conditional - Customer name details
- **email/phone** (String) - Conditional - Customer contact details
- **notifyURL** (String) - Optional - Server notification endpoint
- **recurrence/duration** (Enum) - Optional - Subscription settings
- **isHoldOnCardEnabled** (Bool) - Optional - Authorization hold flag
### Request Example
{
"merchantID": "1210XXX",
"orderID": "230000123",
"amount": 1000.00,
"currency": "LKR",
"firstName": "Saman",
"lastName": "Perera"
}
### Response
#### Success Response (200)
- **status** (Int) - Payment status code
- **message** (String) - Status message
- **paymentNo** (String) - PayHere payment reference
#### Response Example
{
"status": 2,
"message": "Success",
"paymentNo": "123456789"
}
```
--------------------------------
### Configure Preapproval Payment (Android Java)
Source: https://payheredoc.theepankaja.website/llms.txt
Sets the `preapprove` flag to `true` on an `InitRequest` object to enable preapproval payments. This allows for future charges without requiring immediate customer action.
```java
req.setPreapprove(true);
```
--------------------------------
### Sandbox & Testing
Source: https://payheredoc.theepankaja.website/llms.txt
Information on how to utilize the PayHere sandbox environment for testing purposes, including accessing the sandbox portal, using test card numbers for successful and declined payments, and switching to sandbox mode in your code.
```APIDOC
## Sandbox & Testing
**Docs:** https://support.payhere.lk/sandbox-and-testing
### Sandbox Portal
- URL: https://sandbox.payhere.lk
- Create a separate sandbox account (not linked to live account)
- No real payments processed — all transactions are simulated
### Test Card Numbers (Successful Payments)
| Card Number | Type |
|---|---|
| `4916217501611292` | Visa |
| `5307732125531191` | Mastercard |
| `346781005510225` | Amex |
For "Name on Card", "CVV" & "Expiry date" — enter any valid data.
### Test Cards for Decline Scenarios
Any card number NOT in the list above will result in a failed payment in sandbox.
### Switching to Sandbox in Code
- Change API endpoint from `www.payhere.lk` to `sandbox.payhere.lk`
- Set `sandbox: true` in JS SDK / Mobile SDK payment objects
- For plugins: enable "Sandbox Mode" checkbox in plugin settings
```
--------------------------------
### Implement One-Time Payment
Source: https://payheredoc.theepankaja.website/llms.txt
Demonstrates how to construct a payment object and initiate a one-time transaction using the PayHere Flutter SDK.
```dart
import 'package:payhere_mobilesdk_flutter/payhere_mobilesdk_flutter.dart';
Map paymentObject = {
"sandbox": true,
"merchant_id": "1211149",
"merchant_secret": "xyz",
"notify_url": "http://sample.com/notify",
"order_id": "ItemNo12345",
"items": "Hello from Flutter!",
"amount": 50.00,
"currency": "LKR",
"first_name": "Saman",
"last_name": "Perera",
"email": "samanp@gmail.com",
"phone": "0771234567",
"address": "No.1, Galle Road",
"city": "Colombo",
"country": "Sri Lanka"
};
PayHere.startPayment(
paymentObject,
(paymentId) { print("One Time Payment Success. Payment Id: $paymentId"); },
(error) { print("One Time Payment Failed. Error: $error"); },
() { print("One Time Payment Dismissed"); },
);
```
--------------------------------
### Add PayHere iOS SDK via Swift Package Manager
Source: https://payheredoc.theepankaja.website/llms.txt
Instructions for adding the PayHere iOS SDK to an Xcode project using Swift Package Manager. This involves providing the GitHub repository URL and specifying the version.
```swift
dependencies: [
.package(url: "https://github.com/PayHereLK/payhere-mobilesdk-ios.git", from: "3.2.2")
]
```
--------------------------------
### Configure Android Build for PayHere SDK
Source: https://payheredoc.theepankaja.website/llms.txt
Adds the JitPack repository to your project's root `build.gradle` file, which is necessary for resolving dependencies for the PayHere React Native SDK on Android. It also shows how to add necessary namespaces and overrides to the `AndroidManifest.xml`.
```groovy
allprojects {
repositories {
mavenLocal()
maven { url 'https://jitpack.io' }
}
}
```
```xml
```
--------------------------------
### Initialize One-Time Payment (Android Java)
Source: https://payheredoc.theepankaja.website/llms.txt
Initializes a one-time payment request for Android using the PayHere SDK. This involves setting merchant details, customer information, order specifics, and notification URL. The request is then passed to the PayHere activity for processing.
```java
InitRequest req = new InitRequest();
req.setMerchantId("1210XXX");
req.setCurrency("LKR");
req.setAmount(1000.00);
req.setOrderId("230000123");
req.setItemsDescription("Door bell wireless");
req.setCustom1("Custom message 1");
req.setCustom2("Custom message 2");
req.getCustomer().setFirstName("Saman");
req.getCustomer().setLastName("Perera");
req.getCustomer().setEmail("samanp@gmail.com");
req.getCustomer().setPhone("+94771234567");
req.getCustomer().getAddress().setAddress("No.1, Galle Road");
req.getCustomer().getAddress().setCity("Colombo");
req.getCustomer().getAddress().setCountry("Sri Lanka");
req.setNotifyUrl("https://yourserver.com/notify");
Intent intent = new Intent(this, PHMainActivity.class);
intent.putExtra(PHConstants.INTENT_EXTRA_DATA, req);
launcher.launch(intent);
```
--------------------------------
### Initialize One-Time Payment (Swift)
Source: https://payheredoc.theepankaja.website/llms.txt
Initializes a one-time payment request for iOS using the PayHere SDK. This involves creating an `PHInitialRequest` object with all necessary payment details and then presenting the payment controller.
```swift
let item = Item(id: "item_1", name: "Item 1", quantity: 1, amount: 50.0)
let initRequest = PHInitialRequest(
merchantID: merchantID,
notifyURL: "https://yourserver.com/notify",
firstName: "Saman",
lastName: "Perera",
email: "samanp@gmail.com",
phone: "+9477123456",
address: "No.1, Galle Road",
city: "Colombo",
country: "Sri Lanka",
orderID: "001",
itemsDescription: "Greeting Card",
itemsMap: [item],
currency: .LKR,
amount: 50.00,
deliveryAddress: "",
deliveryCity: "",
deliveryCountry: "",
custom1: "",
custom2: ""
)
PHPrecentController.precent(
from: self,
isSandBoxEnabled: true,
withInitRequest: initRequest!,
delegate: self
);
```
--------------------------------
### Configure Recurring Payments in React Native
Source: https://payheredoc.theepankaja.website/llms.txt
Shows how to add fields to the payment object for setting up recurring payments with the PayHere React Native SDK. This includes specifying the recurrence interval, subscription duration, and an optional startup fee.
```javascript
"recurrence": "1 Month", // Billing frequency: "1 Month", "2 Week", "1 Year"
"duration": "1 Year", // Subscription duration or "Forever"
"startup_fee": "10.00" // Optional extra charge for first payment
```
--------------------------------
### Configure Recurring Payment (Swift)
Source: https://payheredoc.theepankaja.website/llms.txt
Provides guidance on setting recurrence parameters within the `PHInitialRequest` object for Swift. This includes specifying the recurrence interval, duration, and startup fee.
```swift
// Set recurrence: .Week, .Month, .Year
// Set duration: .Week, .Month, .Year, .Forever
// Set startupFee: initial charge amount
```
--------------------------------
### JavaScript SDK (payhere.js)
Source: https://payheredoc.theepankaja.website/llms.txt
Enables onsite payment processing via an iframe popup, eliminating the need for redirects. Requires HTTPS.
```APIDOC
## JavaScript SDK Integration
### Description
Provides an onsite checkout popup for web applications. The `hash` parameter must be generated server-side to ensure security.
### Setup
Include the script: ``
### Payment Object Fields
- **merchant_id** (string) - Required
- **order_id** (string) - Required
- **amount** (string) - Required
- **currency** (string) - Required
- **hash** (string) - Required (Server-side generated)
- **return_url** (undefined) - Required (Must be undefined for JS SDK)
- **cancel_url** (undefined) - Required (Must be undefined for JS SDK)
### Usage Example
```javascript
var payment = {
"sandbox": true,
"merchant_id": "121XXXX",
"order_id": "ItemNo12345",
"amount": "1000.00",
"currency": "LKR",
"hash": "GENERATED_HASH_FROM_BACKEND"
};
payhere.startPayment(payment);
```
```
--------------------------------
### Configure Authorize/Hold on Card (Android Java)
Source: https://payheredoc.theepankaja.website/llms.txt
Sets the `authorize` flag to `true` on an `InitRequest` object to enable authorization holds on the customer's card. This reserves funds without immediately charging them.
```java
req.setAuthorize(true);
```
--------------------------------
### Configure Recurring Payment (Android Java)
Source: https://payheredoc.theepankaja.website/llms.txt
Adds parameters to an existing `InitRequest` object to configure a recurring payment. This includes setting the recurrence interval, duration, and any applicable startup fee.
```java
req.setRecurrence("1 Month");
req.setDuration("Forever");
req.setStartupFee(0);
```
--------------------------------
### Add PayHere iOS SDK via CocoaPods
Source: https://payheredoc.theepankaja.website/llms.txt
Instructions for adding the PayHere iOS SDK to an Xcode project using CocoaPods. This involves specifying the pod source, minimum iOS version, and the 'payHereSDK' pod in the Podfile.
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '13.0'
use_frameworks!
target '' do
pod 'payHereSDK'
end
```
--------------------------------
### Initialize PayHere Payment Callback
Source: https://payheredoc.theepankaja.website/llms.txt
Defines the callback structure for handling payment outcomes. It includes handlers for successful completion, errors, and user dismissal.
```javascript
PayHere.startPayment(paymentObject, onCompleted, onError, onDismissed);
// onCompleted(paymentId: string) — called on successful payment with PayHere Payment ID
// onError(errorData: string) — called on payment failure with error message
// onDismissed() — called when user closes payment popup without completing
```
```dart
PayHere.startPayment(paymentObject, onCompleted, onError, onDismissed);
// onCompleted(paymentId: String) — called on successful payment
// onError(error: String) — called on payment failure
// onDismissed() — called when popup closed without completing
```
--------------------------------
### Preapproval API
Source: https://payheredoc.theepankaja.website/llms.txt
The Preapproval API is used to tokenize a customer's card details, allowing for future on-demand charges without requiring the customer to re-enter their information.
```APIDOC
## Preapproval API
### Purpose
Tokenize customer's card for future on-demand charges via Charging API.
### Form Action URLs
- Live: `https://www.payhere.lk/pay/preapprove`
- Sandbox: `https://sandbox.payhere.lk/pay/preapprove`
### Key Differences from Checkout
- The `amount` field can be set to `0` (or a minimum of `10.00` LKR / `1.01` for other currencies) for card validation purposes.
- The notification callback includes a `customer_token` which is an encrypted token to store securely for future charges.
### Notification Response Includes
- **customer_token** (string) - Encrypted token for the customer's card. Store this securely for use with the Charging API.
```
--------------------------------
### Charging API
Source: https://payheredoc.theepankaja.website/llms.txt
The Charging API enables merchants to charge a customer using a previously obtained `customer_token` from the Preapproval API. This is useful for automated or recurring billing scenarios.
```APIDOC
## POST /merchant/v1/payment/charge
### Description
Charge a customer using a `customer_token` obtained via the Preapproval API. This endpoint is used for automated charging, recurring billing, or charging a customer on demand after initial tokenization.
### Method
POST
### Endpoint
`https://www.payhere.lk/merchant/v1/payment/charge` (Live)
`https://sandbox.payhere.lk/merchant/v1/payment/charge` (Sandbox)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **merchant_id** (string) - Required - Your Merchant ID.
- **order_id** (string) - Required - Merchant-defined unique reference for this charge.
- **items** (string) - Required - Description of the item(s) being charged for.
- **currency** (string) - Required - The currency of the transaction (e.g., `LKR`, `USD`).
- **amount** (decimal) - Required - The amount to charge.
- **customer_token** (string) - Required - The token obtained from the Preapproval API for the customer's card.
- **notify_url** (string) - Optional - Server callback URL for payment status.
- **first_name** (string) - Optional - Customer's first name.
- **last_name** (string) - Optional - Customer's last name.
- **email** (string) - Optional - Customer's email.
- **phone** (string) - Optional - Customer's phone number.
### Request Example
```json
{
"merchant_id": "your_merchant_id",
"order_id": "CHARGE_ORDER_9876",
"items": "Monthly Subscription Fee",
"currency": "LKR",
"amount": "500.00",
"customer_token": "encrypted_customer_token_from_preapproval",
"notify_url": "https://yourdomain.com/charge_notify"
}
```
### Response
#### Success Response (200 OK)
- **payment_id** (string) - Unique PayHere payment identifier.
- **order_id** (string) - The merchant-defined order ID.
- **status_code** (string) - The status of the charge (`2` for success, `0` for pending, etc.).
#### Response Example
```json
{
"payment_id": "pay_12345abcde",
"order_id": "CHARGE_ORDER_9876",
"status_code": "2"
}
```
```
--------------------------------
### PayHere Links & Buttons
Source: https://payheredoc.theepankaja.website/llms.txt
Accept payments without a website using shareable payment links or embeddable payment buttons.
```APIDOC
## PayHere Links & Buttons
### Payment Links
Accept payments without a website using shareable payment links.
#### Creating a Payment Link
1. Log in to your PayHere Merchant Account.
2. Navigate to the "Payment Links" section.
3. Click "Create New Link".
4. Fill in the payment details: amount, currency, and description.
5. Click "Create" to generate the link.
#### Sharing Options
* Copy the generated URL and share via email, SMS, social media, or messaging apps.
* Each link can be for a fixed amount or a customer-entered amount.
* Links can be single-use or reusable.
### Payment Buttons
Embed a payment button on your website with minimal code — no API integration needed.
#### Button HTML Embedding
After creating a payment link in the dashboard, you can get an embeddable button:
```html
```
#### Use Cases
* Freelancers collecting payments via invoice links.
* Social media sellers without a website.
* Event ticket sales with shareable links.
* Donation collection for organizations.
* Simple one-off payments without full API integration.
```
--------------------------------
### Configure ProGuard Rules for Android
Source: https://payheredoc.theepankaja.website/llms.txt
Essential ProGuard rules to ensure the PayHere SDK functions correctly in Android release builds by preventing code obfuscation for required classes.
```proguard
-keepattributes Signature
-keepattributes *Annotation*
-keep interface retrofit2.** { *; }
-keep class retrofit2.** { *; }
-keep class okhttp3.** { *; }
-keep class okio.** { *; }
-keep class lk.payhere.** { *; }
-keep interface lk.payhere.androidsdk.PayhereSDK { *; }
-keep interface u2.c { *; }
-keep class lk.payhere.androidsdk.models.** { *; }
```
--------------------------------
### Recurring API
Source: https://payheredoc.theepankaja.website/llms.txt
This API allows for setting up recurring payments, enabling subscription-based services where customers are automatically charged at regular intervals.
```APIDOC
## Recurring Payments API
### Purpose
Accept recurring/subscription payments. Customer enters card once, auto-charged at set intervals.
### Form Action URLs
- Live: `https://www.payhere.lk/pay/checkout`
- Sandbox: `https://sandbox.payhere.lk/pay/checkout`
### Additional Required Parameters (on top of Checkout params)
- **recurrence** (string) - Required - Charging frequency (e.g., `1 Month`, `2 Week`, `6 Month`, `1 Year`). Word must be singular (`Week`, `Month`, `Year`).
- **duration** (string) - Required - How long to charge (e.g., `Forever`, `1 Year`, `3 Month`). Must be compatible with recurrence.
### Optional Recurring Parameters
- **startup_fee** (decimal) - Optional - Extra amount added/subtracted from the first charge (can be negative for a discount).
### Additional Notification Parameters for Recurring
- **recurring** (string) - `1` if recurring payment, `0` if one-time.
- **item_rec_status** (string) - Recurring status: `0`=active, `1`=completed, `-1`=cancelled, `-2`=failed, `-3`=pending retry.
- **item_rec_date_next** (string) - Next scheduled charge date.
- **item_rec_install_paid** (int) - Number of successful recurring installments charged.
```
--------------------------------
### Configure Preapproval (Tokenization) in React Native
Source: https://payheredoc.theepankaja.website/llms.txt
Details how to enable preapproval (tokenization) for payments using the PayHere React Native SDK. This involves setting the `preapprove` flag to `true` and specifying an authorization amount. Delivery fields are not required for preapproval payments.
```javascript
"preapprove": true,
"amount": "50.00" // Authorization amount
```
--------------------------------
### Payment Limits, Fees & Plans
Source: https://payheredoc.theepankaja.website/llms.txt
Information regarding PayHere's payment limits, associated fees, and available plans.
```APIDOC
## Payment Limits, Fees & Plans
**Docs:** https://support.payhere.lk/limits-and-fees
```
--------------------------------
### Define Item Model (Swift)
Source: https://payheredoc.theepankaja.website/llms.txt
Creates an `Item` object in Swift, which is used to represent products or services in a payment request. It requires an ID, name, quantity, and amount.
```swift
let item = Item(id: "item_1", name: "Item 1", quantity: 1, amount: 50.0)
```
--------------------------------
### Handle Payment Responses in Swift
Source: https://payheredoc.theepankaja.website/llms.txt
Implements the PHViewControllerDelegate protocol to handle success and error responses from the PayHere payment process in a Swift application. It checks for payment success and extracts data from the response, or handles payment failures.
```swift
extension ViewController: PHViewControllerDelegate {
func onErrorReceived(error: Error) {
// Handle payment errors
}
func onResponseReceived(response: PHResponse?) {
if response?.isSuccess() == true {
guard let resp = response?.getData() as? StatusResponse else { return }
// resp.status, resp.message, resp.paymentNo, resp.price
} else {
// Payment failed: response?.getMessage()
}
}
}
```
--------------------------------
### OAuth Authentication Flow
Source: https://payheredoc.theepankaja.website/llms.txt
Steps to authenticate with PayHere APIs using client credentials. Requires Base64 encoding of App ID and Secret to obtain a bearer token.
```http
POST https://www.payhere.lk/merchant/v1/oauth/token
Authorization: Basic
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
```
--------------------------------
### OAuth Authentication API
Source: https://payheredoc.theepankaja.website/llms.txt
This section details the process of obtaining and using OAuth bearer tokens for authenticating with PayHere Merchant APIs. It covers creating API keys, generating authorization codes, requesting access tokens, and including the access token in subsequent API requests.
```APIDOC
## OAuth Authentication (Merchant APIs)
The Charging, Retrieval, Subscription Manager, Refund, and Capture APIs all use OAuth Bearer tokens.
### Step 1: Create API Key
1. Sign in to PayHere > Settings > API Keys
2. Click "Create API Key"
3. Enter app name and comma-separated domains to whitelist
4. Copy the **App ID** and **App Secret**
### Step 2: Generate Authorization Code
Base64-encode your `App_ID:App_Secret`:
```
Base64Encode("4OVx33RVOPg4DzdZUzq4A94D2:8n4VCj25MXp4JLDFyvsE9h4a8qgbPaZUI4JEWK4FCvop")
```
### Step 3: Get Access Token
```
POST https://www.payhere.lk/merchant/v1/oauth/token (Live)
POST https://sandbox.payhere.lk/merchant/v1/oauth/token (Sandbox)
Headers:
Authorization: Basic
Content-Type: application/x-www-form-urlencoded
Body:
grant_type=client_credentials
```
Response:
```json
{
"access_token": "cb5c47fd-741c-489a-b69e-fd73155ca34e",
"token_type": "bearer",
"expires_in": 599,
"scope": "SANDBOX"
}
```
### Step 4: Use Access Token
Include in all subsequent API requests:
```
Authorization: Bearer cb5c47fd-741c-489a-b69e-fd73155ca34e
```
**Note:** Access tokens expire (default ~10 minutes). Retrieve a new one when expired.
### Live Environment IP Whitelisting
For live Merchant APIs, PayHere enforces IP-based whitelisting. Email `support@payhere.lk` with your server IP address to get whitelisted.
```
--------------------------------
### Charging API
Source: https://payheredoc.theepankaja.website/llms.txt
This API enables programmatic charging of preapproved customers using their stored customer tokens. It requires an OAuth Bearer Token for authentication.
```APIDOC
## Charging API (Tokenization)
### Purpose
Programmatically charge preapproved customers on demand using their stored `customer_token`.
### Auth
OAuth Bearer Token
### Endpoint
- Live: `POST https://www.payhere.lk/merchant/v1/payment/charge`
- Sandbox: `POST https://sandbox.payhere.lk/merchant/v1/payment/charge`
### Headers
```
Authorization: Bearer
Content-Type: application/json
```
### Request Body
```json
{
"type": "PAYMENT",
"order_id": "Order12345",
"items": "Taxi Hire 123",
"currency": "LKR",
"amount": 345.67,
"customer_token": "59AFEE022CC69CA39D325E1B59130862",
"custom_1": "custom parameter 1",
"custom_2": null,
"notify_url": "http://www.abc.com/notify",
"itemList": [
{
"name": "Item Name",
"number": "ITEM_001",
"quantity": 1,
"unit_amount": 345.67
}
]
}
```
#### Request Body Parameters
- **type** (string) - Required - Type of transaction. Values: `PAYMENT` (capture immediately, default), `AUTHORIZE` (authorize amount, returns `authorization_token` for later capture).
- **order_id** (string) - Required - Unique identifier for the order.
- **items** (string) - Required - Name or description of the item(s).
- **currency** (string) - Required - Currency code (e.g., LKR).
- **amount** (decimal) - Required - The amount to charge.
- **customer_token** (string) - Required - The tokenized customer card identifier.
- **custom_1** (string) - Optional - Custom parameter 1.
- **custom_2** (string) - Optional - Custom parameter 2.
- **notify_url** (string) - Optional - URL to receive payment status notifications.
- **itemList** (array) - Optional - An array of item details.
- **name** (string) - Item name.
- **number** (string) - Item number.
- **quantity** (int) - Item quantity.
- **unit_amount** (decimal) - Unit amount for the item.
```
--------------------------------
### Subscription API
Source: https://payheredoc.theepankaja.website/llms.txt
This section covers APIs related to managing subscriptions, including listing all subscriptions, retrieving payments for a specific subscription, retrying failed payments, and canceling subscriptions.
```APIDOC
## Subscription Management APIs
### List Subscriptions
#### Method
GET
#### Endpoint
`https://www.payhere.lk/merchant/v1/subscription` (Live)
`https://sandbox.payhere.lk/merchant/v1/subscription` (Sandbox)
#### Description
Retrieves a list of all active subscriptions managed by the merchant.
#### Parameters
- **merchant_id** (string) - Required - Your Merchant ID.
#### Response Example
```json
[
{
"subscription_id": "sub_abc123",
"order_id": "SUB_ORDER_001",
"status": "active",
"created_at": "2023-10-26T12:00:00Z"
}
]
```
### Subscription Payments
#### Method
GET
#### Endpoint
`https://www.payhere.lk/merchant/v1/subscription/{id}/payments` (Live)
`https://sandbox.payhere.lk/merchant/v1/subscription/{id}/payments` (Sandbox)
#### Description
Retrieves a list of all payments made for a specific subscription, identified by its ID.
#### Parameters
- **id** (string) - Required - The ID of the subscription.
#### Response Example
```json
[
{
"payment_id": "pay_xyz789",
"order_id": "SUB_ORDER_001_PAY_1",
"amount": "500.00",
"currency": "LKR",
"status": "success",
"paid_at": "2023-10-26T12:05:00Z"
}
]
```
### Retry Subscription Payment
#### Method
POST
#### Endpoint
`https://www.payhere.lk/merchant/v1/subscription/retry` (Live)
`https://sandbox.payhere.lk/merchant/v1/subscription/retry` (Sandbox)
#### Description
Attempts to retry a failed payment for a specific subscription.
#### Parameters
- **merchant_id** (string) - Required - Your Merchant ID.
- **subscription_id** (string) - Required - The ID of the subscription to retry.
#### Response Example
```json
{
"message": "Subscription payment retry initiated successfully."
}
```
### Cancel Subscription
#### Method
POST
#### Endpoint
`https://www.payhere.lk/merchant/v1/subscription/cancel` (Live)
`https://sandbox.payhere.lk/merchant/v1/subscription/cancel` (Sandbox)
#### Description
Cancels an active subscription.
#### Parameters
- **merchant_id** (string) - Required - Your Merchant ID.
- **subscription_id** (string) - Required - The ID of the subscription to cancel.
#### Response Example
```json
{
"message": "Subscription cancelled successfully."
}
```
```