CrypaxDocs

@crypax/node

Node.js 서버 사이드 SDK. 결제 생성, 고객 관리, 웹훅 검증, 온체인 확인.


설치

$ npm install @crypax/node

설정

비밀 키로 클라이언트를 초기화합니다. 비밀 키는 절대 클라이언트 코드에 노출하지 마세요.

crypax.ts
import { Crypax } from '@crypax/node';

const crypax = new Crypax('sk_live_...');

체인 상수

SDK에서 사전 정의된 체인 상수를 제공하므로 체인 ID를 외울 필요가 없습니다. 결제 생성 시 이 상수를 사용하세요.

import { PLUMISE_MAINNET, PLUMISE_TESTNET, CHAINS, SUPPORTED_CHAIN_IDS } from '@crypax/node';

// Use chain constants instead of raw chain IDs
console.log(PLUMISE_MAINNET.chainId);  // 41956
console.log(PLUMISE_TESTNET.chainId);  // 419561

// Each constant includes full chain info
// { chainId, name, symbol, decimals, rpcUrl, explorerUrl, isTestnet }

// CHAINS object for iteration
Object.values(CHAINS).forEach(chain => {
  console.log(chain.name, chain.chainId);
});

// SUPPORTED_CHAIN_IDS = [41956, 419561]

지원 체인

상수이름체인 ID심볼테스트넷
PLUMISE_MAINNETPlumise Mainnet41956PLMNo
PLUMISE_TESTNETPlumise Testnet419561PLMYes

결제 (Payments)

payments.create(params)

새 결제를 생성합니다. 프론트엔드로 전달할 clientSecret이 포함된 Payment 객체를 반환합니다.

const payment = await crypax.payments.create({
  amount: '10.00',
  chainId: 41956,
  currency: 'native',          // optional, defaults to 'native'
  recipientAddress: '0x...',   // optional, defaults to project wallet
  description: 'Pro Plan',
  metadata: { userId: 'user_456' },
  qrMode: false,               // set true to skip wallet selection
});

console.log(payment.id);           // Payment UUID
console.log(payment.clientSecret); // 'cs_live_...' — send to frontend
CreatePaymentParams
파라미터타입필수설명
amountstring필수소수점 문자열로 표현한 결제 금액 (예: '10.00')
chainIdnumber필수체인 ID (예: Plumise 메인넷은 41956)
currency?string선택PLM은 'native', ERC20은 토큰 컨트랙트 주소
recipientAddress?string선택결제를 받을 지갑 주소 (선택 — 미입력 시 프로젝트 지갑 사용)
description?string선택사람이 읽을 수 있는 설명
metadata?Record<string, unknown>선택결제에 첨부할 임의 키-값 데이터
qrMode?boolean선택지갑 선택 화면을 건너뛰고 QR 코드를 바로 표시

payments.retrieve(id)

ID로 결제를 조회합니다.

const payment = await crypax.payments.retrieve('payment-uuid');
console.log(payment.status); // 'created' | 'processing' | 'confirmed' | 'expired' | 'failed'
console.log(payment.txHash); // '0x...' (after confirmation)

payments.list(params?)

상태와 페이지네이션 필터로 결제 목록을 조회합니다.

const { data, total } = await crypax.payments.list({
  status: 'confirmed',  // optional filter
  page: 1,
  limit: 20,
});

data.forEach(payment => {
  console.log(payment.id, payment.amount, payment.status);
});

고객 (Customers)

지갑 주소에 연결된 고객 레코드를 생성하고 관리합니다.

// Create a customer
const customer = await crypax.customers.create({
  walletAddress: '0x...',
  email: 'user@example.com',
  displayName: 'Alice',
  metadata: { plan: 'pro' },
});

// Retrieve
const customer = await crypax.customers.retrieve('cust_...');

// List
const { data } = await crypax.customers.list({ page: 1, limit: 20 });

// Update
await crypax.customers.update('cust_...', { displayName: 'Bob' });

// Delete
await crypax.customers.delete('cust_...');

환불 (Refunds)

확인된 결제에 대한 환불을 시작하고 추적합니다.

// Create a refund (full or partial)
const refund = await crypax.refunds.create({
  paymentId: 'pay_...',
  amount: '5.00',     // optional — omit for full refund
  reason: 'Customer request',
});

// Retrieve
const refund = await crypax.refunds.retrieve('refund_...');

// List
const { data } = await crypax.refunds.list({ paymentId: 'pay_...', page: 1, limit: 20 });

프로젝트 (Projects)

프로젝트 설정을 조회하고 업데이트합니다.

// Retrieve project settings
const project = await crypax.projects.retrieve();

// Update settings
await crypax.projects.update({
  name: 'My Store',
  brandingConfig: { primaryColor: '#8B5CF6' },
  allowedOrigins: ['https:2
  callbackUrl: 'https://my-store.com/api/crypax/callback',
});

체인 (Chains)

지원 체인과 토큰을 조회합니다.

// List supported chains
const chains = await crypax.chains.list();

// Get tokens for a specific chain
const tokens = await crypax.chains.getTokens(41956);
tokens.forEach(token => {
  console.log(token.symbol, token.address, token.decimals);
});

웹훅

webhooks.constructEvent(rawBody, signature, secret)

들어오는 웹훅 요청을 파싱하고 검증합니다. 원시 요청 바디(Buffer 또는 string), X-Crypax-Signature 헤더, 웹훅 시크릿을 전달하세요. 시그니처가 유효하지 않으면 예외를 던집니다.

webhook.ts
import { Crypax } from '@crypax/node';
import express from 'express';

const app = express();
const crypax = new Crypax('sk_live_...');

app.post('/webhooks/crypax', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-crypax-signature'] as string;

  try {
    const event = crypax.webhooks.constructEvent(
      req.body,
      signature,
      'whsec_...',
    );

    switch (event.type) {
      case 'payment.confirmed':
        console.log('Confirmed:', event.data.id, event.data.txHash);
        break;
      case 'payment.expired':
        console.log('Expired:', event.data.id);
        break;
      case 'payment.failed':
        console.log('Failed:', event.data.id);
        break;
      case 'refund.completed':
        console.log('Refund completed:', event.data.id);
        break;
    }

    res.json({ received: true });
  } catch (err) {
    res.status(400).json({ error: 'Invalid signature' });
  }
});

webhooks.verifySignature(rawBody, signature, secret)

이벤트 파싱 없이 HMAC-SHA256 시그니처를 검증합니다. 유효하면 true를 반환합니다.

const isValid = crypax.webhooks.verifySignature(
  rawBody,      // Buffer or string
  signature,    // x-crypax-signature header value
  webhookSecret // whsec_... from dashboard
);

if (!isValid) {
  throw new Error('Invalid webhook signature');
}

검증 (Verification)

verification.verifyPayment(txHash, params)

트랜잭션 해시로 온체인 네이티브 PLM 결제를 검증합니다.

const result = await crypax.verification.verifyPayment('0xabcdef...', {
  to: '0xRecipientAddress',
  amount: '10.00',
  decimals: 18,  // optional, defaults to 18
});

console.log(result.status);      // 'confirmed'
console.log(result.txHash);      // '0x...'
console.log(result.blockNumber); // 12345678

verification.verifyERC20Payment(txHash, params)

트랜잭션 해시로 온체인 ERC20 토큰 결제를 검증합니다.

const result = await crypax.verification.verifyERC20Payment('0xabcdef...', {
  tokenAddress: '0xTokenContract',
  to: '0xRecipientAddress',
  amount: '100.00',
  decimals: 6,  // optional, e.g. USDC uses 6
});

console.log(result.tokenAddress); // ERC20 contract address
console.log(result.amount);       // Transferred amount

유틸리티

@crypax/node에서 직접 import 가능한 유틸리티 함수들입니다.

import {
  isValidAddress,
  addressEquals,
  parseAmount,
  formatAmount,
} from '@crypax/node';

isValidAddress('0x...');                  // boolean
addressEquals('0xABC...', '0xabc...');    // true (case-insensitive)
parseAmount('10.00', 18);                 // BigInt wei value
formatAmount(1000000000000000000n, 18);   // '1.0'

타입 정의

// Payment object
interface Payment {
  id: string;
  clientSecret: string;
  amount: string;
  chainId: number;
  currency: string;
  recipientAddress?: string;
  senderAddress?: string;
  description?: string;
  metadata?: Record<string, unknown>;
  qrMode?: boolean;
  status: 'created' | 'processing' | 'confirmed' | 'expired' | 'failed' | 'refunded';
  txHash?: string;
  blockNumber?: number;
  expiresAt: string;
  confirmedAt?: string;
  createdAt: string;
}

// Webhook event
interface WebhookEvent {
  id: string;
  type:
    | 'payment.created' | 'payment.processing' | 'payment.confirmed'
    | 'payment.failed' | 'payment.expired' | 'payment.refunded'
    | 'refund.created' | 'refund.completed' | 'refund.failed'
    | 'settlement.requested' | 'settlement.approved'
    | 'settlement.completed' | 'settlement.failed'
    | 'customer.created' | 'customer.updated';
  data: Payment;
  createdAt: string;
}
Node.js SDK | Crypax