Machine Integration Examples

Python Client

import requests
import hmac
import hashlib
import base64
from eth_account import Account
from eth_account.messages import encode_structured_data

class SigweiClient:
    def __init__(self, private_key, base_url="https://402ify.com"):
        self.account = Account.from_key(private_key)
        self.base_url = base_url
        self.access_token = None
    
    def authenticate(self):
        # Get message to sign
        response = requests.get(
            f"{self.base_url}/api/v1/auth/message",
            params={"walletAddress": self.account.address}
        )
        message = response.json()["message"]
        
        # Sign message
        encoded_msg = encode_structured_data(primitive=message)
        signature = self.account.sign_message(encoded_msg)
        
        # Login
        auth_response = requests.post(
            f"{self.base_url}/api/v1/auth/login",
            json={"message": message, "signature": signature.signature.hex()}
        )
        self.access_token = auth_response.json()["accessToken"]
    
    def create_paygate(self, target_url, method="GET", price="0.01",
                      network="base-sepolia", require_auth=False, header_auth_mode="hmac", assume_valid=False):
        if not self.access_token:
            self.authenticate()

        response = requests.post(
            f"{self.base_url}/api/v1/paygates",
            headers={"Authorization": f"Bearer {self.access_token}"},
            json={
                "targetUrl": target_url,
                "method": method,
                "price": price,
                "network": network,
                "paymentAddress": self.account.address,
                "requireAuth": require_auth,
                "headerAuthMode": header_auth_mode,
                "assumeValid": assume_valid
            }
        )
        return response.json()
    
    def get_paygates(self):
        if not self.access_token:
            self.authenticate()
        
        response = requests.get(
            f"{self.base_url}/api/v1/paygates",
            headers={"Authorization": f"Bearer {self.access_token}"}
        )
        return response.json()
    
    def execute_transfer(self, to_address, amount_usdc):
        # Generate EIP-712 signature for USDC transfer
        nonce = "0x" + secrets.token_hex(32)
        valid_before = int(time.time()) + 3600  # 1 hour validity
        
        authorization = {
            "from": self.account.address,
            "to": to_address,
            "value": str(int(amount_usdc * 1e6)),  # Convert to USDC wei
            "validAfter": "0",
            "validBefore": str(valid_before),
            "nonce": nonce
        }
        
        # Sign with EIP-712 (implementation depends on your signing library)
        signature = self.sign_transfer_authorization(authorization)
        
        response = requests.post(
            f"{self.base_url}/api/v1/transfer",
            json={
                "network": "base-sepolia",
                "signature": signature,
                "authorization": authorization
            }
        )
        return response.json()

# Usage example
client = SigweiClient("0xYOUR_PRIVATE_KEY")

# Create a PayGate
paygate = client.create_paygate(
    target_url="https://api.example.com/data",
    method="GET",
    price="0.05",
    require_auth=True,
    header_auth_mode="hmac"
)

print(f"PayGate created: {paygate['accessUrl']}")

JavaScript/Node.js Client

import axios from 'axios';
import { withPaymentInterceptor } from 'x402-axios';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { baseSepolia } from 'viem/chains';

class SigweiClient {
  constructor(privateKey, baseURL = 'https://402ify.com') {
    this.account = privateKeyToAccount(privateKey);
    this.walletClient = createWalletClient({
      account: this.account,
      chain: baseSepolia,
      transport: http()
    });
    this.baseURL = baseURL;
    this.authToken = null;
    
    // Create x402-enabled HTTP client
    this.paymentClient = withPaymentInterceptor(axios, this.walletClient);
  }

  async authenticate() {
    const walletAddress = this.account.address;
    
    // Get auth message
    const messageResponse = await axios.get(
      `${this.baseURL}/api/v1/auth/message?walletAddress=${walletAddress}`
    );
    const { message } = messageResponse.data;

    // Sign message
    const signature = await this.walletClient.signMessage({
      message: { raw: message }
    });

    // Login
    const loginResponse = await axios.post(`${this.baseURL}/api/v1/auth/login`, {
      message,
      signature
    });

    this.authToken = loginResponse.data.accessToken;
    return this.authToken;
  }

  async createPayGate(config) {
    if (!this.authToken) {
      await this.authenticate();
    }

    const response = await axios.post(
      `${this.baseURL}/api/v1/paygates`,
      {
        targetUrl: config.targetUrl,
        method: config.method || 'GET',
        price: config.price || '0.01',
        network: config.network || 'base-sepolia',
        paymentAddress: this.account.address,
        requireAuth: config.requireAuth || false,
        headerAuthMode: config.headerAuthMode || 'hmac',
        title: config.title || '',
        description: config.description || ''
      },
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`,
          'Content-Type': 'application/json'
        }
      }
    );

    return response.data;
  }

  async accessPayGate(shortCode, requiresAuth = false) {
    let headers = {};
    
    if (requiresAuth) {
      if (!this.authToken) {
        await this.authenticate();
      }
      headers.Authorization = `Bearer ${this.authToken}`;
    }

    try {
      const response = await this.paymentClient.get(
        `${this.baseURL}/${shortCode}`,
        { headers }
      );
      return response.data;
    } catch (error) {
      if (error.response?.status === 401) {
        // Re-authenticate and retry
        await this.authenticate();
        headers.Authorization = `Bearer ${this.authToken}`;
        
        const retryResponse = await this.paymentClient.get(
          `${this.baseURL}/${shortCode}`,
          { headers }
        );
        return retryResponse.data;
      }
      throw error;
    }
  }

  async getDashboardStats() {
    if (!this.authToken) {
      await this.authenticate();
    }

    const response = await axios.get(
      `${this.baseURL}/api/v1/dashboard/stats`,
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`
        }
      }
    );

    return response.data;
  }
}

// Usage example
const client = new SigweiClient('0xYOUR_PRIVATE_KEY');

// Create an authenticated PayGate
const paygate = await client.createPayGate({
  targetUrl: 'https://api.example.com/premium',
  method: 'GET',
  price: '0.10',
  requireAuth: true,
  headerAuthMode: 'hmac',
  title: 'Premium API Access'
});

console.log(`PayGate created: ${paygate.accessUrl}`);

// Access the PayGate (payment handled automatically)
const data = await client.accessPayGate(paygate.shortCode, true);
console.log('Protected data:', data);

Go Client

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type SigweiClient struct {
    BaseURL     string
    PrivateKey  string
    AuthToken   string
    HTTPClient  *http.Client
}

type PayGateConfig struct {
    TargetURL      string `json:"targetUrl"`
    Method         string `json:"method"`
    Price          string `json:"price"`
    Network        string `json:"network"`
    PaymentAddress string `json:"paymentAddress"`
    RequireAuth    bool   `json:"requireAuth"`
    HeaderAuthMode string `json:"headerAuthMode"`
    Title          string `json:"title,omitempty"`
    Description    string `json:"description,omitempty"`
}

func NewSigweiClient(privateKey, baseURL string) *SigweiClient {
    return &SigweiClient{
        BaseURL:    baseURL,
        PrivateKey: privateKey,
        HTTPClient: &http.Client{Timeout: 30 * time.Second},
    }
}

func (c *SigweiClient) Authenticate() error {
    // Implementation would include wallet address derivation
    // and message signing logic
    walletAddress := deriveWalletAddress(c.PrivateKey)
    
    // Get message to sign
    resp, err := c.HTTPClient.Get(
        fmt.Sprintf("%s/api/v1/auth/message?walletAddress=%s", 
                   c.BaseURL, walletAddress))
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    var messageResp struct {
        Message string `json:"message"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&messageResp); err != nil {
        return err
    }

    // Sign message (implementation depends on your signing library)
    signature := signMessage(c.PrivateKey, messageResp.Message)

    // Login
    loginData := map[string]string{
        "message":   messageResp.Message,
        "signature": signature,
    }
    
    jsonData, _ := json.Marshal(loginData)
    resp, err = c.HTTPClient.Post(
        c.BaseURL+"/api/v1/auth/login",
        "application/json",
        bytes.NewBuffer(jsonData))
    
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    var authResp struct {
        AccessToken string `json:"accessToken"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
        return err
    }

    c.AuthToken = authResp.AccessToken
    return nil
}

func (c *SigweiClient) CreatePayGate(config PayGateConfig) (map[string]interface{}, error) {
    if c.AuthToken == "" {
        if err := c.Authenticate(); err != nil {
            return nil, err
        }
    }

    jsonData, _ := json.Marshal(config)
    req, _ := http.NewRequest("POST", c.BaseURL+"/api/v1/paygates", bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+c.AuthToken)
    req.Header.Set("Content-Type", "application/json")

    resp, err := c.HTTPClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    return result, nil
}

// Usage example
func main() {
    client := NewSigweiClient("0xYOUR_PRIVATE_KEY", "https://402ify.com")

    paygate, err := client.CreatePayGate(PayGateConfig{
        TargetURL:      "https://api.example.com/data",
        Method:         "GET", 
        Price:          "0.05",
        PaymentAddress: "0xYOUR_WALLET_ADDRESS",
        RequireAuth:    true,
        HeaderAuthMode: "hmac",
        IsTest:         true,
        Title:          "Premium Data API",
    })

    if err != nil {
        panic(err)
    }

    fmt.Printf("PayGate created: %v\n", paygate["accessUrl"])
}

cURL Examples

# Authentication Flow
curl -X GET "https://402ify.com/api/v1/auth/message?walletAddress=0x742d35Cc6634C0532925a3b8c2414F4e456C10F4"

curl -X POST "https://402ify.com/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Sigwei Authentication\n\nWallet: 0x742d35cc6634c0532925a3b8c2414f4e456c10f4\nNonce: abc123def456\nTime: 2024-01-01T12:00:00Z\n\nSign this message to authenticate.",
    "signature": "0x1234567890abcdef..."
  }'

# Create PayGate
curl -X POST "https://402ify.com/api/v1/paygates" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "targetUrl": "https://api.example.com/data",
    "method": "GET",
    "price": "0.01",
    "network": "base-sepolia",
    "paymentAddress": "0x742d35Cc6634C0532925a3b8c2414F4e456C10F4",
    "requireAuth": false,
    "headerAuthMode": "hmac",
    "assumeValid": false
  }'

# List PayGates
curl -X GET "https://402ify.com/api/v1/paygates" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# Access PayGate (first request - returns 402)
curl -X GET "https://402ify.com/abc123"

# Access PayGate with payment proof
curl -X GET "https://402ify.com/abc123" \
  -H "X-Payment: <base64-encoded-payment-data>"

# Get dashboard statistics
curl -X GET "https://402ify.com/api/v1/dashboard/stats" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# Update PayGate settings
curl -X PUT "https://402ify.com/api/v1/paygates/123" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Updated API Access",
    "requireAuth": true,
    "headerAuthMode": "plaintext",
    "assumeValid": false
  }'

# Regenerate PayGate secret
curl -X PATCH "https://402ify.com/api/v1/paygates/123/secret" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{"sigweiSecret": ""}'

AI Agent Integration

For AI agents and automated systems, use x402-compatible HTTP libraries that handle payment flows automatically:

# Python with x402 support
import x402_requests  # Hypothetical x402-enabled requests library

session = x402_requests.Session(wallet_client=your_wallet)
response = session.get('https://402ify.com/abc123')
# Automatically handles 402 responses and payments
// JavaScript with automatic payment handling
import { withPaymentInterceptor } from 'x402-axios';

const client = withPaymentInterceptor(axios, walletClient);
const response = await client.get('https://402ify.com/abc123');
// Payments handled automatically in background

Last updated