dochuong627/privy-php-server-auth

PHP SDK for Privy Server Authentication

v1.0.0 2025-09-03 19:41 UTC

This package is not auto-updated.

Last update: 2025-09-04 11:17:48 UTC


README

PHP SDK cho Privy Server Authentication, chuyển đổi từ thư viện Node.js @privy-io/server-auth.

Cài đặt

Yêu cầu hệ thống

  • PHP >= 8.0
  • Composer
  • Extensions: ext-json, ext-openssl, ext-curl

Cài đặt qua Composer

composer require dochuong627/privy-php-server-auth

Dependencies

SDK sử dụng các thư viện PHP phổ biến:

  • HTTP Requests: guzzlehttp/guzzle (thay thế cho redaxios)
  • JWT: firebase/php-jwt (thay thế cho jose)
  • Crypto: ext-openssl (built-in PHP extension)
  • JSON: ext-json (built-in PHP extension)

Cách sử dụng

Khởi tạo Client

<?php

use Privy\ServerAuth\PrivyClient;

// Khởi tạo client với App ID và App Secret
$privy = new PrivyClient(
    'your-app-id',
    'your-app-secret',
    [
        'apiURL' => 'https://auth.privy.io', // Optional
        'timeout' => 10000, // Optional, default 10 seconds
        'walletApi' => [
            'apiURL' => 'https://api.privy.io', // Optional
            'timeout' => 10000, // Optional
            'authorizationPrivateKey' => 'your-private-key' // Optional
        ]
    ]
);

Xác thực Token

<?php

// Verify auth token
try {
    $tokenData = $privy->verifyAuthToken('your-jwt-token');
    echo "User ID: " . $tokenData['userId'];
    echo "App ID: " . $tokenData['appId'];
    echo "Issuer: " . $tokenData['issuer'];
    echo "Expires: " . date('Y-m-d H:i:s', $tokenData['expiration']);
} catch (PrivyClientException $e) {
    echo "Token verification failed: " . $e->getMessage();
}

Lấy thông tin User

<?php

// Lấy user bằng ID
$user = $privy->getUserById('user-id-here');

// Lấy user bằng email
$user = $privy->getUserByEmail('user@example.com');

// Lấy user bằng wallet address
$user = $privy->getUserByWalletAddress('0x1234...');

// Lấy user từ ID token
$user = $privy->getUserFromIdToken('jwt-token-here');

// Lấy user bằng phone number
$user = $privy->getUserByPhoneNumber('+1234567890');

// Lấy user bằng social accounts
$user = $privy->getUserByDiscordUsername('username');
$user = $privy->getUserByGithubUsername('username');
$user = $privy->getUserByTwitterUsername('username');

Quản lý User

<?php

// Import user mới
$user = $privy->importUser([
    'linkedAccounts' => [
        [
            'type' => 'email',
            'address' => 'user@example.com'
        ],
        [
            'type' => 'wallet',
            'address' => '0x1234...',
            'chainType' => 'ethereum'
        ]
    ],
    'createEthereumWallet' => true,
    'customMetadata' => [
        'plan' => 'premium',
        'region' => 'US'
    ]
]);

// Tạo wallets cho user
$wallets = $privy->createWallets([
    'userId' => 'user-id',
    'createEthereumWallet' => true,
    'createSolanaWallet' => false,
    'numberOfEthereumWalletsToCreate' => 1
]);

// Xóa user
$privy->deleteUser('user-id');

// Cập nhật custom metadata
$user = $privy->setCustomMetadata('user-id', [
    'plan' => 'enterprise',
    'lastLogin' => date('Y-m-d H:i:s')
]);

// Bulk search users
$users = $privy->getUsers([
    'emails' => ['user1@example.com', 'user2@example.com'],
    'phoneNumbers' => ['+1234567890', '+0987654321'],
    'walletAddresses' => ['0x1234...', '0x5678...']
]);

Quản lý Allowlist

<?php

// Lấy danh sách allowlist
$allowlist = $privy->getAllowlist();

// Mời user vào allowlist
$invite = $privy->inviteToAllowlist([
    'email' => 'user@example.com',
    'phoneNumber' => '+1234567890'
]);

// Xóa user khỏi allowlist
$remove = $privy->removeFromAllowlist([
    'email' => 'user@example.com'
]);

Webhook Verification

<?php

// Verify webhook signature
try {
    $isValid = $privy->verifyWebhook(
        $payload, // Request body
        $headers,  // Request headers
        $secret    // Webhook secret
    );
    
    if ($isValid) {
        // Process webhook
        echo "Webhook verified successfully";
    }
} catch (PrivyClientException $e) {
    echo "Webhook verification failed: " . $e->getMessage();
}

Test Credentials

<?php

// Lấy test access token
$testToken = $privy->getTestAccessToken([
    'email' => 'test@example.com',
    'phoneNumber' => '+1234567890'
]);

echo "Test Access Token: " . $testToken['accessToken'];

Lấy App Settings

<?php

// Lấy cài đặt app
$settings = $privy->getAppSettings();

echo "App Name: " . $settings['name'];
echo "Wallet Auth Enabled: " . ($settings['walletAuth'] ? 'Yes' : 'No');
echo "Email Auth Enabled: " . ($settings['emailAuth'] ? 'Yes' : 'No');

Wallet API

<?php

// Tạo wallet
$wallet = $privy->walletApi->createWallet([
    'type' => 'ethereum',
    'userId' => 'user-id'
]);

// Lấy wallet
$wallet = $privy->walletApi->getWallet('wallet-id');

// Thực hiện RPC call
$result = $privy->walletApi->executeRpc('wallet-id', [
    'method' => 'eth_getBalance',
    'params' => ['0x1234...', 'latest']
]);

// Tạo policy
$policy = $privy->walletApi->createPolicy([
    'name' => 'My Policy',
    'description' => 'Policy description'
]);

Error Handling

SDK sử dụng các exception classes riêng biệt:

<?php

use Privy\ServerAuth\Exceptions\PrivyApiException;
use Privy\ServerAuth\Exceptions\PrivyClientException;

try {
    $user = $privy->getUserById('invalid-id');
} catch (PrivyApiException $e) {
    // API errors (4xx, 5xx)
    echo "API Error: " . $e->getMessage();
    echo "Status Code: " . $e->getStatus();
} catch (PrivyClientException $e) {
    // Client errors (network, parsing, etc.)
    echo "Client Error: " . $e->getMessage();
}

So sánh với Node.js SDK

Node.jsPHP
new PrivyClient(appId, appSecret, options)new PrivyClient(appId, appSecret, options)
client.getUser(userId)$client->getUserById(userId)
client.getUserByEmail(email)$client->getUserByEmail(email)
client.verifyAuthToken(token)$client->verifyAuthToken(token)
client.importUser(options)$client->importUser(options)
client.getAppSettings()$client->getAppSettings()

Migration từ Node.js

Thay đổi cú pháp

Node.js:

const { PrivyClient } = require('@privy-io/server-auth');

const privy = new PrivyClient(appId, appSecret);
const user = await privy.getUserById(userId);

PHP:

use Privy\ServerAuth\PrivyClient;

$privy = new PrivyClient($appId, $appSecret);
$user = $privy->getUserById($userId);

Thay đổi xử lý lỗi

Node.js:

try {
    const user = await privy.getUserById(userId);
} catch (error) {
    if (error.status === 404) {
        // User not found
    }
}

PHP:

try {
    $user = $privy->getUserById($userId);
} catch (PrivyApiException $e) {
    if ($e->getStatus() === 404) {
        // User not found
    }
}

Contributing

  1. Fork repository
  2. Tạo feature branch
  3. Commit changes
  4. Push to branch
  5. Tạo Pull Request

License

Apache-2.0 License - xem file LICENSE để biết thêm chi tiết.