Skip to main content
Glama
lakshitha0526

PayHere MCP Server

@lk-pay/payhere-mcp

npm license

A Model Context Protocol server for PayHere, Sri Lanka's payment gateway. It exposes PayHere's Merchant API and checkout flow as tools any MCP-aware client can call.

Status

v0.1 — early preview. All five tools have been validated end-to-end against the PayHere sandbox. The transport is stdio only.

Related MCP server: PayFast MCP

What this is

This is an MCP server for developers integrating PayHere. It lets you retrieve payments, issue refunds, generate signed checkout payloads, and compute or verify PayHere hashes directly from Claude Code, Claude Desktop, or any other MCP client.

The audience is developers, not merchants. It helps you debug an integration, pull a payment record, issue a refund, and get a checkout signature right — it is not a dashboard replacement.

PayHere uses snake_case fields and MD5-based hashes throughout its API. The tools here mirror that surface exactly and handle the parts that are easy to get wrong, like amount formatting and signature computation.

Quick start

Requires Node 18 or newer. If you already have a PayHere Business App and a whitelisted domain, run it directly:

npx @lk-pay/payhere-mcp

It reads configuration from the environment. The minimum is:

PAYHERE_MODE=sandbox
PAYHERE_MERCHANT_ID=your_merchant_id
PAYHERE_MERCHANT_SECRET=your_domain_bound_secret
PAYHERE_APP_ID=your_app_id
PAYHERE_APP_SECRET=your_app_secret

In Claude Code, add it to ~/.claude/mcp.json (or a project-local .claude/mcp.json):

{
  "mcpServers": {
    "payhere": {
      "command": "npx",
      "args": ["-y", "@lk-pay/payhere-mcp"],
      "env": {
        "PAYHERE_MODE": "sandbox",
        "PAYHERE_MERCHANT_ID": "your_merchant_id",
        "PAYHERE_MERCHANT_SECRET": "your_domain_bound_secret",
        "PAYHERE_APP_ID": "your_app_id",
        "PAYHERE_APP_SECRET": "your_app_secret"
      }
    }
  }
}

Setup

The Merchant API calls (get_payment, issue_refund, verify_credentials) need a Business App and a whitelisted domain. The checkout and signature tools work with just your merchant credentials.

Step 1 — Create a PayHere Business App

Log in to sandbox.payhere.lk (or www.payhere.lk for live). Go to Settings → Business Apps → Create API Key. Name the app, fill in the Allowed Domains field, and enable at least the Payment Retrieval API permission. Enable the Refund API permission too if you plan to issue refunds.

Step 2 — How PayHere binds credentials to domains

This is the part that trips most people up, so it's worth stating plainly.

PayHere generates a separate merchant_secret for each domain you whitelist. A Merchant API call only succeeds when the merchant_secret you send is tied to a domain that PayHere can currently verify is reachable. If the domain can't be reached, the secret is rejected.

It is not a Referer check and not a source-IP check. It is a binding between the secret and a verifiable domain. So the secret in your environment and a live, reachable whitelisted domain have to line up at request time.

Step 3 — Configure your domain

Local development. Use ngrok or any similar publicly reachable tunnel. VS Code dev tunnels don't work here because their auth interstitial stops PayHere from verifying the domain. Run:

ngrok http <your-port>

Whitelist the ngrok URL in PayHere's Allowed Domains, then copy the merchant_secret PayHere generates for that domain into your .env. Keep the tunnel running the whole time you use the MCP server — if it stops, the domain stops being reachable and calls start failing.

Production. Deploy to a server with a stable domain or static IP. For sandbox, whitelist the domain through the dashboard. For live, PayHere whitelists by IP — email support@payhere.lk with your production server IP and they'll add it.

Step 4 — Note your credentials

From the dashboard, collect:

  • Merchant ID

  • App ID and App Secret (from the Business App you created)

  • The merchant_secret tied to your whitelisted domain

Step 5 — Install and configure

Install globally, or skip this and use npx:

npm install -g @lk-pay/payhere-mcp

Set these environment variables:

Variable

Required

Description

PAYHERE_MODE

Yes

sandbox or live. Picks which PayHere environment the tools talk to.

PAYHERE_MERCHANT_ID

Yes

Your Merchant ID from the dashboard.

PAYHERE_MERCHANT_SECRET

Yes

The per-domain secret tied to your whitelisted domain. Used for checkout and notify hashes.

PAYHERE_APP_ID

Yes

Business App ID, used to fetch OAuth tokens for the Merchant API.

PAYHERE_APP_SECRET

Yes

Business App secret, paired with PAYHERE_APP_ID.

PAYHERE_DOMAIN

Optional

Bare domain (no scheme, no path), e.g. your-tunnel.ngrok.app. When set, requests include a Referer: https://<domain>/ header matching your whitelisted domain. Leave it unset unless your setup needs it.

Step 6 — Wire into your MCP client

Add all the variables to your client config:

{
  "mcpServers": {
    "payhere": {
      "command": "npx",
      "args": ["-y", "@lk-pay/payhere-mcp"],
      "env": {
        "PAYHERE_MODE": "sandbox",
        "PAYHERE_MERCHANT_ID": "your_merchant_id",
        "PAYHERE_MERCHANT_SECRET": "your_domain_bound_secret",
        "PAYHERE_APP_ID": "your_app_id",
        "PAYHERE_APP_SECRET": "your_app_secret",
        "PAYHERE_DOMAIN": "your-tunnel.ngrok.app"
      }
    }
  }
}

Once connected, run verify_credentials first to confirm your environment and OAuth token resolve correctly.

Tools

Tool

Purpose

When to reach for it

create_checkout_payload

Generate form fields + hash for a /pay/checkout submission

You're building a payment form and need a correctly signed payload.

get_payment

Retrieve all payment attempts for an order_id

You want to check an order's status or attempt history.

issue_refund

Refund a payment by payment_id, full or partial

A customer needs money back.

generate_signature

Compute or verify PayHere MD5 hashes (checkout + notify)

You're validating a notify callback or debugging a hash mismatch.

verify_credentials

Health-check env vars and fetch an OAuth token

You're setting up and want to confirm your config works.

Troubleshooting

The four errors you're most likely to see, and what they mean:

  • {"status":-1,"msg":"Access denied for the domain"} — The merchant_secret is bound to a domain PayHere can't currently verify. Check that (a) your ngrok tunnel is up, (b) the merchant_secret in .env matches the whitelisted domain, and (c) you haven't mixed sandbox and live values.

  • {"status":-2,"msg":"Authentication error"} — The App ID or App Secret is wrong, or the token belongs to a different Business App. Recheck PAYHERE_APP_ID and PAYHERE_APP_SECRET.

  • {"error":"invalid_token"} — The access token is expired or malformed, which usually means the App credentials don't match what PayHere expects. Confirm the App ID and secret, then retry.

  • {"status":-1,"msg":"No payments found"} — Not an error. The order_id has no payments yet. get_payment returns attempts: [] with a note field explaining there's nothing on record.

Design notes

  • No list_payments. PayHere's Retrieval API only accepts an order_id — there is no date-range or status filter endpoint. get_payment returns the array of attempts for one order.

  • generate_signature is the differentiator. Most PayHere integration bugs come from incorrect hash computation. This tool exposes the exact algorithm the gateway uses, with constant-time verification for notify URL validation.

  • stdio transport only in v0.1. That's the supported transport for this release.

Development

git clone https://github.com/lakshitha0526/payhere-mcp.git
cd payhere-mcp
npm install

npm run test       # vitest
npm run typecheck  # tsc --noEmit
npm run lint       # biome check
npm run build      # tsup

License

MIT — see LICENSE.

Part of the lk-* family of Sri Lanka-focused developer tooling.

Available Tools

5 tools
create_checkout_payloadCreate PayHere checkout payloadA

Generates the form data needed to POST a checkout request to PayHere, including the MD5 hash. Returns action URL, form fields, and an HTML snippet.

ParametersJSON Schema
NameRequiredDescriptionDefault
orderIdYesUnique order identifier for this payment
amountYesPayment amount (will be formatted to 2dp)
currencyYesISO 4217 currency code, e.g. LKR, USD
itemsYesItem description shown on the checkout page
customerYes
returnUrlYesURL to redirect to after successful payment
cancelUrlYesURL to redirect to if payment is cancelled
notifyUrlYesPublic URL PayHere will POST the payment result to

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, description carries full burden. It discloses the tool generates form data and hash, and returns specific outputs. However, it does not clarify if this is a pure computation or involves external calls, nor does it specify required authorizations or side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single, well-structured sentence that front-loads the verb 'Generates' and lists outputs. No redundant information, but could be more concise by splitting into two sentences.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema, the description outlines return types (action URL, form fields, HTML snippet), which is helpful. It implies usage (POST the form data) but does not address prerequisites like merchant credentials. Overall adequate for a moderately complex tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is high (88%), so the description adds little beyond schema. It mentions MD5 hash but doesn't tie it to a specific parameter. Baseline 3 is appropriate as the schema already documents parameters well.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the tool generates form data for posting a checkout request, including MD5 hash, and specifies outputs (action URL, form fields, HTML snippet). This distinguishes it from siblings like generate_signature or issue_refund.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives. No mention of prerequisites (e.g., requiring API credentials) or exclusions. The description only states what it does, not when it's appropriate.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

generate_signatureGenerate or verify a PayHere signatureA

Computes a PayHere MD5 hash for either checkout submission (mode='checkout') or notify URL validation (mode='notify'). For notify mode, pass expectedMd5Sig to verify an incoming signature in one shot. Uses the merchant secret from the server's environment — never include the secret in tool arguments.

ParametersJSON Schema
NameRequiredDescriptionDefault
modeYesWhich hash variant to compute
merchantIdNoMerchant ID. Defaults to PAYHERE_MERCHANT_ID env var.
orderIdYes
amountNoRequired for mode='checkout'. Formatted to 2dp internally.
currencyNoRequired for mode='checkout'. ISO 4217 (e.g. LKR).
payhereAmountNoRequired for mode='notify'. As sent by PayHere.
payhereCurrencyNoRequired for mode='notify'. As sent by PayHere.
statusCodeNoRequired for mode='notify'. PayHere status_code value.
expectedMd5SigNoOptional for mode='notify'. If provided, returns verification result instead of just the hash.

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It reveals that the tool uses a merchant secret from the server environment and never requires it in arguments. It describes conditional behavior for notify mode with verification. However, it does not discuss side effects or performance, but as a pure computation, this is acceptable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three sentences long, front-loads the core purpose, and contains no filler. Every sentence provides essential information about modes, verification, and security. It is highly efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

While the description covers modes and verification well, it does not specify the return type or structure. For a tool with no output schema, describing whether the output is a hash string, a boolean, or an object would be helpful for an AI agent to interpret results correctly. This omission makes it slightly incomplete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 89%, so the schema already documents most parameters. The description adds value by explaining conditional requirements (e.g., amount and currency for checkout, payhereAmount/Currency/statusCode for notify) and the role of expectedMd5Sig. This goes beyond the schema's individual descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states that the tool computes a PayHere MD5 hash for checkout submission or notify URL validation, using specific verbs and resources. It distinguishes between two modes and a verification feature, making its purpose unambiguous and distinct from sibling tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explains when to use each mode (checkout vs notify) and how to verify incoming signatures by passing expectedMd5Sig. It also warns against including the secret in arguments. However, it does not explicitly contrast with sibling tools, though the different operations imply appropriate usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_paymentGet PayHere payment(s) by order IDA

Returns all payment attempts (success, refunded, chargedback) associated with the given order_id. PayHere does not support listing by date range or status — only by order_id.

ParametersJSON Schema
NameRequiredDescriptionDefault
orderIdYesThe order_id used when initiating the payment

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It specifies the types of payment attempts returned (success, refunded, chargedback), which adds transparency. However, it does not discuss permissions, rate limits, or whether the data is mutable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences with no superfluous information. Every sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simplicity (one parameter, no output schema, no annotations), the description covers the essential return value and API limitation. It is adequately complete for a straightforward retrieval tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% as there is only one parameter. The description repeats the schema's description ('order_id used when initiating the payment'), adding minimal additional meaning.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states that the tool returns all payment attempts (success, refunded, chargedback) for a given order_id. This is distinct from sibling tools like issue_refund or create_checkout_payload.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explicitly states that PayHere does not support listing by date range or status—only by order_id. This provides clear guidance on when to use the tool and what not to expect, though it does not mention alternative tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

issue_refundIssue a PayHere refundA

Refunds a payment by payment_id. Omit amount for a full refund, or set it for a partial refund. Returns the PayHere refund status.

ParametersJSON Schema
NameRequiredDescriptionDefault
paymentIdYesPayHere payment_id (from get_payment or notify)
descriptionYesReason / note for the refund — visible to the merchant
amountNoPartial refund amount. Omit for a full refund.

TDQS

A4.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description must cover all behavior. It states returns refund status, but does not detail potential errors, side effects, or idempotency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, front-loaded with the action, no redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Minimally complete: explains return value but lacks context on error handling, prerequisites, or performance implications. No output schema to rely on.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, but description adds value by clarifying the conditional use of 'amount' (omit for full, set for partial refund), beyond schema details.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the verb 'Refunds' and the resource 'payment by payment_id', distinguishing it from sibling tools like create_checkout_payload or get_payment.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit guidance on when to omit or set 'amount' for full vs partial refund, but lacks explicit instructions on when not to use or alternative tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

verify_credentialsVerify PayHere credentialsA

Health check that confirms env vars are loaded and (once implemented) that the App credentials can fetch an OAuth token. Useful first call when setting up an integration.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. It discloses that the tool checks env vars and OAuth token fetch, indicating a read-only, non-destructive behavior. Does not detail error conditions or output format, but is sufficient for a health check.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences: first defines functionality, second provides usage guidance. No unnecessary words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description is complete for a zero-parameter health check tool. It explains purpose and usage. Could mention expected response format, but overall adequate given no output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has no parameters, so no additional semantic information is needed. Baseline score of 4 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it is a health check for credentials, specifying the verb 'confirm' and the resource 'env vars' and 'OAuth token'. It distinguishes from sibling tools like create_checkout_payload or issue_refund.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states it is useful as a first call when setting up an integration, providing clear usage context. Does not mention when not to use, but sibling tool names imply different purposes.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv0.1.0
    • First observedcreate_checkout_payload
    • First observedgenerate_signature
    • First observedget_payment
    • First observedissue_refund
    • First observedverify_credentials

TDQS

A4.2/5.0

Scored across 5 tools

Disambiguation5/5

Each tool serves a distinct purpose: creating checkout payloads, generating signatures, retrieving payments by order ID, issuing refunds, and verifying credentials. No overlapping responsibilities.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in snake_case (e.g., create_checkout_payload, issue_refund), making the API predictable and easy to navigate.

Tool Count5/5

With 5 tools covering checkout creation, signature generation, payment retrieval, refunds, and credential verification, the number is well-scoped for a payment gateway integration without unnecessary clutter.

Completeness4/5

Covers essential payment operations: creating checkouts, refunding, retrieving payment status by order ID, and signature validation. Missing list payments endpoint aligns with PayHere's API limitations, but a tool for direct payment retrieval by payment_id would enhance completeness.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Centralizes payment gateway integrations for Pagar.me (customers, recipients, Pix, credit card, splits, charges) and Woovi/OpenPix (Pix charges, refunds, webhook verification) through MCP tools.
    6 npm
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    Enables interaction with the South African PayFast payment gateway to manage transactions, subscriptions, and refunds. It allows users to create payments, query transaction statuses, and check settlement balances through the MCP protocol.
    8
    16 npm
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides AI-ready documentation for the PayHere payment gateway, enabling access to API references, SDK guides, and documentation search through MCP tools.
    MIT