",
},
});
```
On failure, `makeRequest` throws a `ResponseNotOkError` with the response status:
| Status | Description |
| --- | --- |
| 401 | Invalid wallet secret |
| 404 | Session not found |
| 500 | Internal server error |
### Step 3: Track completion
Once confirmed, use [`waitForSession`](/typescript/wait-for-session) to wait for the settlement transaction to complete:
```ts
const completedSession = await waitForSession(config, {
sessionId: session.sessionId,
});
console.log("Withdrawal settled:", completedSession.sponsoredTransactionHash);
```
You can also configure webhooks to track completion server-side — see the [Payments guide](/guides/payments#webhooks) for details.
## Building the Withdrawal UI
You are responsible for building the withdrawal UI in your app — typically a simple form where the user picks the chain and currency they want to receive, and enters their destination wallet address.
To populate the chain and currency pickers, use the [listSupportedChains](/typescript/list-supported-chains) and [listSupportedCurrencies](/typescript/list-supported-currencies) actions. Use `currency.on(chain)` to get the CAIP-19 ID for the `settleCurrency` parameter. Note that withdrawals are currently EVM only, so filter for chains whose `id` starts with `eip155:`.
---
# Testing [Develop your Glide integration without moving real funds]
## Use testnets
Glide supports testnets alongside mainnets. Testnet chains are exported from `@paywithglide/glide-js/chains` just like mainnets — configure them the same way:
```ts [config.ts]
export const config = createGlideConfig({
projectId: "your-project-id",
chains: [baseSepolia, ethereumSepolia],
});
```
Sessions created against testnet chains behave exactly like mainnet sessions — same statuses, same payment actions, same webhooks — but use testnet funds from a faucet.
To discover available testnets programmatically, pass `all: true` to [`listSupportedChains`](/typescript/list-supported-chains) and filter on `isTestnet`:
```ts
const chains = await listSupportedChains(config, { all: true });
const testnets = chains.filter((chain) => chain.isTestnet);
```
The same flag exists on [`listSupportedCurrencies`](/typescript/list-supported-currencies) for testnet tokens. See [Supported chains & tokens](/resources/supported-chains-and-tokens) for the full list, including virtual testnets.
## Dry mode
[`createPaymentSession`](/typescript/create-payment-session) accepts a `dryMode` flag that creates the session for testing without processing a real payment — useful for exercising your session-handling code end to end:
```ts
const session = await createPaymentSession(config, {
paymentCurrency: usdc.on(base),
settleCurrency: usdc.on(polygon),
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
paymentAmount: "100",
dryMode: true,
});
```
## Testing cheaply on mainnet
For an end-to-end test of the real thing, small amounts on low-fee chains (like Base) keep the cost of a full payment-to-settlement round trip to a few cents. The [quickstart](/quickstart) script is a good harness: run it with a small `paymentAmount`, pay the deposit address from any wallet, and watch the statuses progress.
## Testing webhooks
Run your webhook endpoint locally by exposing it with a tunnel (e.g., `ngrok` or `cloudflared`) and pointing a webhook at the tunnel URL in the Glide Dashboard. Remember to verify the `X-Glide-Signature` header even in development — see [Webhooks](/webhooks).
---
# Error Handling [Handle every failure mode of the Glide SDK]
Every error the SDK throws is a typed error class exported from `@paywithglide/glide-js`, so you can branch on failure modes with `instanceof`:
```ts
createSession,
executeEVMSession,
NoPaymentOptionsError,
SessionExpiredError,
SponsoredTransactionFailedError,
InsufficientPaymentAmountError,
} from "@paywithglide/glide-js";
try {
const session = await createSession(config, { ... });
await executeEVMSession(config, { session, ... });
} catch (e) {
if (e instanceof NoPaymentOptionsError) {
// The user has no balance that can cover this transaction
} else if (e instanceof SessionExpiredError) {
// Create a fresh session and let the user retry
} else if (e instanceof InsufficientPaymentAmountError) {
// The amount paid was too low; the payment will be refunded
} else if (e instanceof SponsoredTransactionFailedError) {
// Settlement failed; contact Glide support with the session ID
} else {
// The user rejected in their wallet, a network error, etc.
throw e;
}
}
```
## Error reference
### Session lifecycle
**`SessionExpiredError`** — the session expired (or is within 30 seconds of expiring) before the payment was completed. Thrown by `executeEVMSession`, `executeSolanaSession`, and `waitForSession`. **Recovery:** create a new session and let the user retry — quotes are only valid for the session's lifetime.
**`SponsoredTransactionFailedError`** — the settlement transaction on the destination chain failed. Thrown by `waitForSession` (and the execute actions, which wait internally). **Recovery:** this is rare and terminal for the session; surface it to the user and contact Glide support with the session ID.
**`InsufficientPaymentAmountError`** — the amount paid doesn't cover the required payment amount, and the payment is queued for refund (`paymentStatus` becomes `pending_refund`). Thrown by `waitForSession`, `payWithTransfer`, and other actions when the backend reports it. **Recovery:** the payer is refunded automatically; create a new session for another attempt.
**`PaymentPendingError`** — the payment hasn't been detected or confirmed yet. Thrown by `payWithTransfer`, `payWithCoinbaseOnramp`, and `payWithCoinbaseApp`. **Recovery:** retry after a short delay — `waitForTransfer` does exactly this loop for you.
**`TransactionNotFoundError`** — the payment transaction hash can't be found on chain yet. Thrown by `updatePaymentTransaction` and the pay actions. **Recovery:** the transaction may not have propagated yet; retry with a short delay (the execute actions retry this for up to a minute internally).
### Session creation
**`NoPaymentOptionsError`** — thrown by `createSession` when no `paymentCurrency` was specified and the user has no balance that can cover the transaction. **Recovery:** prompt the user to fund their wallet, or use `listPaymentOptions` with `includeInsufficientBalanceOptions: true` to show what they could pay with.
**`GlideOverCapacityError`** — Glide is temporarily over capacity for the requested route. **Recovery:** retry later.
**`CurrencyNotSupportedError`** — thrown by a currency's `on(chain)` or `contractAddressOn(chain)` helper when the currency doesn't exist on that chain. **Recovery:** only offer chain and currency combinations returned by [`listSupportedCurrencies`](/typescript/list-supported-currencies).
### Transport
**`ResponseNotOkError`** — the catch-all for any non-OK API response that doesn't map to a more specific error. It exposes `statusCode` (the HTTP status) and `response` (the raw body) for debugging:
```ts
if (e instanceof ResponseNotOkError) {
console.error("Glide API error", e.statusCode, e.response);
}
```
**Recovery:** a `4xx` usually means invalid parameters — check `response` for the reason; a `5xx` is safe to retry.
## Wallet errors
Errors from the user's wallet — rejecting a transaction or signature, or failing to switch chains — are thrown by the callbacks you pass to `executeEVMSession`/`executeSolanaSession` (e.g., wagmi's `UserRejectedRequestError`), not by Glide. Handle them alongside the Glide errors in your catch block; the session remains valid until it expires, so the user can simply retry.
---
# Webhooks [Track payments server-side as they progress]
Glide can publish webhooks to your server as a session progresses — from creation to final settlement. Events fire for every session regardless of how it was created: through the [embedded widgets](/guides/embed-glide-pay) or the [headless SDK](/quickstart).
Webhooks are the recommended way to track money movement in production: unlike client-side polling, they keep working if the user closes the tab, and they let your backend be the source of truth for order fulfillment and balance updates.
## Setup
Head over to the Webhooks page in the [Glide Dashboard](https://buildwithglide.com) and add a webhook pointing to an HTTPS endpoint on your server.
## The event
Glide sends a `SESSION_UPDATE` event every time a session changes. The payload is the full session object — the same shape returned by [`getSessionById`](/typescript/get-session-by-id):
```json
{
"webhookId": "d5fa3629-9187-4ca6-9f2b-d70f7816ce4b",
"entityId": "a44ac1a5-5b73-4cbe-83a1-7e937189d470",
"type": "SESSION_UPDATE",
"payload": {
"sessionId": "a44ac1a5-5b73-4cbe-83a1-7e937189d470",
"paymentStatus": "paid",
"sponsoredTransactionStatus": "success",
"sponsoredTransactionHash": "0x36145cfe...",
"metadata": "{\"orderId\":\"order-12345\"}"
// ... the full session object
}
}
```
- **`webhookId`** — unique ID for this delivery. Use it to deduplicate.
- **`entityId`** — the ID of the entity the event is about (the session ID for `SESSION_UPDATE`).
- **`payload`** — the full session object. See [Sessions](/sessions) for the field reference and status lifecycles.
## Verify the signature
Every delivery includes an `X-Glide-Signature` header: the hex-encoded HMAC-SHA256 of the raw request body, keyed with the Webhook Signing Secret from the Glide Dashboard. Always verify it before processing the payload.
```ts [server.ts]
const app = express();
app.post(
"/glide-webhook",
// Verify against the *raw* body — parsing and re-serializing
// JSON can change the bytes and break the signature
express.raw({ type: "application/json" }),
(req, res) => {
const signature = req.header("X-Glide-Signature");
const expected = crypto
.createHmac("sha256", process.env.GLIDE_WEBHOOK_SECRET!)
.update(req.body)
.digest("hex");
if (
!signature ||
signature.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
) {
return res.status(401).send("Invalid signature");
}
const event = JSON.parse(req.body.toString());
if (event.type === "SESSION_UPDATE") {
const session = event.payload;
// Handle the update, e.g. fulfill the order when settled
}
res.status(200).send("ok");
},
);
```
## Handling events reliably
- **Treat delivery as at-least-once.** The same update can arrive more than once — deduplicate by `webhookId`, and make your handlers idempotent (fulfilling the same order twice should be a no-op).
- **Don't rely on ordering.** Process events based on the session state in the payload, not the order deliveries arrive in.
- **Act on the settled signal.** `paymentStatus: "paid"` together with `sponsoredTransactionStatus: "success"` means the money has fully arrived — that's the signal to fulfill an order or credit a balance.
- **Correlate with your own records.** Set the `metadata` field when creating the session (e.g., your order ID) and read it back from the payload, or key off `sessionId`.
- **Respond quickly.** Return a `200` as soon as the event is persisted, and do heavy work asynchronously.
## Webhooks vs. polling
Client-side, [`waitForSession`](/typescript/wait-for-session) is often all you need — it polls until settlement and works great for showing live status in your UI. Use webhooks whenever the outcome matters to your backend: order fulfillment, balance crediting, or any flow where the user may leave before settlement completes. The two complement each other — poll for UI feedback, webhook for the source of truth.
---
# List payment options
Lists the payment options available for a transaction for the user's wallet based on their balance across chains and tokens and the required transaction amount.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const fabricAbi = [/* your contract's ABI */];
const paymentOptions = await listPaymentOptions(config, {
chainId: base.id,
account: "0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625",
evm: {
address: "0x1169c6769c4F4B3cA1944AF0F26B36582fd5279d",
value: 999999907200n,
data: encodeFunctionData({
abi: fabricAbi,
functionName: "mintFor",
args: ["0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625", 999999907200n],
}),
},
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The CAIP-2 chain ID of the chain where the transaction will be executed (e.g., `eip155:8453` for Base). Use the `id` field of a chain imported from `@paywithglide/glide-js/chains`.
The wallet address that will be used to pay for the transaction. If set, only the payment options for which the user has a balance will be returned.
The EVM transaction to be executed on the destination chain. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The contract's address, or the recipient's address if the transaction is not a contract call.
Value in the smallest unit (ex. wei) to be sent with the transaction.
The encoded calldata for the transaction. Use viem's `encodeFunctionData` to encode a contract call.
The approval object, required if the transaction requires spending of an ERC-20 token. Contains `token` (the token's contract address as `Hex`) and `amount` (the amount to approve, as `bigint` in the token's smallest unit).
The Solana transaction to be executed on the destination chain. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The base64-encoded Solana transaction message to be executed.
A simple token transfer to be executed on the destination chain, instead of a contract call. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The token to send to the recipient on the destination chain.
The address that will receive the tokens.
The amount to transfer, in a human-readable format.
List of payment currencies that should be considered for the transaction, either in the CAIP-19 format or as currency objects imported from `@paywithglide/glide-js/currencies`. Cannot be used with paymentChainIds.
List of CAIP-2 chain IDs that should be considered for the transaction. Cannot be used with paymentCurrencies. Defaults to the chains set in the config.
The commission amount in USD that will be added on top of the transaction cost and will be paid out to the developer.
Commission rates per currency tier (`tier1`, `tier2`, `tier3`) that will be added on top of the transaction cost and paid out to the developer, as a percentage of the transaction amount (e.g., `"0.5"` = 0.5%). Cannot be used with commissionUSD.
When set to true, payment options for which the user does not have a sufficient balance are also returned, with `hasSufficientBalance` set to false. Defaults to false.
A Coinbase OAuth access token. When provided, the user's Coinbase account balances are also considered as payment options.
List of CAIP-2 chain IDs to exclude from the returned payment options.
List of currency tiers to exclude from the returned payment options.
The amount of native gas currency to send to the user on the destination chain along with the transaction, in a human-readable format.
## Return Type
Returns an array of payment options, each with the following fields:
The account of the user that will pay for the transaction.
The currency in which the user pays in CAIP-19 format.
The payment amount required for the transaction in the payment currency, in a human-readable format.
The payment amount required for the transaction in USD.
The user's current balance of the payment currency, in a human-readable format.
The user's current balance of the payment currency in USD.
The name of the payment currency.
The symbol of the payment currency.
The URL of the payment currency's logo.
The CAIP-2 chain ID of the chain on which the user pays.
The name of the chain on which the user pays.
The URL of the chain's logo.
The estimated amount required to complete the transaction in the transaction currency.
The currency required by the transaction to be executed, in CAIP-19 format.
The estimated amount required to complete the transaction in USD.
The name of the transaction currency. Ex. "Ethereum".
The symbol of the transaction currency. Ex. "ETH".
The URL of the transaction currency's logo.
The total fee covering the relayer fee and the destination transaction gas cost paid by the relayer, in USD.
Boolean indicating whether the user has sufficient balance to pay for the transaction.
---
# Create session [Create a new Glide session to make a cross-chain, cross-token, or gasless payment]
A Glide session should be created once a user has shown intent to pay for a transaction using Glide.
A session is valid for 10 minutes, during which the user should complete the payment process. If the user does not complete the payment within this time, the session will expire and the user will need to create a new session. If a payment is made for an expired session, the payment will be refunded automatically.
Once a session is created, use the [`executeEVMSession`](/typescript/execute-session) action to complete the payment process.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const fabricAbi = [/* your contract's ABI */];
const session = await createSession(config, {
chainId: base.id,
account: "0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625",
paymentCurrency: usdc,
evm: {
address: "0x1169c6769c4F4B3cA1944AF0F26B36582fd5279d",
value: 999999907200n,
data: encodeFunctionData({
abi: fabricAbi,
functionName: "mintFor",
args: ["0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625", 999999907200n],
}),
},
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The CAIP-2 chain ID of the chain where the transaction will be executed (e.g., `eip155:8453` for Base). Use the `id` field of a chain imported from `@paywithglide/glide-js/chains`.
The wallet address that will be used to pay for the transaction. Required when `paymentCurrency` is not set, so the best payment option can be selected based on the user's balances.
The currency in which the user pays, either in the CAIP-19 format or as a currency object imported from `@paywithglide/glide-js/currencies`. Defaults to the first currency returned by `listPaymentOptions` for the user's account.
The amount the user wants to pay, denominated in the paymentCurrency, can be set for transactions that support variable payment amounts (ex. p2p transfers).
The amount the user wants to pay, denominated in USD. Alternative to paymentAmount.
How the user pays for the session: `wallet`, `transfer`, `coinbase_onramp`, `coinbase_app`, `moonpay`, `onramp`, or `onramper`. Defaults to `wallet`.
When set to true and if supported by the payment currency, the user will be able to pay with a signature only, requiring no gas. Defaults to false.
The EVM transaction to be executed on the destination chain. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The contract's address, or the recipient's address if the transaction is not a contract call.
Value in the smallest unit (ex. wei) to be sent with the transaction.
The encoded calldata for the transaction. Use viem's `encodeFunctionData` to encode a contract call.
The approval object, required if the transaction requires spending of an ERC-20 token. Contains `token` (the token's contract address as `Hex`) and `amount` (the amount to approve, as `bigint` in the token's smallest unit).
The Solana transaction to be executed on the destination chain. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The base64-encoded Solana transaction message to be executed.
A simple token transfer to be executed on the destination chain, instead of a contract call. Exactly one of `evm`, `solana`, or `transfer` must be provided.
The token to send to the recipient on the destination chain.
The address that will receive the tokens.
The amount to transfer, in a human-readable format.
The commission amount in USD that will be added on top of the transaction cost and will be paid out to the developer.
Commission rates per currency tier (`tier1`, `tier2`, `tier3`) that will be added on top of the transaction cost and paid out to the developer, as a percentage of the transaction amount (e.g., `"0.5"` = 0.5%). Cannot be used with commissionUSD.
The wallet secret that was used when creating the wallet. Required if the `account` wallet was created on Glide.
Custom string metadata to attach to the session (e.g., order ID, user ID, JSON-encoded objects).
The amount of native gas currency to send to the user on the destination chain along with the transaction, in a human-readable format.
When set to true and the payment method is `transfer`, any amount deposited to the deposit address is accepted, instead of requiring the exact payment amount.
An identifier for generating a stable deposit address. When the payment method is `transfer`, providing a consistent key ensures the same deposit address is returned for repeat sessions.
The wallet address that owns the deposit. Used with transfer payments to attribute the deposit address to a specific user.
When set to true, the payer will receive an email if their payment is refunded.
The email address of the payer, used for refund notifications.
Configuration for Glide-hosted payment pages. Contains an optional `appMetadata` object (`id`, `name`, `logoUrl`, `faviconUrl`) and an optional `theme` object with custom theme values.
The priority to use when selecting a route for the payment: optimize for the fastest route or the cheapest route.
## Return Type
---
# Create payment session [Create a payment session for cross-chain cryptocurrency transactions]
A payment session should be created when a user wants to send cryptocurrency from one blockchain to another, or convert between different tokens. Glide handles the routing, conversion, and transaction execution.
A session is valid for a limited time, during which the user should complete the payment process. If the user does not complete the payment within this time, the session will expire and the user will need to create a new session. If a payment is made for an expired session, the payment will be refunded.
The payment session enables users to pay in one currency on one blockchain while settling in a different currency on a potentially different blockchain, with all fees and conversion rates calculated upfront.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const session = await createPaymentSession(config, {
paymentCurrency: usdc.on(ethereum),
settleCurrency: usdc.on(polygon),
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
paymentAmount: "100", // Omit for arbitrary payment amounts
});
console.log("Session ID:", session.sessionId);
console.log("Payment action:", session.paymentAction);
console.log("Settlement amount:", session.sponsoredTransactionAmount);
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The cryptocurrency the user will use to pay, in CAIP-19 format (e.g., `eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` for USDC on Ethereum).
The cryptocurrency the recipient will receive, in CAIP-19 format. Can be the same as or different from paymentCurrency.
The blockchain wallet address that will receive the settled funds. The address format depends on the settle currency's blockchain.
The amount the user will pay, specified as a string in human-readable format (not wei/smallest unit). Either paymentAmount OR settleAmount should be specified, but not both.
The amount the recipient will receive, specified as a string in human-readable format. Mutually exclusive with paymentAmount.
An identifier for generating a stable deposit address. When the payment method is transfer, providing a consistent key ensures the same deposit address is returned for repeat sessions.
Custom string metadata to attach to the session (e.g., order ID, user ID, JSON-encoded objects). Maximum length is typically 1024 characters.
The account of the user that will pay for the session, when known upfront.
The wallet secret that was used when creating the wallet. Required if the payer wallet was created on Glide.
When set to true, the payer will receive an email if their payment is refunded.
The email address of the payer, used for refund notifications.
Configuration for Glide-hosted payment pages. Contains an optional `appMetadata` object (`id`, `name`, `logoUrl`, `faviconUrl`) and an optional `theme` object with custom theme values.
The commission amount in USD that will be added on top of the payment amount and will be paid out to the developer.
Commission rates per currency tier (`tier1`, `tier2`, `tier3`) that will be added on top of the payment amount and paid out to the developer, as a percentage of the transaction amount (e.g., `"0.5"` = 0.5%). Cannot be used with commissionUSD.
When set to true, the session is created in dry mode for testing and no real payment is processed.
## Return Type
The session object includes:
- **Payment details**: Currency, amount, chain, and transaction hash
- **Settlement details**: Final amount and destination after fees
- **Payment action**: What the user needs to do (`signAndSendTransaction`, `signTypedData`, `redirectToUrl`, or `transfer`)
- **Fee breakdown**: Service fees, gas fees, and total costs
- **Status tracking**: Payment and transaction status fields for polling
## Payment Actions
After creating a session, the `paymentAction` field determines what the user needs to do:
### signAndSendTransaction
Most common action. User signs and sends a blockchain transaction using the `unsignedTransaction` field.
### signTypedData
User signs EIP-712 typed data (permit) using the `unsignedTypedData` field. Used for gasless approvals.
### redirectToUrl
User needs to complete payment through an external service (e.g., Coinbase onramp) using the `redirectUrl` field.
### transfer
User manually transfers cryptocurrency to the `depositAddress`. Poll the session to detect when payment is received.
## Examples
### Settle a fixed amount
Ensure the recipient receives exactly 50 USDC:
```ts
const session = await createPaymentSession(config, {
paymentCurrency: "eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
settleCurrency: "eip155:137/erc20:0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
settleAmount: "50", // Recipient gets exactly 50 USDC
});
console.log("User needs to pay:", session.paymentAmount);
console.log("Total fees:", session.totalFeeUSD);
```
### With metadata
Track sessions with custom metadata:
```ts
const session = await createPaymentSession(config, {
paymentCurrency: "eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
settleCurrency: "eip155:137/erc20:0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
paymentAmount: "100",
metadata: JSON.stringify({
orderId: "order-12345",
userId: "user-789",
}),
});
const orderInfo = JSON.parse(session.metadata);
console.log("Order ID:", orderInfo.orderId);
```
### Stable deposit address
For recurring payments or saved addresses:
```ts
const userId = "user-123";
const depositKey = `deposit-${userId}`;
const session = await createPaymentSession(config, {
paymentCurrency: "eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
settleCurrency: "eip155:137/erc20:0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
paymentAmount: "100",
stableDepositAddressKey: depositKey,
});
if (session.paymentAction === "transfer" && session.depositAddress) {
console.log("Send payment to:", session.depositAddress);
// User can save this address for future payments
}
```
### Native to token
Pay with native ETH, settle USDC:
```ts
const session = await createPaymentSession(config, {
paymentCurrency: eth.on(ethereum),
settleCurrency: usdc.on(ethereum),
recipientWallet: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
paymentAmount: "0.1", // Pay 0.1 ETH
});
console.log("Recipient will receive:", session.sponsoredTransactionAmount, "USDC");
```
---
# Execute session
The `executeEVMSession` and `executeSolanaSession` actions orchestrate the process required to complete a Glide session using the user's wallet. More specifically, they:
1. Switch the user's wallet to the correct chain (EVM only).
2. Trigger the payment transaction using the user's wallet and update Glide with the transaction hash.
3. If gasless payment is available (EVM only), instead of a payment transaction, the user is prompted to sign a message to authorize the payment. The signature is submitted to Glide.
4. Wait for the Glide session to be completed.
5. Return the completed session object, including the `sponsoredTransactionHash`.
If the session is expired, or is about to expire in the next 30 seconds, a `SessionExpiredError` is thrown without prompting the user.
## Import
```ts
```
## Usage
### EVM
:::code-group
```ts [index.ts]
const session = await createSession(config, {...});
const { sponsoredTransactionHash } = await executeEVMSession(config, {
session,
currentChainId: 1,
switchChainAsync: async ({ chainId }) => {
// switch current chain to chainId on the user's wallet
},
sendTransactionAsync: async (tx) => {
// send tx to the chain using the user's wallet
// return the transaction hash
},
signTypedDataAsync: async (typedData) => {
// sign the typed data using the user's wallet
// return the signature
},
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
### Solana
:::code-group
```ts [index.ts]
const session = await createSession(config, {...});
const { sponsoredTransactionHash } = await executeSolanaSession(config, {
session,
signAndSendTransaction: async (tx) => {
// sign and send the VersionedTransaction using the user's Solana wallet
// return the transaction signature
},
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
### executeEVMSession
The session object returned from the `createSession` action.
The EIP-155 chain ID of the chain that the user's wallet is currently connected to.
A function that switches the user's wallet to the specified chain.
A function that sends a transaction to the specified chain using the user's wallet. Returns the transaction hash.
A function that signs typed data using the user's wallet. Returns the signature. Required for gasless payments, i.e. when the session's `paymentAction` is `signTypedData`.
A callback invoked right after the user has completed their payment transaction or signature, before waiting for the session to complete.
A callback invoked with the latest session object every time the session is polled while waiting for it to complete.
### executeSolanaSession
The session object returned from the `createSession` action.
A function that signs and sends the Solana transaction using the user's wallet. Returns the transaction signature.
A callback invoked right after the user has completed their payment transaction, before waiting for the session to complete.
A callback invoked with the latest session object every time the session is polled while waiting for it to complete.
## Return Type
Returns the completed session object with `sponsoredTransactionHash` guaranteed to be set.
---
# Pay with signature [Pay for a gasless session with a signature]
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const { success } = await payWithSignature(config, {
sessionId: "c165e159-1f0e-44a1-8fa8-8c963444752e",
signature: "0x...",
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the session.
The signature of the session's `unsignedTypedData`, signed by the payer's wallet, that will be used to pay for the session.
## Return Type
Indicates whether the payment was successful.
---
# Pay with transfer [Settle a session paid via deposit address]
Asks Glide to check for and process the payment for a session whose `paymentAction` is `transfer`. Call it after the user has sent funds to the session's `depositAddress`.
Throws a `PaymentPendingError` while the transfer hasn't been detected or confirmed yet — use [`waitForTransfer`](/typescript/wait-for-transfer) to poll until it succeeds.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const { success } = await payWithTransfer(config, {
sessionId: "c165e159-1f0e-44a1-8fa8-8c963444752e",
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the session.
## Return Type
Indicates whether the payment was processed successfully.
## Errors
- `PaymentPendingError` — the transfer hasn't been detected or confirmed yet; retry after a short delay.
- `TransactionNotFoundError` — no transfer transaction was found for the session.
- `InsufficientPaymentAmountError` — the transferred amount doesn't cover the required payment amount; the payment will be refunded.
---
# Wait for transfer [Wait for a deposit-address payment to be received]
Polls [`payWithTransfer`](/typescript/pay-with-transfer) every 2 seconds until the transfer payment for a session is received and processed. Use it after showing the user the session's `depositAddress`.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const { success } = await waitForTransfer(config, {
sessionId: "c165e159-1f0e-44a1-8fa8-8c963444752e",
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the session.
## Return Type
Indicates whether the payment was processed successfully.
## Errors
Rejects with the same errors as [`payWithTransfer`](/typescript/pay-with-transfer) — except `PaymentPendingError`, which it handles by continuing to poll.
Note that this action resolves when the **payment** is received. To wait for the settlement transaction as well, follow up with [`waitForSession`](/typescript/wait-for-session).
---
# Wait for session [Wait for a session to be completed after the payment has been made]
Polls the session every 2 seconds until the sponsored transaction succeeds, and returns the completed session object. If you use [`executeEVMSession`](/typescript/execute-session) or `executeSolanaSession`, this is done for you automatically.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const completedSession = await waitForSession(config, {
sessionId: "74f9fc21-9ca9-41dd-a16f-121703543eaa",
onUpdate: (session) => {
console.log("Session status:", session.sponsoredTransactionStatus);
},
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the session.
A callback invoked with the latest session object on every poll.
A callback invoked when a poll request fails. Polling continues after the error.
An abort signal to cancel waiting. When aborted, the returned promise rejects with an `AbortError`.
## Errors
The returned promise rejects with one of the following errors:
- `SponsoredTransactionFailedError` — the sponsored transaction failed.
- `InsufficientPaymentAmountError` — the payment made was insufficient and is pending a refund.
- `SessionExpiredError` — the session expired before the payment was completed.
## Return Type
Returns the completed session object with `sponsoredTransactionHash` guaranteed to be set.
---
# Get session by ID [Retrieve a session by its unique ID]
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const session = await getSessionById(config, 'c165e159-1f0e-44a1-8fa8-8c963444752e');
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the session.
## Return Type
---
# Get session by payment transaction [Retrieve a session by its payment transaction]
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const session = await getSessionByPaymentTransaction(config, {
chainId: chains.base.id,
hash: "0x36145cfe6fd2b2c3c60ef52f16e86d9fdb825f59f82f8c3cdd0c6ac398cab48c",
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The CAIP-2 chain ID of the chain where the payment transaction was made (e.g., `eip155:8453` for Base). Use the `id` field of a chain imported from `@paywithglide/glide-js/chains`.
The payment transaction hash.
## Return Type
---
# List sessions
Lists previously created sessions by various filters.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const sessions = await listSessions(config, {
account: "0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625",
paymentStatus: "paid",
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The wallet address that was used when creating the session.
Filter sessions by their payment status.
## Return Type
Returns an array of session objects:
---
# List supported chains
Lists the chains supported by Glide. Useful for building chain pickers in deposit and withdrawal UIs.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const chains = await listSupportedChains(config);
const evmChains = chains.filter((chain) => chain.id.startsWith("eip155:"));
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
When set to true, all supported chains are returned, including testnets. Defaults to false.
## Return Type
Returns an array of chain objects:
The CAIP-2 chain ID (e.g., `eip155:8453` for Base).
The name of the chain.
The URL of the chain's logo.
Whether the chain is a testnet.
---
# List supported currencies
Lists the currencies supported by Glide on one or more chains. Useful for building currency pickers in deposit and withdrawal UIs.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const currencies = await listSupportedCurrencies(config, {
chainId: base.id,
});
// Get the CAIP-19 ID of a currency on a chain
const usdcOnBase = currencies
.find((currency) => currency.symbol === "USDC")!
.on(base);
// "eip155:8453/erc20:0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The CAIP-2 chain ID to list currencies for (e.g., `eip155:8453` for Base). Use the `id` field of a chain imported from `@paywithglide/glide-js/chains`.
A list of CAIP-2 chain IDs to list currencies for. Alternative to chainId.
When set to true, all supported currencies are returned. Defaults to false.
## Return Type
Returns an array of currency objects:
The unique identifier of the currency.
The name of the currency. Ex. "USD Coin".
The symbol of the currency. Ex. "USDC".
The number of decimals of the currency.
The URL of the currency's logo.
The tier of the currency. Stablecoins are `tier1`, major tokens are `tier2`, and volatile tokens are `tier3`.
Returns the CAIP-19 ID of the currency on the given chain. Throws a `CurrencyNotSupportedError` if the currency is not supported on that chain.
Returns the token's contract address on the given chain. Only present for tokens with a contract address (i.e., not native currencies).
---
# Create SVM transfer message [Build a Solana transfer message for a session]
Builds a base64-encoded Solana transfer message that sends a currency to a recipient. Pass the resulting `message` as the `solana.message` parameter of [`createSession`](/typescript/create-session) or [`listPaymentOptions`](/typescript/list-payment-options) when the destination transaction is a simple Solana transfer.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const userWalletAddress = "6VxUx4M6heF5g9EDXbCEV3AhtnJhrAxUdz4JXHrX43GB";
const { message } = await createSVMTransferMessage(config, {
chain: solana,
currency: usdc,
recipient: "7C4jsPZpht42Tw6MjXWF56Q5RQUocjBBmciEjDa8HRtp",
amount: "25",
});
const session = await createSession(config, {
chainId: solana.id,
account: userWalletAddress,
solana: { message },
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The Solana chain, imported from `@paywithglide/glide-js/chains`.
The currency to transfer, imported from `@paywithglide/glide-js/currencies`.
The Solana address that receives the transfer.
The amount to transfer, in a human-readable format.
## Return Type
The base64-encoded Solana transfer message.
---
# Create widget session [Create a session for the embedded widgets]
Creates a widget session on your backend to pre-configure the [Pay](/guides/embed-glide-pay) or [Deposit / Withdrawal](/guides/embed-glide-deposit) widget — the mode, amount, allowed chains, and funding sources. Pass the returned `id` to the widget on your frontend.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const { id } = await createWidgetSession(config, {
mode: "pay",
amount: "5",
});
// Pass `id` to the useGlidePay hook on your frontend
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The widget mode the session is for.
The amount, denominated in your preferred currency configured in the Glide Dashboard.
The wallet address that receives the funds.
The chains the user can pay from. Defaults to the chains set in the config.
The funding sources to offer: `wallet`, `external_wallet`, `transfer`, `coinbase`, `coinbase_app`, `fiat`, `interac`, `onramp`, or `onramper`.
Chains to exclude from the payment options.
Currency tiers to exclude from the payment options.
Funding sources to exclude: `transfer`, `coinbase`, `coinbase_app`, `fiat`, `interac`, `onramp`, or `onramper`.
Custom string metadata to attach to the session.
Commission rates per currency tier (`tier1`, `tier2`, `tier3`) paid out to the developer, as a percentage of the transaction amount (e.g., `"0.5"` = 0.5%).
The maximum destination-chain gas fee, in USD, that will be sponsored.
When set to true, the payer will receive an email if their payment is refunded.
The email address of the payer, used for refund notifications.
The phone number of the user.
An identifier for generating a stable deposit address across sessions.
## Return Type
Returns a widget session object:
The unique identifier of the widget session. Pass this to the widget on your frontend.
The widget mode.
The metadata attached to the session.
The widget session also echoes back the configuration it was created with (`chainIds`, `excludeChainIds`, `excludeCurrencyTiers`, `excludeFundingSources`, `commissionRates`, `maxSponsoredGasFeeUSD`, `stableDepositAddressKey`, `widgetConfig`).
---
# Get widget session [Retrieve the session for a widget session ID]
Retrieves the session for a widget session ID. Use it to check the state of a payment made through the widget.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const session = await getWidgetSession(config, "c165e159-1f0e-44a1-8fa8-8c963444752e");
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the widget session.
## Return Type
---
# Create session from widget [Create a Glide session from a widget session]
Creates a Glide session from a widget session, with the user's chosen payment method and currency. Use it to build your own payment UI on top of widget sessions instead of using the pre-built widget.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const widgetSessionId = "c165e159-1f0e-44a1-8fa8-8c963444752e";
const userWalletAddress = "0xc6FfEB1298Eb33Da430d14e5Eb789256ec344625";
const session = await createSessionFromWidget(config, {
sessionId: widgetSessionId,
account: userWalletAddress,
paymentMethod: "wallet",
paymentCurrency: usdc.on(base),
});
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the widget session, from `createWidgetSession`.
The wallet address that will pay for the session.
How the user pays: `wallet`, `transfer`, `coinbase_onramp`, `coinbase_app`, `moonpay`, `onramp`, or `onramper`.
The currency the user pays with, in CAIP-19 format.
When set to true and if supported by the payment currency, the user pays with a signature only, requiring no gas. Defaults to false.
The amount to pay. Defaults to the amount configured on the widget session.
When set to true, the widget session's `stableDepositAddressKey` is not applied, so a fresh deposit address is generated.
The wallet address that owns the deposit. Used with transfer payments to attribute the deposit address to a specific user.
Configuration for Glide-hosted payment pages. Contains an optional `appMetadata` object (`name`, `logoUrl`, `faviconUrl`) and an optional `theme` object with custom theme values.
## Return Type
---
# Get session by widget session [Retrieve the Glide session associated with a widget session]
Retrieves the Glide session that was created from a widget session — for example, via [`createSessionFromWidget`](/typescript/create-session-from-widget) or by the widget itself.
## Import
```ts
```
## Usage
:::code-group
```ts [index.ts]
const session = await getSessionByWidgetSession(
config,
"c165e159-1f0e-44a1-8fa8-8c963444752e",
);
```
```ts [config.ts]
// [!include ~/snippets/config.ts]
```
:::
## Parameters
The unique identifier of the widget session.
## Return Type
---
# Media Kit
You can download the Glide media kit here. It contains the Glide logo in various formats.
You can use the Glide logo in your dapp or wallet to attribute the payment option to Glide.
[Download the Glide media kit here](https://static.buildwithglide.com/Glide_Media_Kit.zip)
---