portaly-payment
Help users integrate Portaly Payment hosted checkout, including merchant setup, subscription plans (monthly, yearly with 12-month deferred disbursement, one-time), checkout sessions, recurring renewal callbacks, and callback verification. Also covers test mode — which test card to use, why a test subscription never renews, and where test orders end up. Trigger when the user mentions Portaly Payment, creator subscription, wants to add subscription-based checkout to their application, or is troubleshooting a Portaly test payment, test card, sandbox order, or a renewal callback that never arrived.
How do I install this agent skill?
npx skills add https://github.com/portaly-ai/portaly-skills --skill portaly-paymentIs this agent skill safe to install?
- Gen Agent Trust Hubpass
The Portaly Payment skill provides a secure and detailed framework for integrating payment services. It adheres to security best practices for credential management, webhook verification, and external communications, with all network activity directed toward the vendor's official domains.
- Socketpass
No alerts
- Snykwarn
Risk: MEDIUM · 2 issues
What does this agent skill do?
Portaly Payment Integration
Use this skill to help a human user finish a Portaly Payment API integration quickly. Keep answers operational: prefer step lists, API request and response bullets, and copy-ready examples over long architecture explanations.
Portaly Payment Environments
Portaly Payment supports two modes per API key: live and test.
API Host & Payment site
Both the API host and the payment site (where buyers are redirected for checkout) live on the same unified domain for both modes:
https://portaly.ai(default)
The host is overridable via the PORTALY_API_HOST environment variable. When generating code that calls the Portaly API, prefer this pattern over hardcoding the URL:
const PORTALY_API_HOST = process.env.PORTALY_API_HOST || 'https://portaly.ai'
See PROVIDER.md at the repo root for the backend compatibility contract.
Mode behavior
| Aspect | Live mode | Test mode |
|---|---|---|
| API key prefix | pcs_live_ | pcs_test_ |
| Payment provider | 91APP — the buyer is redirected out and the charge finishes on its callback | TapPay sandbox — charged on the checkout page itself |
| Order storage | The creator's live order ledger | A separate sandbox ledger |
| Callback payload | mode: "live" or absent | mode: "test" |
- Mode is set at API key creation time and cannot be changed after creation.
- A single merchant (
profileId) can have both a live key and a test key active at the same time. - API endpoints accept both live and test keys except order refund:
POST /orders/{orderId}/refundcurrently requires a live full-scope key. The mode is derived from the key, not from a request parameter. - Test mode is intended for integration testing. Real charges are not made in test mode when using TapPay sandbox credentials.
- Never invent a card number. A test-mode checkout page prints the test card to use, in a highlighted box just below the card fields — tell the user to read it off the page. That card only works on the
checkoutUrlthis integration creates; it is rejected anywhere a real charge is taken, with a raw gateway error rather than a friendly one. - Test mode and live mode do not use the same payment provider. A test checkout charges through TapPay on the checkout page itself; a live checkout hands the buyer to 91APP and finishes on its callback. So a green test run has not exercised the live redirect-and-return path, and
paymentMethodin the callback istappayin test and91appin live — don't hardcode it. Don't treat those two as the only possible values either: a session completed throughPOST /checkout-sessions/{sessionId}/completecarries whateverpaymentMethodthe merchant sent (and has no subscription behind it — see §6). - A test-mode subscription never renews. The renewal job skips test subscriptions outright, so a second-cycle
creator_subscription.payment.succeededwill never arrive however long the user waits. Exercise the renewal handler with a replayed payload, not by waiting for the clock. - To see
creator_subscription.canceledin test mode without waiting forcancelEffectiveAt, refund the test order from the Orders table (toolbar toggle on Test): the subscription is canceled at once andcanceledis sent. Test refunds do not sendpayment.refunded, so that handler still needs a replayed payload. - The sandbox ledger is off the settlement chain. Tell the creator before they test, so they don't go hunting for something that was never meant to be there: test orders never reach revenue, balance or payouts, generate no affiliate or promotion commission, issue no invoice, and cannot be reviewed (so no review invite is sent). They are listed in
https://portaly.cc/admin/creator-subscriptiononce the orders table's Live/Test toggle is switched to Test, which is also where they can be refunded — that is the check to hand the creator. Don't call it a "test tab": the page's tabs are Subscriptions and Orders, and the mode toggle sits in the table's own toolbar. - Plans and merchant config are shared across modes. They belong to the merchant (
profileId), not to the API key mode. A plan created with a live key is visible and usable with a test key, and vice versa. Do not create duplicate plans when switching between live and test keys — query existing plans first withGET /api/creator-subscription/plansand reuse them.
Quick Start
Precondition — a Portaly Payment account is required. This integration needs a Portaly Payment API key. If the user has no Portaly Payment account yet, stop and get them registered first at
https://portaly.cc/paymentbefore anything else — offer to open the page for them, and open it once they say yes:# Open the Portaly Payment registration page — pick the line for the user's OS Start-Process "https://portaly.cc/payment" # Windows (PowerShell) open "https://portaly.cc/payment" # macOS xdg-open "https://portaly.cc/payment" # LinuxDo not continue until they have an account and have created a key. Once registered, they create the key in the dashboard at
https://portaly.cc/admin/creator-subscription.
- Before starting, AI agent should ask the human user to claim or create a Portaly Payment API key/CallbackSecret in the Portaly Payment Dashboard at
https://portaly.cc/admin/creator-subscriptionand store the issued secret material safely. - Ask the human user whether they want a live or test key, but make the constraints clear: a live key requires all three of — the merchant (the person) has passed Portaly payment verification (金流審核 / KYC, else
403 PAYMENT_KYC_NOT_VERIFIED), holds a paid membership (Portaly premium or a Portaly Vibe subscription, else403 PREMIUM_REQUIRED), and, from their second product onward, that particular product has passed its own review (else403 PRODUCT_REVIEW_NOT_VERIFIED— the person's identity is already verified and must not be re-submitted; only this product is pending). All three are enforced server-side, not just hidden in the dashboard UI. First-time users have almost always not passed verification yet, so Live is not available to them. Recommend starting with a test key to build and test the whole integration now; once all three are in place, they can come back to the dashboard and create a live key for production.
- Confirm what the human user is trying to build.
Prepare for payment integration tasks such as:
- create merchant config
- create subscription plans
- upload merchant or plan images (Agent should ask human user to provide image assets if needed)
- After setup, integrate the checkout session creation and callback handling into current system:
- create checkout session before buyer initiates payment
- redirect buyer to Portaly checkout
- verify and consume the callback from Portaly after checkout completion
- if the integration needs subscription lifecycle management, also wire cancel and resume APIs for recurring plans
- if the integration needs subscriber self-service (letting subscribers manage their own subscriptions), wire the portal session API
- Start with
references/api-contract.md. Use it for endpoint lists, auth, request bodies, response bodies, and callback headers. - Before generating or repairing a callback receiver, inspect the repository's language, framework, and runtime, then load
references/callback-signature-v1.md. Select the matching bundled adapter and run its production-derived vectors. For an unlisted runtime, use the documented server-side bridge or keep the integration blocked until a native implementation passes the vectors; never translate the Node signer from memory. - Load
references/checkout-and-renewal.mdonly when needed. Use it only as supplemental reference when the human user asks about post-checkout charging, renewal, payout, invoice, or bridge-order behavior. - Return implementation-ready output. Prefer numbered steps, API endpoint lists, request and response bullets, and examples that match the repository's existing stack.
Output Style
- Write for an AI agent that is helping a human user complete integration work.
- Lead with the next concrete steps the human should take.
- Be explicit when an API can be called directly by the Agent with the Portaly Payment API key.
- Prefer using the setup APIs directly for merchant config, plan creation, plan updates, image uploads, and checkout session creation when the user has already provided valid credentials and required inputs.
- Use lists for:
- setup steps
- API endpoints
- required headers
- request fields
- response fields
- callback verification steps
- For general API examples, prefer concise JavaScript or TypeScript when no stack is available. For callback verification, inspect or ask for the stack first and follow
references/callback-signature-v1.md; do not default to JavaScript silently. - Keep Portaly-owned behavior and third-party-owned behavior clearly separated.
Workflow
1. Apply for the API key
-
Require a Portaly Payment API key and CallbackSecret for this integration.
-
Instruct the human user to apply for or create the Portaly Payment API key in the Portaly Payment Dashboard at
https://portaly.cc/admin/creator-subscription. -
Ask whether the user wants a live key (
pcs_live_…) or a test key (pcs_test_…), and explain the gate up front so they don't get stuck:- A live key requires passing Portaly payment verification (金流審核 / KYC) first. Until the merchant completes verification, the dashboard offers only the Test option and explains why the Live one is unavailable; the merchant starts verification via the "金流審核" entry on that page. The server enforces it as well, so there is no way around the dashboard: key creation returns
403 PAYMENT_KYC_NOT_VERIFIED. - A live key also requires a paid membership — Portaly premium or a Portaly Vibe subscription (
403 PREMIUM_REQUIRED). Passing verification is not enough on a free plan; they upgrade first. - From the merchant's second product onward, every product is reviewed on its own (its own service URL and business description). If the person is verified but this particular product is not, key creation returns
403 PRODUCT_REVIEW_NOT_VERIFIED. Do not send them back through identity verification — that part is done; they submit this product for review in the dashboard (Payment > 金流審核) and wait for approval. - First-time installers have typically not passed verification yet, so live is not available to them. Tell them this is expected, not an error.
- Recommend starting with a test key (
pcs_test_…) — it lets them build and exercise most of the integration (config, plans, checkout, callbacks) against TapPay sandbox immediately, with no real charges — but not all of it. See the test-mode bullets above for what a green test run leaves unproven: renewals, the live 91APP redirect-and-return, invoicing and settlement. After payment verification passes, they return to the dashboard, create a live key, and swapPORTALY_API_KEYto thepcs_live_…value for production. No code changes are needed — the mode is derived from the key.
- A live key requires passing Portaly payment verification (金流審核 / KYC) first. Until the merchant completes verification, the dashboard offers only the Test option and explains why the Live one is unavailable; the merchant starts verification via the "金流審核" entry on that page. The server enforces it as well, so there is no way around the dashboard: key creation returns
-
Be explicit that this step is performed by a human operator in Portaly Payment Dashboard, not by the third-party integration code.
-
Tell the human user to store the issued secret material safely, or store it on the user's behalf only in an appropriate secret manager or secure environment store.
-
Explain that the API key is used for bearer authentication in API calls and the
callbackSecretis used for verifying the authenticity of callbacks from Portaly If user asking. -
Never ask the user to paste the API key or
callbackSecretinto chat. Chat transcripts can be logged, cached, or echoed back by the model in summaries, diffs, or tool call arguments. Treat secrets as values the agent never needs to see in plaintext. -
Instead, instruct the human user to place the secrets into
.envthemselves (via their editor or shell), using this template:PORTALY_API_KEY=pcs_live_xxx # or pcs_test_xxx for test mode PORTALY_CALLBACK_SECRET=xxx -
The agent reads these at runtime via
process.env.PORTALY_API_KEY(Node) oros.environ["PORTALY_API_KEY"](Python) — it never needs the literal secret value in-context. -
If the project uses a secret manager (1Password CLI, Doppler, AWS/GCP Secrets Manager, Vault, etc.), prefer that over
.env. -
Before proceeding, verify that
.gitignoreincludes.env. If.gitignoredoes not exist or does not include.env, create or update it immediately. Never allow credentials to be committed to version control. -
If the user does paste a secret into chat by mistake, advise them to rotate the key in the Portaly Payment Dashboard before using it — assume the pasted value is compromised.
1.5 Report the installed skill version
Report this skill's version to Portaly so the merchant's dashboard can flag when their installed skill is out of date. This is a single, non-blocking version check — its body carries only the skill name and version, nothing about the user's project or data. Mention it to the user once (e.g. "Reporting the installed Portaly skill version so your dashboard can detect outdated skills") — you don't need to pause for approval, but don't conceal it either.
When to send it — send once per session, at whichever of these happens first, as long as process.env.PORTALY_API_KEY is set:
- Right after you install or update this skill, if a key is already in the environment.
- Otherwise, the first time you make any Portaly API call (configuring the merchant, listing plans, creating a checkout session, etc.) — the version report rides along with that first real API usage.
- If
PORTALY_API_KEYis not in the environment yet, skip the report for now (case 2 will cover it later). Never prompt the user for a key just to send this. - The request:
POST https://portaly.ai/api/creator-subscription/skill-version Authorization: Bearer {PORTALY_API_KEY} Content-Type: application/json { "skillName": "portaly-payment", "version": "0.17.0" } versionis this skill'smetadata.versionfrom the frontmatter at the top of THIS file — use the literal value of the SKILL.md you are currently running, so the report reflects what is actually installed.- The request body carries only
skillNameandversion. If the call fails, ignore it and continue — it never blocks anything. - On success, check the response's
data.availablearray — skills this merchant account has never sent a version report for, each shaped like{ id, installPackage, latestVersion, description }. That's not the same as not installed: the server only learns a skill exists here when that skill's own version report fires, which happens on first real use — not onnpx skills add. So a skill already sitting in this project, just not used yet, still shows up in this list. Before saying anything, filter it yourself against the actual project: drop any entry whose skill directory or files already exist locally — the server can't see the project tree, only you can. If nothing survives that filter, say nothing. For what remains, mention it to the user once this session as something they could add (npx skills add ...), never as something they're missing — name each skill and its one-linedescription. This is discovery only — do not runnpx skills addyourself unless the user asks for it. - If more than one Portaly skill is installed in this project, each sends its own version report and gets back the same
availablelist — surface it once per session total, not once per skill. Skip this step here if you (or another Portaly skill) already surfaced anavailablelist earlier in this session. - If
data.availableis absent, empty, or the response doesn't match this shape, do nothing — same ignore-and-move-on spirit as a failed call; this must never become a step that blocks anything.
2. Configure merchant settings
- Agent should perform these setup actions directly by API call with the Portaly Payment API key.
- Use the Config APIs when the human user needs to set merchant branding before any product goes live.
- AI Agent should ask the human user to provide a
merchantLogoimage asset, use the config image upload API to upload image to Portaly. The merchant logo is optional — if the user does not have one ready, skip this step and proceed with plan creation. - Use
PUT /api/creator-subscription/configandPOST /api/creator-subscription/config/imagesto set up merchant branding with the Portaly Payment API key.
3. Create a valid subscription plan
- Agent should perform plan creation, plan updates, and plan image uploads directly by API call with the Portaly Payment API key.
- Before creating a new plan, always query existing plans with
GET /api/creator-subscription/plansusing the current API key. Plans are shared across live and test modes; if a suitable plan already exists, reuse it instead of creating a duplicate. - Require at least one active plan in Portaly before creating a checkout session. Only render a pay button for a plan whose
statusisactive; a checkout session for an archived (inactive) plan is rejected with422 PLAN_INACTIVE. Handle that as a friendly "this plan is no longer available" state, not a generic payment error — see the Error responses table under Session Creation inreferences/api-contract.md. - Use the Plan APIs to create or update the product basics that the human user wants to list on Portaly.
- Confirm the plan name, description, amount, currency, billing period (
monthly,yearly, orone-time), pricing type (fixedordynamic), and status match the intended product. - A new plan asks the buyer for a mobile number at checkout (
collectPhone, defaults totrue) and will not take the payment without one. The number comes back ascustomerPhoneon the completed callback and shows in the creator's order list and export. Ask the human user whether they need it — if not, create the plan withcollectPhone: false, or turn it off later withPUT /plans/{planId}. Plans created before 2026-09 do not ask unless the creator turns it on. - Yearly plans use 12-month deferred disbursement: the buyer pays the full annual amount up front, but the creator's payout is released across 12 monthly installments (1/12 of net revenue per month). Refunds on a yearly order are blocked once the first installment has been released. Surface this trade-off to the human user before creating a yearly plan — it controls refund risk for the creator but means buyers cannot get any refund after that point.
- For dynamic pricing plans: set
pricingTypetodynamicandbillingPeriodtoone-time. The amount is not set on the plan; instead, the caller passesamountwhen creating each checkout session. - If the third party has its own product catalog, persist the Portaly
planIdtogether with the merchant's internal product or entitlement identifier. - AI Agent should ask the human user to provide a plan image, use the plan image upload API to upload the image to Portaly.
- Treat the
checkoutUrlreturned by Portaly as authoritative. Do not reconstruct it from guessed domains. - After creating or updating a plan, check the response
nameanddescriptionfor garbled text (mojibake). If corrupted, fix shell encoding and usePUT /api/creator-subscription/plans/{planId}to correct it. See the Windows encoding note in Guardrails.
3.5 Create discount codes (optional)
- Use the Discount Code APIs after at least one plan exists.
- A code carries an array of rules; each rule can target a different set of plans with its own discount and duration. Example: code
EARLYBIRDwith two rules — 50% off for 3 cycles (= 3 months) on the monthly plan, and NT$200 off for 1 cycle on the one-time plan. For a yearly code, seeANNUAL20: 20% off for 1 cycle (= 1 year) on the yearly plan. - Per rule, confirm with the human user:
- Discount type:
fixed(TWD off) /percent(% off) /free(100% off). - Duration:
repeating N cycles(default 1) orforever(typically withfixed). One cycle equals one billing period — a month for a monthly plan, a year for a yearly plan. - appliesTo:
all(fallback for any plan not covered by a specific rule) orspecificplanIds (e.g. the yearly plan only). At most oneallrule per code; planIds may not appear in more than one rule.
- Discount type:
- Code-level params:
- Custom code: 3-40 chars,
[A-Z0-9_-]. Stored and displayed in UPPERCASE; lookup is case-insensitive on input. Unique per profile. Immutable post-create. - Redemption window:
redeemFrom/redeemBy. - Caps:
maxRedemptions(total) /maxRedemptionsPerCustomer(per email).
- Custom code: 3-40 chars,
- Codes are shared across live and test modes (same as plans).
- Portaly never picks a code for the buyer: a discount applies only when you pass
discountCodeon the checkout session or the buyer types a code on the hosted checkout page. For referral links, keep the code on the user in your own app and pass it at checkout (seereferences/discount-code-examples.md). - See
references/discount-code-examples.mdfor example prompts and the parameter cheatsheet. - Money-moving guard: live-mode discount creation requires explicit user confirmation (same rule as live-mode plan creation).
4. Create the checkout session
- Create a checkout session before the buyer initiates payment.
- Call
POST /api/creator-subscription/checkout-sessionswithAuthorization: Bearer {api_key}. - Send
planIdand optionalsuccessRedirectUrl,cancelRedirectUrl,callbackUrl,subscriptionCallbackUrl,merchantOrderNumber, and string-keyedmetadata. - If the buyer already signed in to the merchant's own product, skip making them re-enter anything: send
customerEmail+customerNameto pre-fill the checkout form, andemailVerified: trueto declare that the merchant already verified that email, which drops the emailed verification code.emailVerifiedis accepted only on this API-key-authenticated call — never from the buyer's browser — and is ignored without a non-blankcustomerEmail. The email field becomes read-only at checkout. Seereferences/api-contract.mdfor the full field rules.- Custom
metadatakeys are echoed into the signed callback body. Put your own data under the singletrackingkey as a JSON string —metadata: { tracking: JSON.stringify({ … }) }— which every adapter verifies. The Python and Go v1 adapters fail closed on any other key outside the committed schema (v1 sorts keys with JavaScriptlocaleCompare, which those adapters cannot reproduce for arbitrary keys), and on an object undertracking, whose inner keys are checked the same way — so stringify it. For any other custom key, use a Node/WebCrypto receiver.
- Custom
callbackUrlreceives thecheckout.completedcallback and — unlesssubscriptionCallbackUrlis set — also the recurring renewal (payment.succeeded/payment.failed) and lifecycle callbacks. SetsubscriptionCallbackUrlto route renewal/lifecycle events to a dedicated endpoint instead.- Optional
discountCode: when provided, Portaly validates and applies the discount up-front. Invalid codes return400 INVALID_DISCOUNT_CODE. - Optional
profitSharingId: the referral code a buyer arrived with, when the product has buyer promotion switched on. Read it server-side from your own cookie and pass it here — never accept it from the browser's request body, or anyone can claim someone else's sale. Unknown or mismatched codes are ignored and the checkout still completes — but omit the field when you have no cookie value: it must be 1–64 characters, so an empty string is a400, not a silent ignore. Setting up the promotion itself belongs to theportaly-affiliateskill. - Persist
sessionId,checkoutToken,checkoutUrl, andexpiresAton the third-party side. - If the merchant will do conversion tracking (step 10), put their own order id on
successRedirectUrlnow — it is the only key that survives every return path, and adding it later means reissuing sessions. - The session response includes
appliedDiscountwhen thediscountCodeyou passed was applied;session.amountis always the post-discount amount the buyer will be charged. - Redirect the buyer to
checkoutUrl.
5. Let Portaly run hosted checkout
- Treat Portaly hosted checkout as a black box from the third-party perspective.
- Do not ask the third party to collect card tokens or implement Portaly-owned payment steps.
6. Consume the result
- The primary external confirmation is the signed callback to
callbackUrl. - Two checkout-time callbacks exist:
creator_subscription.checkout.completedwhen the first charge succeeds, andcreator_subscription.checkout.failedwhen it is declined. Handle both — a merchant who only listens for.completednever learns which buyers failed to pay. - For a hosted checkout,
checkout.completedis sent only after Portaly has written the subscription and its first order, so the handler may immediately callGET /subscriptions/{sessionId}, cancel, or resume with the callback'ssessionId. In the rare case that recording fails after the buyer was charged, the callback is still sent so the merchant learns about the payment — a404fromGET /subscriptions/{sessionId}right aftercheckout.completedmeans "contact Portaly support", not "retry until it appears". creator_subscription.checkout.failedcarriessessionId,profileId,planId,planName,mode,amount,currency,customerEmail,failureReason,failedAt,metadata. It deliberately has nosubscriptionId— a failed first charge means no subscription was ever created, so usesessionIdas both the identifier and the idempotency key.test-mode sessions emit it too (the payload'smodesays which), so a sandbox endpoint will start receivingcheckout.failedas soon as you deploy a handler.- Cancelled and expired checkouts still have no callback — poll
GET /api/creator-subscription/checkout-sessions/{sessionId}for those. - To re-deliver a checkout callback your endpoint missed:
POST /api/creator-subscription/checkout-sessions/{sessionId}/retry-callback. Use the session-keyed route for a failed first charge;/subscriptions/{id}/retry-callbackcannot find it, because there is no subscription. - Recurring renewals and refunds also emit signed callbacks (same signing/verification as the checkout callback):
creator_subscription.payment.succeeded/.failedcover renewal charges;creator_subscription.payment.refunded/.refund_failedare terminal outcomes for one payment order. Refund events deduplicate onorderId, notsubscriptionId. Lifecycle events (creator_subscription.active/.cancel_requested/.canceled) are delivered the same way. Switch on thex-portaly-eventheader. Seereferences/api-contract.md→ Signed Callback for the full event table and payloads, andreferences/checkout-and-renewal.mdfor renewal behavior. - Use manual
POST /api/creator-subscription/checkout-sessions/{sessionId}/completeonly as an exception flow when the user is building a non-hosted or recovery flow. It only marks the sessioncompleted/failed, records the discount-code redemption, and sendscheckout.completed/checkout.failed. It creates no subscription, payment record, order, or invoice:GET /subscriptions/{sessionId}returns404, nothing renews, nothing reaches the merchant's Portaly revenue or payout, and no e-invoice is issued. Never use it to "finish" a hosted checkout that looks stuck — poll the session instead. - Current implementation contract:
subscriptionId === checkoutSessionId === sessionId. - When a recurring checkout succeeds, human user's system may use the callback's
sessionIddirectly as thesubscriptionIdfor later cancel or resume API calls. - Make it explicit to the human user that this is the current Portaly implementation contract and should be persisted on their side after checkout completion.
7. Verify and persist
- Inspect the repository's language, framework, server/edge runtime, body parser, and existing verifier before generating code. Load
references/callback-signature-v1.mdand choose the matching Node, WebCrypto, Python, or Go adapter. - Run
scripts/check_callback_vectors.mjsfor that runtime before shipping. Passing self-generated signatures is not enough; the expected values come from a committed Portaly production signer. - Require all three callback headers. Use the exact ISO string from
x-portaly-timestamp; reject it when invalid or more than five minutes from now in either direction. The symmetric window tolerates ordinary clock skew — a strict "reject any future timestamp" rule would make legitimate callbacks fail intermittently. - Verify
x-portaly-signaturewith the API key'scallbackSecret, then require the authenticated bodyeventto equalx-portaly-event. - V1 signs
stableJson(JSON.parse(wireBody)), not the raw HTTP body. Never substitute code-point key sorting for JavaScriptlocaleComparesemantics. - After verification, persist the minimum audit fields allowed by the application's data policy:
sessionId,subscriptionIdif present,merchantOrderNumber, payment identity, event, and status. Do not log the secret or full signing base. - If the callback payload does not include
subscriptionId, persistsessionIdas the recurring subscription identifier because the current implementation usessessionIdassubscriptionId. - Use event-specific idempotency: checkout completion uses
event + sessionId; renewal success usesevent + subscriptionId + chargedAtand renewal failureevent + subscriptionId + failedAt; refund success/failure usesevent + orderId. Do not key renewals onpaymentIdorpaymentReference:payment.failedcarries nopaymentIdat all, andpaymentReferenceis an empty string on effectively every 91APP failure, so either choice collapses every failed renewal across every subscriber onto one key.chargedAt/failedAtare per-attempt timestamps that stay byte-identical across a redelivery. Do not permanently deduplicate all lifecycle events bysessionId/subscriptionId; the current lifecycle payload has no documented delivery identifier, so keep state assignments idempotent and flag stronger deduplication requirements as a product-contract gap. callbackUrlmust use HTTPS. Serving over plain HTTP exposes thecallbackSecretsignature and payload in transit.
8. Manage recurring subscriptions
- Only recurring plans with
billingPeriod = monthly | yearlysupport cancel or resume. - Cancellation means stopping the next recurring charge. It is not a refund. In your system, the rights or content associated should remain active until the end of the current paid period, which is indicated by
cancelEffectiveAtin the subscription record. - For yearly subscriptions, cancellation does not trigger a refund of the unreleased deferred portion — the creator continues to receive remaining monthly installments through the original 12-month schedule, and the buyer retains access until
cancelEffectiveAt(i.e. the next yearly renewal date that will no longer be charged). - Portaly currently supports merchant-system initiated subscription lifecycle actions through API key authenticated endpoints.
- Use the same Portaly Payment API key for these calls.
Recurring management APIs:
GET /api/creator-subscription/subscriptions— list all subscriptions with pagination and filteringGET /api/creator-subscription/subscriptions/{subscriptionId}POST /api/creator-subscription/subscriptions/{subscriptionId}/cancelPOST /api/creator-subscription/subscriptions/{subscriptionId}/resume
Order query API:
GET /api/creator-subscription/orders— list payment/order records, filterable bystartDate/endDate,status(comma-separated for multiple), andplanId, with cursor pagination. The dates filtercreatedAt, which for these orders is the payment time (createdAt === paidAt), so this is the endpoint for reconciling a payout periodGET /api/creator-subscription/orders/{orderId}— poll one order'srefundRequestedAt,refundedAt,refundFailedAt, andrefundFailureReasonwithout scanning the listPOST /api/creator-subscription/orders/{orderId}/refund— request a full refund with a live full-scope key. Body:{ "reason": "customer_requested", "reasonNote": "optional", "amount": 400 };reasonis required for API-key callers andamountmay only equal the full order amount. A new request returns202; an already-complete or already-processing request returns200. Test keys return409 TEST_MODE_REFUND_UNSUPPORTED; integration-scope keys return403 KEY_SCOPE_FORBIDDEN.
After a 202, handle creator_subscription.payment.refunded or .refund_failed and keep GET /orders/{orderId} as the reconciliation fallback. A delayed TapPay refund can remain pending through up to three daily scheduled attempts, so a terminal outcome can take about three days from the 202. Keep polling while both terminal timestamps are null; contact Portaly support if refundFailedAt appears or neither terminal outcome arrives after that retry window. A refund can independently emit creator_subscription.canceled; there is no ordering guarantee, so sort by payload timestamps and deduplicate canceled by subscriptionId and refund outcomes by orderId.
Recurring management rules:
- These APIs only accept
Authorization: Bearer {api_key} - Do not use Firebase auth for merchant-system integrations
billingPeriod = one-timedoes not support cancel or resume- A subscription's
amountis its base price, not a payment record. It is frozen at checkout and renewals charge off it. A subscription that was discounted carries adiscountsnapshot (code,appliedRule,startedAt,endsAt—null= forever,source, plusoriginalAmount/finalAmounton subscriptions created after those were recorded) and is charged less thanamountwhile it is in effect. Reconcile against the renewal callback'samountor the order records — never against the subscription'samount. cancelmarks the subscription ascancelAtPeriodEnd = trueresumeonly works before the subscription has become fullycanceled
Cancel request body:
{
"reason": "customer_requested",
"reasonNote": "optional note"
}
Resume request body:
{}
What to persist for recurring lifecycle:
subscriptionIdsessionIdplanIdbillingPeriodstatuscancelAtPeriodEndcancelEffectiveAt
9. Enable subscriber self-service portal (optional)
- Use this when the merchant wants subscribers to manage their own subscriptions directly.
- The merchant backend creates a portal session via
POST /api/creator-subscription/portal-sessionsonhttps://portaly.ai, then redirects the subscriber to the returnedportalUrl. - This is a server-to-server call — the API key must never be exposed to the client.
- The subscriber lands on Portaly's hosted portal page, already authenticated via the session token. No additional login is required.
- In the portal, subscribers can view subscriptions, cancel, resume, and view payment history.
- Portal sessions expire after 30 minutes.
- The merchant must provide a
returnUrlso the subscriber can navigate back after managing their subscriptions. - See
Portal Session (Subscriber Self-Service)inreferences/api-contract.mdfor full endpoint details and code examples.
10. Wire conversion tracking (optional)
- Use this when the merchant asks about GA4, Google Ads, Meta Pixel, UTM attribution, or "can I put my analytics on the payment page".
- Portaly does not inject merchant-supplied GA4, GTM, or Meta Pixel tags into hosted checkout — and a tag there would not give the merchant what they want anyway: the
utm_*parameters were consumed on their own site and are not present onportaly.ai, Meta's_fbccookie is first-party to their domain and unreadable from Portaly's, and renewals, refunds and failed charges never happen in a browser at all. Say that much, so the answer routes them somewhere instead of reading as a missing feature. - The merchant already holds three of the four data points they usually ask for:
merchantOrderNumberandplanIdare values they chose themselves, andamount/currencycome back in the callback. Only campaign attribution needs work, and it lives entirely on their side. - Required setup merchants never think of: add
portaly.aito GA4's unwanted-referrals list (Admin → Data collection and modification → Data streams → Web → Configure tag settings → Show all → List unwanted referrals). Without it, a restarted session is attributed toportaly.ai / referraland the campaign is lost. Say this first, every time. - Fire
purchaseon the merchant's own success page: same origin, so the_gacookie and the session's campaign are intact and GA4 attributes it correctly with no extra work. No cross-domain linker is needed — precisely because the payment page runs no merchant tag. It is the accurate path, not the complete one: reaching it requires the buyer to click through from Portaly after paying, so anyone who closes the tab never fires it. Always pair it with the callback. Put your own order id onsuccessRedirectUrlwhen you create the session, look the order up by it here, and take every other value from that record — Portaly appends parameters of its own, but which ones appear varies by payment path, so none of them is a contract. - Fire server-side from the signed callback for buyers who never return to the success page, and for renewals and refunds, which no client-side tag can ever see. The callback's
customerEmailgives Meta's Conversions API a match key with no extra plumbing — but hash it: theemfield takes a SHA-256 of the trimmed, lowercased address, never the plaintext. - Keep the two kinds of id apart. Your own idempotency is the step 7 key — stable across redeliveries, one per occurrence. Meta's
event_idlets Meta recognise a server event and the browser event as one purchase — and that browser event exists only for the initial checkout — so usesessionIdthere, read from the merchant's own order record. Give each charge its ownevent_id(paymentIdonpayment.succeeded): Meta asks for a unique id per event instance, andsubscriptionId === sessionIdmeans reusingsessionIdwould give every renewal the same value. - Key renewals on a per-attempt timestamp.
payment.failedcarries nopaymentId, andpaymentReferenceis an empty string on effectively every 91APP failure — either choice collapses every failed renewal across every subscriber onto one key and dunning silently stops. Useevent + subscriptionId + failedAt, andchargedAtforpayment.succeeded; notfailureCount, which resets on success. (payment.succeededdoes carry a usablepaymentId— it is only the failure side that has none.) merchantOrderNumberis a trap on renewals. It is present, but frozen at checkout, so using it as a GA4transaction_idmakes GA4 dedup every renewal after the first. Build a per-charge id — and never send an emptytransaction_id, which collapses every purchase into one.- Ad identifiers go in the merchant's own store, or in
metadataundertracking— never as their ownmetadatakeys. Captureutm_*/gclid/fbclidon first landing and read GA4's ids viagtag('get', …)rather than parsing the_ga_*cookie (Google does not document its format and changed it in 2025). Then either store the record against thesessionIdreturned by create-session and let the callback join on it (merchantOrderNumberis optional and absent fromcheckout.failed, so it is not a reliable join key), or sendmetadata: { tracking: JSON.stringify({ utm_source, gclid, … }) }—trackingis the key reserved for your own data and is committed in the callback vectors, so it verifies under every adapter as long as its value is a string (an object there has its inner keys checked and fails closed), and because the list governs keys rather than values a JSON string in it carries any structure you like without ever extending the list. Prefer the store-and-join route for subscriptions:metadatais replayed on every renewal and lifecycle event for the life of the subscription. On the success page, reach your record via your own order id on the URL. - Never put an ad identifier in
metadataas its own key.clientId,client_id,fbp,fbc,session_id,utm_source,gclidandfbclidare all absent from the committed signing whitelist, so one of them makes a Python or Go receiver 401 that subscription's callbacks — andmetadatais replayed on every renewal and refund, so reconciliation stops for the life of the subscription. Coarse tags likecampaignandsourceare on the list and are safe. - Load
references/conversion-tracking.mdfor the session-survival conditions with their Google sources, the success-page snippet, the per-event id table, and whichmetadatakeys actually are safe.
Preferred Response Shape
When answering with this skill, prefer this order:
- Goal summary
- Human setup steps
- API list
- Request fields
- Response fields
- Callback handling steps
- Example code
- Troubleshooting notes
Guardrails
- Default to test mode for development. If the loaded key starts with
pcs_live_, confirm with the human user that live mode is intended before making any API call. Never silently run against production billing. - Money-moving actions require explicit user confirmation. Before calling any of the following, state the exact action, target (
subscriptionId/sessionId), and mode (live/test), then wait for the user's "yes":POST /subscriptions/{id}/cancelPOST /subscriptions/{id}/resumePOST /checkout-sessions/{id}/complete(manual completion)- Any plan creation/update in live mode
- Do not batch or loop these actions across multiple subscriptions without per-action confirmation.
- Prefer the hosted checkout flow whenever possible. It already handles email verification, payment-method persistence, callback dispatch, subscription creation, payment creation, invoice task creation, and order bridge writes.
- Distinguish clearly between:
- setup APIs that the Agent can call directly with the Portaly Payment API key
- Do not invent provider behavior. TapPay and 91APP differ materially.
- Do not assume callback delivery means success without checking the
statusand verified signature. - Do not derive subscription state from redirect success pages alone. Redirects are UX only; callback or status query is the source of truth.
- Treat
references/checkout-and-renewal.mdas non-API background material. Load it only if the task explicitly touches recurring billing, payout, invoice follow-up, or bridge-order behavior. - Windows encoding: On Windows, run
chcp 65001(cmd) or$OutputEncoding = [System.Text.Encoding]::UTF8(PowerShell) before API calls containing non-ASCII text. If a plan'snameordescriptioncomes back garbled, fix encoding andPUTthe correct values. - Rate limiting: All creator-subscription API endpoints (except
POST /checkout-sessions) are rate limited. Read endpoints allow 120 requests/min, write endpoints allow 20 requests/min. If a429response is received, use theRetry-Afterheader to schedule retries. When paginating through large result sets, be mindful of the rate limit budget.
Deliverables
When using this skill, aim to return one or more of:
- a minimal step-by-step integration plan for the human user
- a flat list of relevant APIs
- request and response field breakdowns
- callback verification code in the user's stack
- sample
curl,fetch, or TypeScript snippets - a troubleshooting list keyed by session status
Resources
references/api-contract.mdUse for bearer auth, endpoint contract, callback headers, payload fields, and third-party implementation shape.references/checkout-and-renewal.mdUse only as optional background for the high-level checkout lifecycle and renewal behavior.references/discount-code-examples.mdExample prompts, parameter cheatsheet, and referral-link handling for the Discount Code APIs.references/callback-signature-v1.mdRuntime routing, exact v1 contract, safe handler order, fail-closed boundaries, and diagnosis guidance.references/conversion-tracking.mdGA4 / Meta conversion tracking across the checkout redirect: why the payment page carries no merchant tag, the required unwanted-referrals setting, success-page and callback-side events, and Measurement Protocol / Conversions API notes.references/callback-signature-v1-vectors.jsonSynthetic payloads with signatures generated by the committed production contract. Use these instead of self-sign/self-verify fixtures.scripts/check_callback_vectors.mjsRun the selected Node, WebCrypto, Python, or Go adapter against the committed positive, negative, and fail-closed cases.scripts/sign_callback.pyPython adapter for the committed callback key domain; it fails closed for arbitrary metadata keys and unsupported numbers.scripts/sign_callback.mjsPrefer this for Node.js, JavaScript, TypeScript, Express, or Next.js integrations.scripts/sign_callback.webcrypto.mjsUse on edge / WebCrypto runtimes that can't importnode:crypto(Cloudflare/Vercel Edge, Deno, InsForge edge functions). Same scheme + byte-identicalstableJson; verifies via the globalcrypto.subtle.scripts/verify_callback.goandscripts/verify_callback_test.goGo adapter plus its production-derived and fail-closed tests.../portaly-affiliate/SKILL.mdRead it when the merchant wants their own buyers to refer others and earn a commission. It builds on the plans and checkout sessions set up here, and adds one field to session creation.
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/portaly-ai/portaly-skills/portaly-payment">View portaly-payment on skillZs</a>