Unity Integration
Gx402 shows how to integrate x402 payments into Unity projects using engine-native UI and wallet connectors (WalletConnect, browser wallets for WebGL). We provide example Unity scripts, a test scene, and an Express middleware example to handle server-side verification and x402 calls.Prerequisites
- Unity 2020.3 LTS or newer (2021+ recommended)
High-Level Flow
- Connect Wallet
The player taps Connect Wallet in the Unity UI.Gx402ManagercallsConnectWalletAsync()from the Solana SDK (e.g., MagicBlocks).- The user approves the prompt in Phantom or Solflare.
- Once connected,
Web3.Accountstores the wallet address and updates the UI with the active wallet.
- Initiate Payment Request
The player taps Buy (or Call API) to begin an x402-protected flow.- Unity triggers
HandleApiCallOptimized(). - The script validates the connected wallet (
CheckWallet()). - The payer’s public key is retrieved to identify who’s making the payment.
- Unity triggers
- Build the Transaction
Unity constructs a Solana USDC transaction viaBuildUsdcTransaction().- Fetches a recent blockhash for transaction validity.
- Derives payer and recipient token accounts (ATAs).
- Bundles three key instructions:
- Create payer ATA (idempotent)
- Create recipient ATA (idempotent)
- Transfer required USDC amount
- Finalizes and signs the transaction object with the payer as the fee payer.
- Sign and Send
- The wallet prompts the player to approve and sign the transaction.
- On approval, Unity sends it using
SendTransactionAsync(). - The Solana network returns a transaction signature (
TX ID), confirming the payment on-chain. ConfirmTransaction()ensures final settlement before proceeding.
- Verify and Unlock (x402 Flow)
- Unity sends the transaction signature in the
X-402-Paymentheader via a POST request to your backend. - The backend verifies the transaction (correct amount, mint, recipient).
- Once confirmed, it unlocks the API endpoint or in-game reward.
- Unity receives a
200 OKresponse and updates the UI to show:
✅ “Payment Verified — Access Granted!”
- Unity sends the transaction signature in the
💡 Tip:
This flow allows any Unity-based Solana game to implement secure, non-custodial payments with a single, reusableGx402Managerscript — fully compliant with x402 payment standards.
