Themia.Payments.TwoCTwoP
0.70.0
dotnet add package Themia.Payments.TwoCTwoP --version 0.70.0
NuGet\Install-Package Themia.Payments.TwoCTwoP -Version 0.70.0
<PackageReference Include="Themia.Payments.TwoCTwoP" Version="0.70.0" />
<PackageVersion Include="Themia.Payments.TwoCTwoP" Version="0.70.0" />
<PackageReference Include="Themia.Payments.TwoCTwoP" />
paket add Themia.Payments.TwoCTwoP --version 0.70.0
#r "nuget: Themia.Payments.TwoCTwoP, 0.70.0"
#:package Themia.Payments.TwoCTwoP@0.70.0
#addin nuget:?package=Themia.Payments.TwoCTwoP&version=0.70.0
#tool nuget:?package=Themia.Payments.TwoCTwoP&version=0.70.0
Themia.Payments.TwoCTwoP
The 2C2P PGW 4.3 (Redirect API) adapter for Themia.Payments:
TwoCTwoPPaymentGateway implements IPaymentGateway and IPaymentGatewayCapabilities, and
TwoCTwoPWebhookVerifier implements IPaymentWebhookVerifier for 2C2P's backend notification. Targets
net8.0 and net10.0.
Registration
services.AddThemiaPaymentsTwoCTwoP(o =>
{
o.MerchantId = configuration["Payments:TwoCTwoP:MerchantId"]!;
o.SecretKey = configuration["Payments:TwoCTwoP:SecretKey"]!;
o.Environment = TwoCTwoPEnvironment.Sandbox; // same API, no real money
// Leave empty to mean "every channel"; set it to the channels this merchant is actually enabled
// for with 2C2P, so a request for one you are not enabled for fails locally, not at 2C2P.
o.PaymentChannels = [PaymentMethod.Card, PaymentMethod.QrPromptPay];
});
AddThemiaPaymentsTwoCTwoP validates MerchantId, SecretKey, Timeout and TransactionTimeOffset on
start, registers the named HttpClient, and calls AddThemiaPayments() itself. Register only one
payment adapter per container (see the Themia.Payments README).
Every method makes a single HTTP call, retried up to 3 attempts: with the default 30 s Timeout that is
up to ~91 s — pass a CancellationToken with your own deadline. A non-2xx response with no 2C2P body at
all (an HTML error page from a proxy) throws PaymentApiException with ProviderCode HTTP_{status},
classified by status (5xx Transient, 429 RateLimited, 401 Authentication, 403 Permission, 404
NotFound).
The JWT signature is the authentication
Every request and response body — including the backend notification — is {"payload": "<JWT>"},
HS256-signed with the shared merchant secret. There is no bearer token, no basic auth header, and no
separate signature field: the JWT's own HS256 signature is 2C2P's entire authentication scheme for
every direction of every call. A response is verified before anything in it is trusted; a body whose
payload fails verification is never parsed for its claims, only for the plain, unsigned
{ "respCode", "respDesc" } error shape 2C2P uses for request-level rejections (bad merchant, bad
signature).
ReferenceId is 2C2P's invoiceNo — 20 characters here, no more
public required string ReferenceId { get; init; } // -> invoiceNo
2C2P documents invoiceNo as up to 50 characters, with 20 alphanumeric characters for QR payments (and 12 numerals for Myanmar APM). This package holds every charge to 20, so a reference id that works for a card never fails later on the QR path. CreateChargeAsync checks this before calling 2C2P and
refuses locally (PaymentApiException(FailureKind.Validation, "reference_id_too_long", …)) rather than
letting a 21-character reference id fail at the provider.
2C2P mints no charge id before payment
ChargeCreation.ChargeId and Charge.ChargeId are always the caller's own ReferenceId — there is no
separate provider-issued id to track. GetChargeAsync (2C2P's Payment Inquiry) reads by invoiceNo
first; a ChargeRef.ProviderChargeId is accepted only as a fallback, and only because for this provider
invoice number and charge id are the same value.
respCode mapping — 0999 is not a failed payment
2C2P respCode |
Inquiry (GetChargeAsync) |
Backend notification |
|---|---|---|
0000 |
Succeeded |
ChargeSucceeded |
0001, 2001 |
Pending |
Other, status Pending |
0003 / 0004 / 4005 / 4051 |
Failed + Canceled / AuthenticationFailed / Declined / InsufficientFunds |
ChargeFailed |
2002 |
throws PaymentApiException(NotFound) |
ChargeFailed |
0999, 2003 and any other code |
throws PaymentApiException(Transient), raw code as ProviderCode |
Other, status Pending — never ChargeFailed |
0999 is 2C2P's own system error, 2003 ("Payment / Inquiry Failed") may mean only that the inquiry failed, and an unrecognised code says nothing reliable about whether the
shopper paid: reporting either as a failed payment could get a paid order cancelled. Retry the inquiry
instead. The raw code is always carried.
Refunds
Not yet verified against the 2C2P sandbox. The request and response shapes follow 2C2P's published Payment Maintenance documentation and are tested against key pairs generated in the tests only. Run a sandbox refund with your own merchant key pair before relying on it in production.
Refunds go through 2C2P's Payment Maintenance API (processType R), which does not use the shared secret
every other call here uses. The XML request is encrypted to 2C2P's public certificate as a JWE
(RSA-OAEP + A256GCM) and the JWE is signed with the merchant's private key as a JWS (PS256). Responses
are verified with 2C2P's public key first and only then decrypted; the algorithms are pinned, and a header
that names another algorithm or selects a key (kid, jwk, jku, x5u, zip, crit) is refused.
services.AddThemiaPaymentsTwoCTwoP(o =>
{
// ... MerchantId, SecretKey, Environment as above ...
o.MerchantPrivateKeyPem = configuration["Payments:TwoCTwoP:MerchantPrivateKeyPem"]; // RSA >= 2048, PKCS#8 or PKCS#1
o.ProviderPublicCertificatePem = configuration["Payments:TwoCTwoP:ProviderPublicCertificatePem"]; // x509 from the 2C2P portal
});
Both are read from configuration, never logged, and checked on start (RSA of at least 2048 bits, an unexpired
certificate). Set both or neither: with neither, RefundAsync refuses with refund_not_supported and
sends nothing, as in earlier versions.
- Full or partial.
RefundRequest.Amountofnullrefunds the charge's whole amount; otherwise the amount must be greater than zero, in the charge's currency, and not above the charge's amount. 2C2P refunds a settled transaction only. - Sent once, never retried. Nothing establishes that 2C2P replays an
idempotencyID, so a timeout, a transport failure, a5xx/429/408, an unverifiable response or an unknownrespCodethrowsPaymentApiExceptionrefund_outcome_unknown(FailureKind.Unknown). Check the 2C2P merchant portal before refunding again. Cancelling theCancellationTokenafter the request is sent is reported the same way, not as a cancellation. TheIdempotencyKeyyou pass is sent asidempotencyID; without one a fresh id is generated, which identifies nothing on a later attempt, so pass a stable key per refund (for example your refund record's id). A response that echoes anotheridempotencyIDis refused. The namedHttpClienthas no resilience or retry handler; do not add one to it, it would re-send a refund. - Status.
respCode00with refund statusRFisSucceeded;RFF(Refund Failed),RR(Refund Rejected) andRR1toRR3(rejected: insufficient balance, invalid bank information, bank account mismatch) areFailed, per 2C2P's Payment Maintenance status codes;RPand any status this package does not know arePending, neverSucceeded.RefundCreation.RefundIdis alwaysnull: key your records on the charge. 2C2P's refund guide says a refund of some 123 payments and wallets is asynchronous and that 2C2P then POSTs the final status, encrypted with JWE + JWS (notifyResponse=...).TwoCTwoPRefundNotificationVerifieropens that notification (see "Refund notification" below); the poll,GetRefundsAsync(below), stays the way to read the result. 2C2P also states that a refund can only be requested for a settled transaction. A caller must never retryrefund_outcome_unknownautomatically. - 2C2P is the only guard against over-refunding. The inquiry does not show what was already refunded, so two concurrent or repeated partial refunds can exceed the charge locally unnoticed. Serialize refunds per charge.
- A response is accepted only when its
invoiceNo(andmerchantID, when present) match the request.
Following a refund: GetRefundsAsync
TwoCTwoPPaymentGateway also implements IRefundStatusGateway. GetRefundsAsync(ChargeRef) asks the Payment Maintenance API for the refund status of the charge's invoice (processType RS) and returns a RefundRecord per refund: 2C2P's referenceNo as RefundId, the amount in the charge's currency, the status (mapped as above), the time, and IdempotencyKey.
- Matching a record to the refund you sent. The
IdempotencyKeyyou pass toRefundAsyncis also sent as the refund'suserDefined1, and 2C2P returns it on the refund in the status list, so match onRefundRecord.IdempotencyKey. A refund made in the 2C2P portal (or one that 2C2P does not echo) hasnull. The key is sent asuserDefined1only when it is at most 50 characters (2C2P publishes 150 foruserDefined1on a payment token request but no length for the Payment Process request, and a rejected value would fail the refund); a longer key is still sent asidempotencyIDbut its record comes back withIdempotencyKeynull, so match it on amount and time. Keep keys short. - Needs the same keys as
RefundAsync(refund_not_supportedwithout them). It changes nothing and is safe to repeat: a failure to reach 2C2P isFailureKind.Transient(refund_status_unavailable), notrefund_outcome_unknown. An unverifiable response, another invoice's, or a refund row with an unreadable amount ismalformed_response; any otherrespCodeis thrown as that code. - Not verified against the 2C2P sandbox: the request omits
actionAmount(the sample in the docs includes one forRS; the older documentation does not), and theuserDefined1echo is as documented.
What the shopper paid with: Charge.PaidMethod
GetChargeAsync fills Charge.PaidMethod, so a receipt can say Card rather than Transfer. The payment inquiry documents paymentScheme and channelCode as values of 2C2P's Payment Scheme / Process by list, whose Type column files each code: every code of Type Card (VI, MA, JC, UP, AM, ...) is Card, and every code of Type Wallet (TM TrueMoney, SH ShopeePay, LP LINE Pay, PP PaoTang, ...) is Wallet, which also covers the pay-later wallets 2C2P files there. paymentScheme is read first, then channelCode. From the payment-channel reference there are three more rules: the group codes CC and CSTOKEN are Card, THQR with agent PPQR is QrPromptPay, and ETQ ("QR Gateway - Thai QR") is read as QrPromptPay. Anything else is null: bank transfer, loyalty, the other QR types, and mobile banking, because 2C2P documents the Thai bank deep links as a way to request a payment but does not say what the inquiry returns for one. So null happens (not paid yet, or an unmapped channel) and each app needs its own fallback. Charge.PaidChannel carries the codes behind it as paymentScheme=MA channelCode=VI agentCode=OCBC (absent parts left out, a value that is not a short alphanumeric code dropped), so an app can log or store them, for example to learn which codes left PaidMethod null; never branch on it. It labels a receipt; it never decides success. Not verified against the sandbox; the list was copied from the documentation on 2026-10-30.
In-page PromptPay QR
A charge whose AllowedMethods is exactly [PaymentMethod.QrPromptPay] and whose PresentationMode is not HostedPage returns NextAction.ShowQr rather than the hosted-page Redirect, so the QR can be drawn inside your own page (for example in LINE LIFF). After the paymentToken call the gateway calls Do Payment (POST /payment/4.3/payment) once with channelCode: THQR, agentCode: PPQR, and expects flow code 1005 ("Pending for user scan QR") with type: URL and data = the QR PNG address, plus expiryTimer in milliseconds. ShowQr.ImagePng is that PNG, RawPayload is null, and Expiry is now + expiryTimer (or the request's ExpiresAt when 2C2P sends none).
PresentationMode.HostedPageopts out. Set it to get the hosted-pageRedirectfor a PromptPay-only charge; Do Payment is then not called at all.- Always a safe fallback. If Do Payment fails or answers anything else (another flow code,
type: QRraw data, an error), or the image cannot be fetched, the charge still succeeds and returns the hosted-pageRedirect. CheckActionby type; do not assumeShowQr. - Image fetch is restricted:
httpson a2c2p.comhost only, no other host after redirects, at most 256 KB, and it must be a PNG. - Do Payment is sent once and never retried. The shopper's payment still arrives through the normal notification / inquiry path; nothing about status mapping changes.
- Charges that allow cards, mobile banking or wallets keep the
Redirect, since those need 2C2P's hosted page (3-D Secure, app switching). - Not yet verified against the 2C2P sandbox. The request and response shapes come from 2C2P's "Do Payment" and "Payment Flow Codes" documentation; 2C2P's current docs show Do Payment at
/payment/4.5/payment, while this package pins 4.3 like the rest of its calls. Run a sandbox charge before relying on it.
Payment channels: group codes, not individual banks/wallets
PaymentMethod is sent to 2C2P as one of its paymentChannel[] group codes:
PaymentMethod |
2C2P group code |
|---|---|
Card |
CC |
QrPromptPay |
THQR |
MobileBanking |
DEEPLINK |
Wallet |
EWALLET |
TwoCTwoPOptions.PaymentChannels narrows SupportedMethods (and, through it, what
PaymentMethodGate/CreateChargeAsync will accept) to the channels this merchant is actually enabled
for with 2C2P; left empty, SupportedMethods reads as "not restricted" (all four) rather than "none" —
2C2P has no capability-discovery call to ask instead.
Verify in the 2C2P sandbox before going live
Three things this adapter takes on faith because 2C2P's documentation does not state them plainly. Confirm each against a real sandbox transaction before trusting it in production:
TransactionTimeOffset(default+07:00). 2C2P'stransactionDateTimeis a bareyyyyMMddHHmmssstring with no timezone, and 2C2P does not document which zone it is in. The default assumes Thailand; if your merchant account settles elsewhere, setTwoCTwoPOptions.TransactionTimeOffset(validated to within ±14 hours) to match. The same offset convertsCreateChargeRequest.ExpiresAtinto 2C2P's barepaymentExpiry(yyyy-MM-dd HH:mm:ss); without anExpiresAt, 2C2P's own default of 20 minutes applies.- The
THQRgroup is not only PromptPay. The group 2C2P callsTHQRalso carries TrueMoney, ShopeePay and GrabPay TH QR codes, not exclusively Thai QR PromptPay — a channel restriction meant to allow "PromptPay only" may admit more than that. - The group codes themselves (
CC/THQR/DEEPLINK/EWALLET) — taken from 2C2P's published payment-channel reference, not from the older ezy-assets integration this package replaces, which used a different, non-matching set (CC/THQR/EWALLETS/123) and never actually sent the field.
Refund notification
For an asynchronous refund 2C2P can call you when it finishes. Set TwoCTwoPOptions.RefundNotifyUrl (https, needs the refund keys; sent as notifyURL in the refund request) and map that URL to an endpoint that hands the raw body to TwoCTwoPRefundNotificationVerifier.Verify(body, headers) (resolve it as itself: IPaymentWebhookVerifier stays the payment webhook's). Set the endpoint's request body limit to 64 KiB.
- It checks the JWS signature with the 2C2P certificate before decrypting anything with the merchant key, and accepts only the pinned algorithms. A bad or unreadable token is
SignatureMismatch(also what a merchant key that changed looks like: check the keys before assuming an attack); a body that is not onenotifyResponseform field, a notification for another merchant or another process type, or one without a time isMalformed. - Use a
Verifiedrefund event as a nudge: callGetRefundsAsyncfor the charge and reconcile byRefundRecord.IdempotencyKey. Do not write the event's status onto a refund row. The notification does not say which of several refunds of one invoice it is about, andRefundAsyncnever learns 2C2P's reference. The status is mapped like the poll (RFsucceeded,RFF/RR*failed, anything else or arespCodeother than00isOtherand pending).RawJsoncarriesidempotencyID/userDefined1/refundReferenceNowhen 2C2P sends them (not confirmed), and nothing about the card. - A body is authentic, not fresh: a captured one replays for ever. As a nudge a replay costs one read; coalesce nudges per charge if you want to bound that.
- Missing or invalid refund keys make
VerifythrowInvalidOperationException(a 500 for 2C2P to retry), not a verdict on the sender. - Not verified against the 2C2P sandbox, so do not set
RefundNotifyUrlin production yet: thenotifyURLelement name and place in the request (a request 2C2P refuses would turn every refund intorefund_outcome_unknown), the form encoding and content type, which reference the notification carries, whethertimeStamp(yyMMddHHmmss, used as the event time) is the refund time, and whether 2C2P retries on a non-2xx answer or publishes sender addresses.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Configuration (>= 10.0.9)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Configuration.Binder (>= 10.0.9)
- Microsoft.Extensions.DependencyInjection (>= 10.0.9)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Http (>= 10.0.9)
- Microsoft.Extensions.Logging (>= 10.0.9)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Options (>= 10.0.9)
- Themia.Payments (>= 0.70.0)
-
net8.0
- Microsoft.Extensions.Configuration (>= 10.0.9)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Configuration.Binder (>= 10.0.9)
- Microsoft.Extensions.DependencyInjection (>= 10.0.9)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Http (>= 10.0.9)
- Microsoft.Extensions.Logging (>= 10.0.9)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Options (>= 10.0.9)
- Themia.Payments (>= 0.70.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.70.0 | 44 | 11/21/2026 |
| 0.69.0 | 76 | 11/18/2026 |
| 0.68.0 | 64 | 11/18/2026 |
| 0.67.2 | 77 | 11/18/2026 |
| 0.67.1 | 77 | 11/18/2026 |
| 0.67.0 | 83 | 11/17/2026 |
| 0.66.0 | 81 | 11/17/2026 |
| 0.65.0 | 139 | 11/16/2026 |
| 0.64.0 | 98 | 11/15/2026 |
| 0.63.2 | 97 | 11/15/2026 |
| 0.63.1 | 88 | 11/14/2026 |
| 0.63.0 | 84 | 11/14/2026 |
| 0.62.1 | 91 | 11/14/2026 |
| 0.62.0 | 94 | 11/14/2026 |
| 0.61.1 | 97 | 11/14/2026 |
| 0.61.0 | 93 | 11/13/2026 |
| 0.60.0 | 93 | 11/10/2026 |
| 0.59.0 | 89 | 11/10/2026 |
| 0.58.0 | 84 | 11/9/2026 |
| 0.57.2 | 104 | 11/8/2026 |