The useTonPay hook provides a React interface for creating TON Pay transfers. It integrates with TON Connect to connect a wallet, sign transactions, and surface transfer errors through the hook state.
The useTonPay hook manages the client-side flow for sending a TON Pay transfer. It performs the following steps:
Checks whether a wallet is connected and, if not, opens the TON Connect modal and waits for a successful connection.
Calls an application-provided factory function that builds the transaction message, either in the client-side or by requesting it from a backend service.
Sends the transaction message to the connected wallet for user approval and signing.
Returns the transaction result along with tracking identifiers that can be used for reconciliation.
Create an API endpoint that builds the transaction message and stores tracking data:
Copy
Ask AI
import { createTonPayTransfer } from "@ton-pay/api";app.post("/api/create-payment", async (req, res) => { const { amount, senderAddr, orderId } = req.body; try { const { message, reference, bodyBase64Hash } = await createTonPayTransfer( { amount, asset: "TON", recipientAddr: "<MERCHANT_WALLET_ADDRESS>", senderAddr, commentToSender: `Payment for Order ${orderId}`, commentToRecipient: `Order ${orderId}`, }, { chain: "testnet", apiKey: "yourTonPayApiKey", } ); // Store tracking identifiers in your database await db.createPayment({ orderId, reference, bodyBase64Hash, amount, asset: "TON", status: "pending", senderAddr, }); // Return only the message to the client res.json({ message }); } catch (error) { console.error("Failed to create payment:", error); res.status(500).json({ error: "Failed to create payment" }); }});
Persist tracking identifiers before respondingAlways persist tracking identifiers such as reference and bodyBase64Hash in the database before returning the message to the client. If the client loses connection or closes the browser, these identifiers are still required to process incoming webhooks.
try { await pay(getMessage);} catch (error) { // User rejected the transaction in their wallet if (error.message?.includes("rejected")) { console.log("User rejected the transaction"); } // Network or API errors else if (error.message?.includes("Failed to create TON Pay transfer")) { console.log("API error - check your configuration"); } // Other unexpected errors else { console.error("Unexpected error:", error); }}
Funds at riskRunning tests on mainnet can result in irreversible loss of real TON. Always use chain: "testnet" and testnet wallet addresses during development. Verify the network before switching to mainnet.
A complete description of testnet configuration, including obtaining testnet TON, testing jetton transfers, verifying transactions, and preparing for mainnet deployment, is available in the Testnet configuration section.