Skip to main content

Implementation & Core Methods

This page sets up the Pi SDK for subscriptions and covers the two methods every subscription app needs: subscribe, which signs a Pioneer up, and process, which collects their renewals. If you are new to subscriptions, read How Subscriptions Work first.

Note: Subscription payments are currently available only on Pi Testnet, on the first version of the Subscription contract (v1). v1 will be replaced before Mainnet: the new contract gets a new address, services must be registered again, and subscribers must subscribe again.

Limits on Testnet v1

  • The maximum billing period is ~180 days, so yearly plans aren't possible yet.
  • An approval lasts just under 180 days, however many periods it covers, so subscribe with a periods value whose renewals fit in it: 5 for a monthly plan, 25 for a weekly one. A Developer Portal month is 2,629,746 seconds (about 30.44 days). Extending starts a new approval, so ask Pioneers to extend before theirs runs out.

Table of Contents​

Prerequisites​

  • Your app is registered in the Developer Portal and runs in the Pi Browser.
  • The Pioneer's wallet is activated on Pi Testnet and holds enough Test-Pi for the price plus transaction fees.
  • The user is authenticated with the payments scope, so the Pi Wallet can sign transactions for them.
  • Subscriber methods take the subscriber's Pi Testnet wallet address (G...). Pi.authenticate doesn't return it, so for now ask the Pioneer to enter it (they can copy it from the Pi Wallet), and confirm it's theirs before you unlock anything for it: see Confirm the wallet belongs to the Pioneer. The examples on this page call it userAddress, and call your merchant wallet's address merchantAddress.
  • For merchant methods (registerService, process, getMerchantSubscriptions), the Pi Browser must be signed in with the merchant wallet, because those calls are signed by the merchant. A common setup is a small admin page in your app that you open yourself, signed in with your app's wallet. process can also run from your server instead (see From your server).

Implementation​

Initialize the Pi SDK​

Every Pi App must include the SDK script and call Pi.init() before any other SDK methods.

<head>
<!-- ... other <head> content (meta, title, styles, etc.) ... -->
<script src="https://sdk.minepi.com/pi-sdk.js"></script>
</head>
await Pi.init({ version: "2.0" });

The Subscription contract is preconfigured for Pi Testnet. You don't pass a contract address.

Execution Modes​

Every subscription method takes an optional last argument, options, with a mode:

ModeWhat happensResolves with
"simulate"Runs the call on the Pi RPC server without sending anything. No signature, no fee.The contract's return value as plain JavaScript (numbers as strings, field names in snake_case).
"submit"Opens the Pi Wallet for the user to sign, then sends the transaction to the network.The send result, an object with the transaction hash and status.

Read methods (get..., is...) default to "simulate". Write methods default to "submit".

A useful pattern is to simulate a write first and show the user a clear message if it would fail, before you open the Pi Wallet:

try {
// Dry run: nothing is signed or sent
await Pi.SmartContract.Subscription.subscribe(address, serviceId, true, "5", { mode: "simulate" });
} catch (err) {
// e.g. "... AlreadySubscribed (#3)"
return showError(err.message);
}

// Looks good: now ask the user to sign
const submitted = await Pi.SmartContract.Subscription.subscribe(address, serviceId, true, "5");

Waiting for a Transaction​

In "submit" mode a method resolves as soon as the transaction is sent, not when it is confirmed. Wait for the result with Pi.SmartContract.pollTransaction before you update your UI:

// Thrown when the transaction was sent but isn't confirmed yet. It can still succeed.
class PendingTransactionError extends Error {
constructor(hash) {
super(`Transaction ${hash} is not confirmed yet`);
this.hash = hash;
}
}

async function waitForTransaction(submitted) {
const result = await Pi.SmartContract.pollTransaction(submitted.hash); // checks up to 10 times
if (result.status === "SUCCESS") return result;
if (result.status === "FAILED") throw new Error(`Transaction ${submitted.hash} failed`);
// Still NOT_FOUND after the last check: the outcome isn't known yet
throw new PendingTransactionError(submitted.hash);
}

Only FAILED means the transaction failed. If pollTransaction still answers NOT_FOUND after its last check, the transaction was sent but isn't confirmed yet, and it can still succeed. Don't treat that as a failure and don't ask the user to sign again: keep the hash, show a pending state, and call pollTransaction with the same hash again a little later.

The examples below use this waitForTransaction helper.

Core Methods​

Most apps need only these two: subscribe signs a Pioneer up (and takes the first payment, unless there's a free trial), and process collects every renewal after that. The methods on the Additional Methods page support them.

subscribe​

Subscribes the user to a service. The Pi Wallet asks the user to approve the subscription and, when needed, the allowance in one signature.

Pi.SmartContract.Subscription.subscribe(
subscriber: string,
serviceId: string | bigint,
autoRenew: boolean, // true = keep renewing, false = one period (or trial) only
periods: string | bigint, // number of future periods to pre-approve, must be > 0
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>

periods decides how much the contract may later take for renewals: price × periods. Pass a value whose renewals fit in one approval, which lasts just under 180 days, counting from the end of any trial: 5 for a monthly plan without a trial, 25 for a weekly one. The periodsFor helper below works it out. Don't pass the service's approve_periods: the Developer Portal registers 1 for monthly plans and 4 for weekly, which would pre-approve only that many renewals. periods is required even when autoRenew is false; pass "1" in that case.

What happens depends on whether the user can still get a free trial:

Free trial availableautoRenewPaid nowPre-approved for renewalsAfter that
yestruenothingprice × periodsprocess charges each period after the trial ends
yesfalsenothingnothingEnds when the trial ends
notruefirst period's priceprice × periodsprocess charges each following period
nofalsefirst period's priceprice × 1Ends after the paid period unless extended

A free trial is only granted on the user's first subscription to a service. Cancelling and subscribing again does not give a second trial.

// How many periods fit in one approval (just under 180 days), counting from the end of any trial
const APPROVAL_SECS = 180 * 86_400;
function periodsFor(service) {
const fit = Math.floor((APPROVAL_SECS - 1 - Number(service.trial_period_secs)) / Number(service.period_secs));
return String(Math.max(1, fit)); // 5 for a monthly plan without a trial, 25 for a weekly one
}

async function subscribeToPlan(userAddress, serviceId) {
const service = await Pi.SmartContract.Subscription.getService(userAddress, serviceId);

const submitted = await Pi.SmartContract.Subscription.subscribe(
userAddress,
serviceId,
true, // auto-renew
periodsFor(service), // renewals that fit in one approval
);
await waitForTransaction(submitted);

// Confirm on-chain before unlocking the feature
const active = await Pi.SmartContract.Subscription.isSubscriptionActive(userAddress, serviceId);
if (active) unlockPremium();
}

The call fails with AlreadySubscribed if the user already has a subscription to this service that is still renewing or still within its paid period. Once it has ended, they can subscribe again.

Confirm the wallet belongs to the Pioneer​

A wallet address a Pioneer types in can be anyone's, and read methods such as isSubscriptionActive answer for any address. Don't unlock anything for an address on its own. Link it to the Pioneer when they subscribe through your app instead: subscribe is signed in their Pi Wallet, so only the owner of that address can complete it.

  1. After subscribe succeeds, send its transaction hash (submitted.hash) to your backend, together with the Pioneer's uid.
  2. On your backend, look the transaction up on Pi Testnet, for example at https://api.testnet.minepi.com/transactions/ followed by the hash. Check that it succeeded, that its source account is the address, and that it called subscribe on the Subscription contract for your service.
  3. Store the address with the Pioneer's uid. From then on, check isSubscriptionActive only for that stored address.

process​

Collects the payments that are due for one of your services. For each auto-renewing subscription whose next_charge_ts has passed, the contract moves price from the subscriber's wallet to yours and pushes the subscription forward by one period.

Renewals never happen by themselves. The contract only charges a subscriber when you call process, and every process call is a transaction that the merchant wallet has to sign. How you sign it is the main decision on this page, because there are two ways to run process:

From the Pi Browser (client side)From your server (server side)
PackagePi SDK, already in your app: Pi.SmartContract.Subscription.processPi server SDK: pi-backend for Node.js, or the pinetwork gem for Ruby
Where it runsInside your app, in the Pi BrowserOn your own backend server, with no browser
Who signsYou, by hand: the Pi Wallet opens and you enter the merchant wallet's passphraseYour server, automatically, with the merchant wallet's secret seed
Needs a personYes, every single timeNo, once it is set up
Can run on a scheduleNoYes, for example every 24 or 12 hours
SetupNone: open a page in your app and tap a buttonInstall a package, store the secret seed safely, schedule a job
Good forTrying subscriptions out, testing, collecting renewals by hand once in a whileRunning a real subscription business

Which one do I need?​

The client side method is the easiest way to start. If your app already runs in the Pi Browser, process is one more SDK call: open your admin page signed in with the merchant wallet, tap a button, enter the passphrase in the Pi Wallet, done. Nothing to install, and the secret never leaves the Pi Wallet. Use it to test your service and to see how processing works.

But it only runs when a person runs it. Every call opens the Pi Wallet and waits for someone to type the merchant wallet's passphrase. Nobody can do that at 3 a.m., and nobody should have to do it every day for every service. That matters, because:

  • each renewal can only be collected for one period after it is due. Miss that window and the contract turns the subscription's auto-renew off, so that subscriber stops paying you;
  • renewals fall due at different times for different subscribers, depending on when each one subscribed, so they have to be collected regularly, not once a month.

The server side method solves that. Your server holds the merchant wallet's secret seed and signs the process call itself, so a scheduled job can collect renewals every 24 hours, every 12 hours, or whatever your billing period needs, without anyone opening the Pi Browser. If you sell subscriptions to real users, use the server side method.

Client sideServer side
You only want to test subscriptions, or process now and then by handYes, use thisOptional
Real users pay you on a schedule (weekly or monthly plans)Not enough on its ownYes, use this
You don't run a backend serverYes, your only option, so process by hand at least once per periodNeeds a server

You can use both: the server side job for regular collection, and the client side button on your admin page for an extra run by hand. Running process twice is safe. A subscription that was already charged for this period is simply skipped.

From the Pi Browser​

Pi.SmartContract.Subscription.process(
merchant: string, // the merchant wallet's address (G...), the one signed in
serviceId: string | bigint,
offset: string | number | bigint, // where to start in the subscription list
limit: string | number | bigint, // how many subscriptions to handle in this call
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>

To run it, open your app in the Pi Browser signed in with the merchant wallet (usually an admin page that only you use). Each submit opens the Pi Wallet, and you approve it by entering the merchant wallet's passphrase.

A single transaction can only handle a limited amount of work, so process works in batches. Use offset and limit to walk through the list, and simulate first to learn the total:

async function collectRenewals(merchantAddress, serviceId) {
const BATCH = 20;

// Simulate once to learn how many subscriptions the service has
const preview = await Pi.SmartContract.Subscription.process(merchantAddress, serviceId, 0, BATCH, {
mode: "simulate",
});
// preview: { charged: 0, failed: 0, skipped: 20, total: 55 } (u32 counters come back as numbers)

for (let offset = 0; offset < preview.total; offset += BATCH) {
// Opens the Pi Wallet: enter the merchant wallet's passphrase to approve each batch
const submitted = await Pi.SmartContract.Subscription.process(merchantAddress, serviceId, offset, BATCH);
await waitForTransaction(submitted);
}
}

In "simulate" mode, process resolves with the batch's result (ProcessResult), as in the preview above. In "submit" mode it resolves with the transaction's status and hash, like every write, so wait for it with waitForTransaction; to see a batch's counters, simulate it first. The server SDKs return the counters after a submit too. ProcessResult has four counters:

CounterMeaning
chargedSubscriptions charged in this call.
failedSubscriptions that were due but could not be charged. The contract turned their auto-renew off.
skippedSubscriptions that were not due yet, already ended, or not auto-renewing. Nothing happened to them.
totalHow many subscriptions the service has in all. Use it to know when to stop paging.

Note: A "simulate" call only previews these counters. It returns charged: 1 when one subscriber would be charged, but nobody is charged until you run the call in "submit" mode.

From your server​

The Pi server SDKs run the same process call without the Pi Browser. On your server they:

  1. build the process call for your merchant wallet,
  2. sign it with the merchant wallet's secret seed, which replaces typing the passphrase in the Pi Wallet,
  3. send it straight to the Pi Testnet RPC server and wait for the result.

The contract can't tell the two methods apart: it receives the same call, signed by the same merchant wallet, and charges the same subscriptions.

Step 1: Install the package​
LanguagePackageVersion with processInstallRequirements
Node.jspi-backend1.x (npm tag next)npm install pi-backend@nextNode.js 20 or later
Rubypinetwork0.2.0.pre.1 (prerelease)gem 'pinetwork', '0.2.0.pre.1' in your Gemfile, then bundle installSame as earlier versions

Apps already using these packages for App-to-User payments are not affected: their current versions keep working, and installing without a version keeps giving them those versions.

Step 2: Store the merchant secret seed safely​

The server needs the secret seed of the merchant wallet, the wallet that registered the service and receives the payments. A secret seed is 56 characters long and starts with S. It is a different form of the wallet's passphrase: anyone who has it can spend everything in the wallet. Treat it like a bank password.

If your merchant wallet is your app's wallet, this is the same wallet private seed you use for App-to-User payments with these packages, so you may have it already.

Important: don't process and pay out from the same wallet at the same time. Every transaction from a wallet uses that wallet's next sequence number. If process and an App-to-User payment are sent from the same wallet at the same moment, they get the same number and only one of them goes through. A process that loses fails with transaction_rejected (txBadSeq), or ends in transaction_not_confirmed (NOT_FOUND) after about 3 minutes. Either way that batch didn't run and can be run again. Run your process job when your server isn't sending payouts, or use a separate wallet for one of them.

Keep the secret seed in an environment variable on your server, never in your code. In these examples the variable is called PI_MERCHANT_SECRET.

On your own computer (development). Put it in a file named .env in your project folder:

# .env
PI_MERCHANT_SECRET=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Then make sure that file is never committed to git:

echo ".env" >> .gitignore

Load it when your program starts:

# Node.js 20.6 or later reads .env files natively (on older versions, use the dotenv package)
node --env-file=.env collect-renewals.mjs
# Ruby: add gem 'dotenv' to your Gemfile, then at the top of your script
require 'dotenv/load'

On your production server. Don't upload the .env file. Set the variable in your hosting provider's secret settings instead, for example "Config Vars" on Heroku, "Environment Variables" on Render, Railway or Vercel, or a secret manager such as AWS Secrets Manager or Google Cloud Secret Manager. Your code reads it the same way in both places:

// Node.js
const merchantSecret = process.env.PI_MERCHANT_SECRET;
if (!merchantSecret) throw new Error("PI_MERCHANT_SECRET is not set");
# Ruby: raises KeyError if the variable is missing
merchant_secret = ENV.fetch("PI_MERCHANT_SECRET")

Rules for the secret seed:

  • Keep it on the server only. Never put it in your frontend code, in your Pi App, in a URL, or in a response your server sends to a browser.
  • Never commit it to git, paste it in chat, or print it in logs. If it ever leaks, move the funds to a new wallet right away.
  • Give access only to the people and services that need it.
  • Keep only the Pi you need for fees in the merchant wallet, and move your earnings to another wallet regularly. That limits the damage if the server is ever compromised.
Step 3: Call process​

Node.js

SmartContract.Subscription.process(
merchantSecret: string, // the merchant wallet's secret seed (S...)
serviceId: IntegerInput,
offset: IntegerInput, // where to start in the subscription list
limit: IntegerInput, // how many subscriptions to handle in this call
options?: ProcessOptions
): Promise<ProcessSubmitResult> // with options.mode "simulate": Promise<ProcessResult>

type IntegerInput = string | number | bigint; // a number, a bigint or a string of digits

type ProcessOptions = {
mode?: "simulate" | "submit"; // default "submit"
rpcUrl?: string; // default: Pi Testnet RPC
networkPassphrase?: string; // default: "Pi Testnet"
contractAddress?: string; // default: the Pi Testnet Subscription contract
timeoutSecs?: number; // how long the transaction stays valid, 1 to 4294967295, default 180
};

type ProcessSubmitResult = { txid: string; ledger: number; result: ProcessResult };

The return type follows mode, so TypeScript code can read preview.total or outcome.txid without narrowing. All of these types are exported from pi-backend.

There is no merchant address argument: the SDK derives it from the secret seed, so the call always runs as the wallet that owns the secret.

// collect-renewals.mjs
import { SmartContract, PiSubscriptionError } from "pi-backend";

const merchantSecret = process.env.PI_MERCHANT_SECRET;
const serviceId = "0"; // your service_id
const BATCH = 20;

export async function collectRenewals() {
// Preview without signing or sending: total is how many subscriptions to page through
const preview = await SmartContract.Subscription.process(merchantSecret, serviceId, 0, BATCH, { mode: "simulate" });

for (let offset = 0; offset < preview.total; offset += BATCH) {
try {
// "submit" is the default: signs with the secret seed, sends, and waits for the result
const { txid, result } = await SmartContract.Subscription.process(merchantSecret, serviceId, offset, BATCH);
console.log(txid, result); // { charged, failed, skipped, total }
} catch (err) {
if (err instanceof PiSubscriptionError && err.code === "transaction_not_confirmed") {
// Sent, but the outcome is unknown: look up err.txid before running this batch again
}
throw err;
}
}
}

await collectRenewals();

Ruby

PiNetwork::SmartContract::Subscription.process(
merchant_secret, # the merchant wallet's secret seed (S...)
service_id, # Integer or String of digits
offset, # where to start in the subscription list
limit, # how many subscriptions to handle in this call
mode: :submit, # :simulate or :submit
rpc_url: "https://rpc.testnet.minepi.com",
network_passphrase: "Pi Testnet",
contract_address: "CCUF75B6W3HRJTJD6O7OXNI72HGJ7DERZ5MUNOMFMSK23ME5GUIKPFYV",
timeout_seconds: 180 # how long the transaction stays valid, 1 to 4294967295
)
# An option passed as nil uses its default, the same as leaving it out.
# mode: :simulate => { charged:, failed:, skipped:, total: }
# mode: :submit => { txid:, ledger:, result: { charged:, failed:, skipped:, total: } }
# collect_renewals.rb
require 'dotenv/load'
require 'pinetwork'

merchant_secret = ENV.fetch("PI_MERCHANT_SECRET")
service_id = "0" # your service_id
batch = 20

preview = PiNetwork::SmartContract::Subscription.process(merchant_secret, service_id, 0, batch, mode: :simulate)

(0...preview[:total]).step(batch) do |offset|
begin
# :submit is the default: signs with the secret seed, sends, and waits for the result
outcome = PiNetwork::SmartContract::Subscription.process(merchant_secret, service_id, offset, batch)
puts "#{outcome[:txid]} #{outcome[:result]}"
rescue PiNetwork::Errors::SubscriptionError => e
if e.code == :transaction_not_confirmed
# Sent, but the outcome is unknown: look up e.txid before running this batch again
end
raise
end
end

What the server method does, in order:

  1. Checks the arguments. Nothing is sent if one is invalid.
  2. Derives the merchant address from the secret seed, loads the account and builds the process call.
  3. Simulates it. With the simulate mode it stops here and returns the counters the call would produce. Nothing is signed or charged.
  4. With the submit mode (the default) it signs the call with the secret seed, sends it, waits for the result and returns the transaction id (txid), its ledger and the counters.

A successful submit always includes a txid. If you get counters but no txid, the call was only simulated and nobody was charged.

Errors come back with a code you can act on, for example simulation_failed with the contract's reason (for example NotServiceOwner), transaction_rejected with the network's reason (txInsufficientBalance), or transaction_not_confirmed with the txid when the outcome is unknown. Each package's README lists every code.

Step 4: Run it on a schedule​

Run your collect-renewals script on a timer. How often depends on the service's billing period. The hard rule is at least once per period, because a renewal can only be collected for one period after it is due. Running more often than that is better: a missed or failed run then still leaves time for the next one, and subscribers are charged closer to their due time. Running often costs nothing extra in charges, since subscriptions that are not due are skipped.

Billing periodRun process every
Monthly (about 30.44 days)24 hours
7 days (weekly)12 to 24 hours
1 day (daily)6 to 12 hours, or every hour
A few minutes (testing only)Every minute

A 12 or 24 hour schedule suits most apps. Two common ways to set it up:

Option A: cron on your server. Cron is the built-in job scheduler on Linux and macOS. Run crontab -e and add a line. This one runs every 12 hours, at midnight and noon:

# minute hour day month weekday command
0 */12 * * * cd /path/to/your/app && node --env-file=.env collect-renewals.mjs >> renewals.log 2>&1

For Ruby, use the same schedule with the Ruby command:

0 */12 * * * cd /path/to/your/app && bundle exec ruby collect_renewals.rb >> renewals.log 2>&1

For every 24 hours instead (once a day at midnight), change the schedule to:

0 0 * * * cd /path/to/your/app && node --env-file=.env collect-renewals.mjs >> renewals.log 2>&1

Most hosting providers offer the same thing as "Cron Jobs" or "Scheduled Jobs" if you can't edit the server's crontab.

Option B: a scheduler inside your app. If your server runs all the time, schedule the job in code. In Node.js, with the node-cron package (npm install node-cron), export collectRenewals from collect-renewals.mjs without the await collectRenewals() line at the bottom, then:

import cron from "node-cron";
import { collectRenewals } from "./collect-renewals.mjs";

let running = false;

// Every 12 hours, at 00:00 and 12:00
cron.schedule("0 */12 * * *", async () => {
if (running) return; // don't start a new run while the previous one is still going
running = true;
try {
await collectRenewals();
} catch (err) {
console.error("Collecting renewals failed:", err); // alert yourself here
} finally {
running = false;
}
});

In Ruby on Rails, use your job system's scheduler, for example sidekiq-cron or the whenever gem, with the same every-12-hours schedule.

Whichever option you choose:

  • Process every service you sell. Call process once per service_id. getMerchantServices lists them all.
  • Alert yourself on errors. If runs fail for longer than one period, subscribers lose their auto-renew. Check the log or send yourself a message when a run throws.

Note: The merchant wallet pays the fee for each process call. On Testnet v1 a call has cost about 0.01 to 0.02 Pi. The fee grows with the number of subscriptions in the batch and with storage rent, so keep some Pi for fees in the merchant wallet. The server SDKs add 50% headroom to the simulated resource fee; the unused part is refunded.

When a charge fails​

A charge that fails does not stop the batch. The contract turns auto-renew off for that subscription and counts it as failed. A charge fails when:

  • the subscriber's balance is too low, or their pre-approved periods are used up;
  • you are more than one full period late. If a subscription's period ended and another whole period passes before you call process, the contract refuses to charge it.

The subscriber keeps access until the end of the period they already paid for. To start paying again, they subscribe again.

Important: Run process at least once per billing period, ideally from a scheduled job using the server SDKs above. A subscription you don't process in time stops renewing.

Data Types​

Field names are snake_case, and u64/i128 numbers come back as strings; convert them with Number(...) for small values like timestamps, or BigInt(...) for amounts.

Subscription (returned by subscribe in "simulate" mode, and by the read methods on the Additional Methods page)

FieldDescription
sub_idUnique ID of the subscription.
subscriberWallet that owns the subscription.
service_idService this subscription belongs to.
pricePrice per period, copied from the service when subscribing.
period_secsBilling period, copied from the service when subscribing.
trial_period_secsTrial granted to this subscription ("0" if none).
trial_end_tsWhen the trial ends ("0" if none).
auto_renewtrue while the merchant can charge renewals.
service_end_tsWhen the current paid (or trial) period ends. The user has access until then.
next_charge_tsWhen process can next charge this subscription.
created_atWhen the user subscribed (Unix seconds).

ProcessResult (returned by process in "simulate" mode, and by the server SDKs after a submit)

FieldDescription
chargedSubscriptions charged successfully in this batch.
failedSubscriptions whose charge failed. Their auto-renew was turned off.
skippedSubscriptions that were not due yet or not auto-renewing.
totalTotal subscriptions in the service's list. Use it to plan batches.

Error Handling​

The SDK checks your arguments before it builds a transaction:

  • Addresses must be valid wallet (G...) or contract (C...) addresses, otherwise it throws an error such as "Invalid subscriber address".
  • Prices and periods must be positive; IDs must be zero or positive; offset and limit must fit in a u32. An empty string throws an error such as "Service ID is required".

When the contract rejects a call, the error message ends with the error name and code, for example ... AlreadySubscribed (#3). Simulate a write first (see Execution Modes) to catch these before the Pi Wallet opens.

Errors from subscribe​

CodeNameWhat it meansWhat to do
2InvalidPeriodperiods is 0.Pass a positive periods value, for example from periodsFor (see subscribe).
3AlreadySubscribedThe user already has a subscription to this service that is still renewing or still within its paid period.Show their current subscription instead of the subscribe button.
5ServiceNotFoundThe service_id doesn't exist.Check the ID with getMerchantServices.
8TimestampOverflowA time or amount calculation overflowed.Use smaller periods values.
12ServiceNotActiveThe merchant paused new sign-ups.Hide the subscribe button and tell the user the plan is closed for now.

If the user's wallet doesn't hold enough Pi for the first period and the fee, the transaction fails and nothing changes: no payment, no subscription.

Errors from process​

These come from Pi.SmartContract.Subscription.process in the Pi Browser, and inside simulation_failed from the server SDKs:

CodeNameWhat it meansWhat to do
5ServiceNotFoundThe service_id doesn't exist.Check the ID.
9NotServiceOwnerThe merchant wallet (or the wallet of the secret seed on your server) doesn't own this service.Use the merchant wallet that registered the service.

A charge that fails for one subscriber is not an error: the call succeeds and counts it under failed. See When a charge fails.

Errors from the server SDKs​

The server SDKs raise PiSubscriptionError (Node.js) or PiNetwork::Errors::SubscriptionError (Ruby) with one of these codes. In Ruby the codes are symbols, for example :simulation_failed.

CodeWhat it meansWhat to do
invalid_merchant_secret, invalid_service_id, invalid_offset, invalid_limit, invalid_mode, invalid_options (Node.js), invalid_timeout, invalid_rpc_url, invalid_network_passphrase, invalid_contract_addressAn argument is invalid. Nothing was sent.Fix the argument. Check that PI_MERCHANT_SECRET is set and starts with S.
account_not_foundThe merchant wallet doesn't exist on Pi Testnet.Activate the wallet, or check you are using the right secret seed.
simulation_failedThe contract refused the call. contractErrorName (Node.js) or contract_error_name (Ruby) says why, for example NotServiceOwner. Nothing was sent.See Errors from process.
state_archivedContract data the call needs is archived and must be restored first. Rare: Pi Testnet restores archived data automatically when a call uses it.Run again. If it persists, restore the data yourself: any funded wallet can send a restore transaction built from the simulation's restorePreamble (for example with Operation.restoreFootprint in @stellar/stellar-sdk).
fee_too_highThe fee is larger than one transaction can carry.Use a smaller limit.
transaction_rejectedThe network didn't accept the transaction; nothing was charged. detail has the reason: txInsufficientBalance (the merchant wallet can't pay the fee), txBadSeq (another transaction from the same wallet went first) or TRY_AGAIN_LATER (the RPC server is busy).For txInsufficientBalance, add Pi to the merchant wallet. For txBadSeq or TRY_AGAIN_LATER, run again.
transaction_failedThe transaction was included in a ledger but failed. The error's txid identifies it.Look up the txid, then run again.
transaction_not_confirmedSent, but the outcome is unknown. The error's txid identifies it.Look up the txid before running this batch again. Running it twice is safe, but costs a second fee.
unexpected_response, rpc_errorThe RPC server answered with something unreadable, or the request to it failed.An unexpected_response with a txid means the transaction was already sent and may have succeeded: look up the txid before running this batch again. Otherwise wait and run again.

The user closes the Pi Wallet​

If the user closes the Pi Wallet without signing, or the wallet fails to send the transaction, the promise rejects with a readable message. Always wrap calls in try/catch:

try {
const submitted = await Pi.SmartContract.Subscription.subscribe(userAddress, serviceId, true, "5");
await waitForTransaction(submitted);
} catch (err) {
console.error("Subscribe failed:", err.message);
showMessage("We couldn't start your subscription. Please try again.");
}

Example Usage​

A complete subscriber flow: show the plan, subscribe, and unlock the feature.

const SERVICE_ID = "0"; // your service_id from getMerchantServices

// Once, when your app loads
await Pi.init({ version: "2.0" });
await Pi.authenticate(["username", "payments"], onIncompletePaymentFound);

// waitForTransaction and PendingTransactionError: see Waiting for a Transaction above

// userAddress: the Pi Testnet wallet address (G...) the Pioneer entered.
// linkedAddress: the address your backend already confirmed for this Pioneer, or null
// (see Confirm the wallet belongs to the Pioneer).
async function startPremium(userAddress, linkedAddress) {
try {
// 1. Already subscribed? Only trust an address your backend has confirmed.
if (linkedAddress && (await Pi.SmartContract.Subscription.isSubscriptionActive(linkedAddress, SERVICE_ID))) {
return unlockPremium();
}

// Not active, but the user may still have a subscription to this plan: its period ended and
// auto-renew is on, so the renewal is due and is charged at your next process run. Subscribing
// again would fail with AlreadySubscribed, so don't offer it.
const now = Math.floor(Date.now() / 1000);
const subs = await Pi.SmartContract.Subscription.getSubscriberSubscriptions(userAddress);
const existing = subs.find(
(s) => String(s.service_id) === SERVICE_ID && (s.auto_renew || Number(s.service_end_ts) > now)
);
if (existing) return showMessage("Your renewal is being processed. Access resumes once it is charged.");

// 2. Show the plan
const service = await Pi.SmartContract.Subscription.getService(userAddress, SERVICE_ID);
if (!service.is_active) return showMessage("This plan is closed to new subscribers.");

const pricePi = Number(service.price) / 10_000_000;
const days = Number(service.period_secs) / 86_400;
const confirmed = await askUser(`Subscribe to ${service.name} for ${pricePi} Pi every ${days} days?`);
if (!confirmed) return;

// 3. Dry run, then subscribe
const periods = periodsFor(service); // see subscribe
await Pi.SmartContract.Subscription.subscribe(userAddress, SERVICE_ID, true, periods, { mode: "simulate" });
const submitted = await Pi.SmartContract.Subscription.subscribe(userAddress, SERVICE_ID, true, periods);
await waitForTransaction(submitted);

// 4. Your backend checks the transaction, links userAddress to this Pioneer and confirms the
// subscription is active (see Confirm the wallet belongs to the Pioneer). Unlock only then.
if (await linkWalletOnBackend(submitted.hash)) unlockPremium();
} catch (err) {
if (err instanceof PendingTransactionError) {
// Sent but not confirmed yet: keep err.hash and check it again later, don't subscribe again
return showMessage("Your subscription is being confirmed. Check back in a minute.");
}
showMessage(`Subscription failed: ${err.message}`);
}
}

function onIncompletePaymentFound(payment) {
// see the Payments page
}

To collect the renewals of these subscribers automatically, add the scheduled job from Step 4: Run it on a schedule to your server.

Implementation checklist​

When adding subscription payments to an app:

  1. Load https://sdk.minepi.com/pi-sdk.js and call Pi.init() before any other SDK methods.
  2. Authenticate with the payments scope.
  3. Register each plan once in the Developer Portal (your app, Subscription Services, Register New Service), and note its service_id. Calling registerService directly instead leaves the plan unlinked to your app in the Pi Wallet.
  4. Show the plan with getService, then call subscribe with a periods value whose renewals fit in one approval (just under 180 days): 5 for monthly, 25 for weekly.
  5. Link the wallet address to the Pioneer on your backend from the subscribe transaction, before unlocking anything for it (see Confirm the wallet belongs to the Pioneer).
  6. After every write, wait for the transaction with pollTransaction before updating the UI. Only FAILED is a failure; NOT_FOUND after the last check means pending.
  7. Gate paid features with isSubscriptionActive, and check it on your backend for anything valuable.
  8. Run process at least once per billing period, in batches: from a scheduled job with the Node.js or Ruby server SDK, or from the Pi Browser signed in with the merchant wallet.
  9. Give users a page to view, extend, turn off auto-renew, or cancel their subscriptions (see Additional Methods).

Next​

Continue with Additional Methods to manage your plans and give Pioneers a page to manage their subscriptions.