Integrating 2C2P, PesoPay and Paynamics: A Front-End Guide to Southeast Asian Payment Gateways
How to integrate 2C2P, PesoPay and Paynamics from a React front end: hosted payment flows, request signing, verifying notifications and avoiding common traps.

The browser starts the payment. The server decides whether it happened. 2C2P, PesoPay and Paynamics look different on paper, but they share one shape: a signed request, a hosted payment page and a server-to-server result. Build around that shape and adding a gateway becomes a small, contained job.
In my post on migrating an AngularJS website to AEM with a React front end, I mentioned that the online payment forms were integrated with three gateways: 2C2P, PesoPay and Paynamics. I promised a closer look, and this is it.
This guide is for front-end and full-stack developers integrating hosted payment gateways in the Philippines and Southeast Asia. It's built on each gateway's public developer documentation and on patterns that apply to any hosted payment flow, not on any client's code. Gateways update their APIs, so always build against the current specification your gateway account manager gives you.
The one shape all three share
Despite different APIs, the flow is the same for all three:
- The customer clicks Pay. Your React app asks your own server to start a payment for an order.
- Your server builds a signed request. It looks up the amount from the order, never from the browser, and signs the request with a secret only the server knows.
- The browser hands off to the gateway. Either a redirect to a payment URL the gateway returned, or an auto-submitted form that posts the signed fields to the gateway.
- The customer pays on the gateway's hosted page and is sent back to a return URL on your site.
- The gateway notifies your server directly, server to server. Your server verifies the signature, checks the amount, and only then marks the order as paid.
The most important consequence: step 4 is not proof of payment. The return URL is a browser redirect, so a customer can open it, refresh it, or reach it without paying. The payment is real only when step 5 arrives and verifies. PesoPay's integration guide says it plainly about its success, fail and cancel URLs: they're "for display purpose only. DO NOT use this URL to update your system."
Rules that apply to every gateway
- Secrets stay on the server. Signing keys and secrets must never reach the browser bundle, environment variables prefixed for the client, or logs.
- The server decides the amount. Look it up from the order in your database. Never accept a price from the browser.
- The notification is the source of truth. Update the order from the verified server-to-server message, not from the return page.
- Verify every signature. A notification endpoint is a public URL. Anyone can post to it; only a valid signature proves it came from the gateway.
- Check the amount and currency again. Even with a valid signature, confirm the paid amount and currency match the order before marking it paid.
- Make notifications idempotent. Gateways retry notifications. Processing the same one twice must not ship an order twice or send two receipts.
- Sign exactly what you send. Amount formatting is the most common signature failure:
1500,1500.0and1500.00produce different hashes. Format once, then use that same string everywhere.
A gateway-agnostic design
Treat each gateway as an adapter behind one interface. The React app only ever deals with a "handoff" description from the server:
1type Handoff =
2 | { type: 'redirect'; url: string } // e.g. 2C2P returns a payment page URL
3 | { type: 'form-post'; action: string; fields: Record<string, string> } // e.g. PesoPay client postEach gateway adapter then needs two server-side functions: one that turns an order into a Handoff, and one that verifies an incoming notification and reports which order it's for, whether it succeeded, and the amount and currency. Adding a gateway means writing those two functions; the checkout UI and order logic don't change.
2C2P: a signed token, then a redirect
2C2P's current payment gateway API (version 4.5 at the time of writing) works in three steps: your server requests a payment token, redirects the customer to the web payment URL it gets back, and receives the result through a backend notification.
Requests and responses are JSON Web Tokens signed with HMAC SHA-256 (HS256) using your merchant secret key, sent as {"payload": "<jwt>"}. Here's the server side, using the jose library:
1import { SignJWT, jwtVerify } from 'jose'
2
3const BASE = process.env.TWOC2P_ENV === 'live' ? 'https://pgw.2c2p.com' : 'https://sandbox-pgw.2c2p.com'
4const key = () => new TextEncoder().encode(process.env.TWOC2P_SECRET!)
5
6/** Server side: ask 2C2P for a payment token and the hosted payment page URL. */
7export async function createTwoC2PPayment(order: { ref: string; amount: number; description: string }, base: string) {
8 const payload = await new SignJWT({
9 merchantID: process.env.TWOC2P_MERCHANT_ID!,
10 invoiceNo: order.ref,
11 description: order.description,
12 amount: order.amount,
13 currencyCode: 'PHP',
14 frontendReturnUrl: `${base}/checkout/result?ref=${order.ref}`,
15 backendReturnUrl: `${base}/api/payments/2c2p/notify`,
16 })
17 .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
18 .sign(key())
19
20 const res = await fetch(`${BASE}/payment/4.5/paymentToken`, {
21 method: 'POST',
22 headers: { 'Content-Type': 'application/json' },
23 body: JSON.stringify({ payload }),
24 })
25 const data = await decodeTwoC2P(((await res.json()) as { payload: string }).payload)
26 if (data.respCode !== '0000') throw new Error(`2C2P: ${data.respCode} ${data.respDesc}`)
27 return { redirectUrl: data.webPaymentUrl as string }
28}
29
30/** Verify (not just decode) a 2C2P JWT with the merchant secret. Throws if it was tampered with. */
31export async function decodeTwoC2P(jwt: string) {
32 const { payload } = await jwtVerify(jwt, key(), { algorithms: ['HS256'] })
33 return payload as Record<string, unknown>
34}A few details from 2C2P's documentation worth knowing:
- Proceed only when
respCodeis"0000"in the token response, then redirect the customer towebPaymentUrl. frontendReturnUrlandbackendReturnUrlare optional per request. If you leave them out, 2C2P uses the URLs set in your merchant profile. Setting them per request keeps environments separate.- The backend notification is a JWT containing the invoice number, amount, currency and response code. Verify it with your secret, as
decodeTwoC2Pdoes, rather than only decoding it. - The browser return carries only an encoded summary, typically telling you to request full payment details. If you don't implement the backend notification, 2C2P requires you to call its Payment Inquiry API to get the final result.
Notice that decodeTwoC2P uses jwtVerify, not a plain decode. Decoding a JWT just reads it; verifying checks the signature. A forged notification decodes perfectly well. Only verification rejects it.
PesoPay: a signed form post and a datafeed
PesoPay (by AsiaPay) uses a client post: your page posts an HTML form to PesoPay's payment page, and PesoPay sends the result to a datafeed URL on your server. Its integration guide lists these endpoints for the client post method:
- Test:
https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp - Live:
https://www.pesopay.com/b2c2/eng/payment/payForm.jsp
Every request carries a secure hash: a SHA-1 (the default) or SHA-256 digest of merchantId|orderRef|currCode|amount|payType|secret, where the secret is the Secure Hash Secret from your merchant administration tool. The currency code for Philippine pesos is 608.
1import { createHash, timingSafeEqual } from 'node:crypto'
2
3const PAY_URL = process.env.PESOPAY_ENV === 'live'
4 ? 'https://www.pesopay.com/b2c2/eng/payment/payForm.jsp'
5 : 'https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp'
6
7const sha1 = (s: string) => createHash('sha1').update(s).digest('hex')
8
9/** Request hash: merchantId|orderRef|currCode|amount|payType|secret (SHA-1 is the default). */
10export function requestHash(f: { merchantId: string; orderRef: string; currCode: string; amount: string; payType: string }, secret: string) {
11 return sha1([f.merchantId, f.orderRef, f.currCode, f.amount, f.payType, secret].join('|'))
12}
13
14/** Server side: everything the browser needs to post the customer to PesoPay. */
15export function createPesoPayForm(order: { ref: string; amount: string }, base: string) {
16 const fields = {
17 merchantId: process.env.PESOPAY_MERCHANT_ID!,
18 orderRef: order.ref,
19 amount: order.amount, // the exact string you hash is the exact string you send
20 currCode: '608', // PHP
21 payType: 'N', // N = sale, H = authorise only
22 lang: 'E',
23 successUrl: `${base}/checkout/result?ref=${order.ref}`,
24 failUrl: `${base}/checkout/result?ref=${order.ref}`,
25 cancelUrl: `${base}/checkout/result?ref=${order.ref}`,
26 }
27 return { action: PAY_URL, fields: { ...fields, secureHash: requestHash(fields, process.env.PESOPAY_SECRET!) } }
28}
29
30/** Datafeed hash: src|prc|successcode|Ref|PayRef|Cur|Amt|payerAuth|secret. */
31export function verifyDatafeed(p: Record<string, string>, secret: string) {
32 const expected = sha1([p.src, p.prc, p.successcode, p.Ref, p.PayRef, p.Cur, p.Amt, p.payerAuth, secret].join('|'))
33 const received = p.secureHash ?? ''
34 return received.length === expected.length && timingSafeEqual(Buffer.from(received), Buffer.from(expected))
35}I checked requestHash against the worked example in PesoPay's integration guide, and it produces the guide's expected hash exactly. It's worth doing the same with your own credentials: a hash that's wrong by one character fails silently at the gateway.
The datafeed handler then looks like this:
1// app/api/payments/pesopay/datafeed/route.ts
2export async function POST(req: Request) {
3 const p = Object.fromEntries((await req.formData()).entries()) as Record<string, string>
4
5 if (verifyDatafeed(p, process.env.PESOPAY_SECRET!)) {
6 await recordPaymentResult({
7 orderRef: p.Ref,
8 succeeded: p.successcode === '0', // 0 = succeeded, 1 = failure, others = error
9 amount: p.Amt,
10 currency: p.Cur,
11 gatewayRef: p.PayRef,
12 })
13 } else {
14 console.warn('PesoPay datafeed failed verification', { ref: p.Ref })
15 }
16
17 // PesoPay reads the response for the word "OK" to confirm the datafeed was received.
18 return new Response('OK')
19}Things the PesoPay guide calls out:
- Respond with
OK. PesoPay checks the datafeed page's response for the word "OK". Without it, the datafeed isn't acknowledged. successcode0 means success, 1 means failure, and anything else is an error.payTypeH only authorises the card. You must capture the payment later in the merchant administration site. If an authorisation isn't captured or reversed within 14 days, the hold may be released to the cardholder.- The Secure Hash Secret is rotated every two years, so keep it in configuration, not in code, and note the rotation date.
Paynamics: same pattern, get the current spec
Paynamics is widely used in the Philippines, but unlike 2C2P and PesoPay, its current developer specification isn't easy to find publicly: what's openly available is mostly older API documents and community libraries, and older Paynamics specifications describe a SHA-512 signature built from the request fields and the merchant key, with results delivered to a server notification URL and the customer returned to a separate response URL.
Treat those details as a starting point, not a specification. Get the current API documentation and sandbox credentials from your Paynamics account manager, and build the adapter against that. The good news is that the architecture doesn't change: a server-signed request, a handoff to the hosted page, a server-to-server notification you verify, and a return page that only displays status. If you've built the 2C2P and PesoPay adapters above, Paynamics becomes a third adapter with the same two functions.
Recording the result safely
All three notification handlers end in the same place. That shared function is where the business rules live:
1// A sketch: adapt to your database.
2async function recordPaymentResult(r: {
3 orderRef: string
4 succeeded: boolean
5 amount: string
6 currency: string
7 gatewayRef: string
8}) {
9 const order = await db.orders.findByRef(r.orderRef)
10 if (!order) return // unknown order: log it and investigate
11
12 // Idempotent: gateways retry notifications.
13 if (order.status === 'paid') return
14
15 // A valid signature isn't enough: the money must match the order.
16 if (r.succeeded && (r.amount !== order.amountString || r.currency !== order.currencyCode)) {
17 await db.orders.flagForReview(r.orderRef, 'Amount or currency mismatch')
18 return
19 }
20
21 await db.orders.update(r.orderRef, {
22 status: r.succeeded ? 'paid' : 'failed',
23 gatewayRef: r.gatewayRef,
24 })
25}Keep this function boring and well tested. It's the only code path that turns a message from the internet into a paid order.
The React side
On the front end, the checkout button asks your server to start a payment and then hands off to the gateway, either by redirecting or by auto-submitting a form:
1'use client'
2
3import { useState } from 'react'
4
5type Handoff =
6 | { type: 'redirect'; url: string }
7 | { type: 'form-post'; action: string; fields: Record<string, string> }
8
9/** Sends the customer to the gateway. The browser only carries what the server prepared. */
10function handOff(h: Handoff) {
11 if (h.type === 'redirect') {
12 window.location.assign(h.url)
13 return
14 }
15 const form = document.createElement('form')
16 form.method = 'POST'
17 form.action = h.action
18 for (const [name, value] of Object.entries(h.fields)) {
19 const input = document.createElement('input')
20 input.type = 'hidden'
21 input.name = name
22 input.value = value
23 form.append(input)
24 }
25 document.body.append(form)
26 form.submit()
27}
28
29export function PayButton({ orderId, gateway }: { orderId: string; gateway: '2c2p' | 'pesopay' | 'paynamics' }) {
30 const [busy, setBusy] = useState(false)
31 const [error, setError] = useState('')
32
33 async function pay() {
34 setBusy(true)
35 setError('')
36 try {
37 // The server looks up the order's amount itself: never send the price from the browser.
38 const res = await fetch('/api/payments/start', {
39 method: 'POST',
40 headers: { 'Content-Type': 'application/json' },
41 body: JSON.stringify({ orderId, gateway }),
42 })
43 if (!res.ok) throw new Error('Could not start payment')
44 handOff((await res.json()) as Handoff)
45 } catch {
46 setError('We couldn’t start the payment. Please try again.')
47 setBusy(false)
48 }
49 }
50
51 return (
52 <>
53 <button type="button" onClick={pay} disabled={busy}>
54 {busy ? 'Redirecting to secure payment…' : 'Pay now'}
55 </button>
56 {error && <p role="alert">{error}</p>}
57 </>
58 )
59}The return page never trusts the redirect. It shows a "confirming" state and polls your server until the verified notification has updated the order:
1'use client'
2
3import { useEffect, useState } from 'react'
4
5type Status = 'pending' | 'paid' | 'failed' | 'slow'
6
7export function PaymentResult({ orderRef }: { orderRef: string }) {
8 const [status, setStatus] = useState<Status>('pending')
9
10 useEffect(() => {
11 let tries = 0
12 const timer = setInterval(async () => {
13 tries++
14 const res = await fetch(`/api/orders/${encodeURIComponent(orderRef)}/status`)
15 const { status: next } = (await res.json()) as { status: Status }
16 if (next !== 'pending' || tries >= 20) {
17 setStatus(next === 'pending' ? 'slow' : next)
18 clearInterval(timer)
19 }
20 }, 3000)
21 return () => clearInterval(timer)
22 }, [orderRef])
23
24 if (status === 'paid') return <p>Payment received. Thank you!</p>
25 if (status === 'failed') return <p>The payment didn’t go through. Please try again or choose another method.</p>
26 if (status === 'slow') return <p>We’re still confirming your payment. We’ll email you as soon as it’s done.</p>
27 return <p aria-live="polite">Confirming your payment… please don’t close this page.</p>
28}The "slow" state matters more than it looks. Notifications can arrive after the customer has returned, sometimes minutes later. Telling customers you'll email them stops them paying twice.
Testing checklist
Before going live with any gateway, test these in its sandbox:
- A successful payment updates the order from the notification, not from the return page.
- A failed and a cancelled payment leave the order unpaid and show a clear message.
- A tampered notification (change the amount, keep the signature) is rejected.
- A duplicate notification doesn't process the order twice.
- The customer closes the tab after paying: the order still updates from the notification.
- A slow notification shows the "still confirming" state, then resolves.
- Amount formatting produces the same signed value as the gateway expects.
- Live credentials are only in production configuration, never in the repository.
FAQ
Can I integrate a payment gateway purely in the front end?
No. Signing requests and verifying results need a secret that must never reach the browser. The front end starts the payment and displays the result; a server builds the signed request and confirms the outcome.
Why can't I trust the success URL?
It's just a browser redirect. Anyone can open it, refresh it or reach it without paying. Mark orders as paid only from the gateway's verified server-to-server notification, as PesoPay's own guide insists.
Should I verify the gateway's signature if I'm using HTTPS?
Yes. HTTPS protects data in transit, but your notification URL is public: anyone can send a request to it. Only the signature proves the message came from the gateway and wasn't changed.
How do I support several gateways at once?
Put each gateway behind the same two functions: one that creates a handoff from an order, and one that verifies a notification. The checkout UI and order logic stay the same, and adding a gateway becomes a contained change.
Related posts
Share this article
Found it helpful? Share it with your network.
Keep reading

Migrating an AngularJS Website to AEM with a React SPA Editor Front End: Lessons Learned
Lessons from migrating an AngularJS and Node.js site to Adobe Experience Manager with a React SPA Editor front end: components, JSON models, payments and SEO.

BullMQ in Production: Retries, Dead-Letter Queues and Monitoring for Node.js Jobs
Run Node.js background jobs with BullMQ in production: idempotent jobs, exponential retries, dead-letter queues, schedulers and graceful shutdown.

TypeScript Generics for React Components: 5 Patterns That Keep UI Honest
Practical TypeScript generics for React components: polymorphic 'as' props, generic tables and selects, keyof constraints, const type params and NoInfer.