Book

 · 

x402 payment js - Nov 4, 9:00

import { Controller } from "@hotwired/stimulus"

export default class extends Controller { static values = { url: String }

async pay() { if (!window.ethereum) { alert("⚠️ 请先安装钱包") return }

try {
// 1️⃣ 请求资源
const res = await fetch(this.urlValue)
const payInfo = await res.json()

if (res.status !== 402) {
alert("✅ 已解锁或无需支付")
return
}

// 2️⃣ 获取支付要求
const accept = payInfo.accepts[0]
const { payTo, asset, maxAmountRequired, network, scheme, extra } = accept

console.log("🧾 支付要求:", accept)
console.log("📦 Extra 信息:", extra)

// 3️⃣ 连接钱包
const accounts = await window.ethereum.request({
method: "eth_requestAccounts"
})
const from = accounts[0]

// 4️⃣ 生成 nonce 和时间戳
const nonce = this.generateNonce()
const timestamp = Math.floor(Date.now() / 1000)
const validAfter = timestamp - 300
const validBefore = timestamp + 600

// 5️⃣ 获取 Chain ID
const chainId = await this.getChainId()
console.log("🔗 Chain ID:", chainId)

// 6️⃣ 读取合约信息(调试用)
await this.debugContractInfo(asset)

// 7️⃣ 构造 EIP-712 签名数据(尝试多个配置)
const domainConfigs = [
// 配置 1: 使用 extra 信息
{
name: extra?.name || "USD Coin",
version: extra?.version?.toString() || "2",
chainId: chainId,
...
Currency-dollar 0.0010 USDC
Pay to @book
Wallet 0xc215...d7c7

Information-circle Not logged in. Payment will only be linked to wallet address.

Information-circle Payment goes directly to the author. For refunds, please contact the author.

Download Pickful App

Better experience on mobile

iOS QR

iOS

Android QR

Android

APK QR

APK