サンプル
いずれも、秘密鍵とシークレットは環境変数やシークレット管理から読み、コードやリポジトリには置かないでください。
| 環境変数 | 内容 |
|---|---|
UPBOND_API_KEY | API キー ID |
UPBOND_AUTH_BASE | https://auth.stg.upbond.io(本番は https://auth.upbond.io) |
UPBOND_API_BASE | 接続情報の API ホスト名(https://…) |
UPBOND_VAULT_ID | Vault アカウント ID |
UPBOND_ASSET_ID | 接続情報の assetId |
UPBOND_PRIVATE_KEY_FILE | 認証用の RSA 秘密鍵(PEM)のパス |
UPBOND_SIGNING_SECRET | シークレット(base64、44 文字) |
Node.js
依存は jose だけです(npm i jose)。Node.js 20 以降。
// upbond-transfer.mjs
import { constants, createHash, createPrivateKey, publicEncrypt, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { SignJWT } from 'jose';
const env = process.env;
const apiKey = env.UPBOND_API_KEY;
const authBase = env.UPBOND_AUTH_BASE;
const apiBase = env.UPBOND_API_BASE;
const privateKey = createPrivateKey(readFileSync(env.UPBOND_PRIVATE_KEY_FILE));
// RFC 7523 client assertion: proves possession of the registered key. Short-lived.
async function clientAssertion() {
return new SignJWT({})
.setProtectedHeader({ alg: 'RS256' })
.setIssuer(apiKey)
.setSubject(apiKey)
.setAudience(authBase)
.setJti(randomUUID())
.setIssuedAt()
.setExpirationTime('60s')
.sign(privateKey);
}
// Opaque access token, cached until 30 s before expiry.
let cached = { token: null, expiresAt: 0 };
export async function accessToken() {
if (cached.token && Date.now() < cached.expiresAt - 30_000) return cached.token;
const res = await fetch(`${authBase}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
client_assertion: await clientAssertion(),
}),
});
if (!res.ok) throw new Error(`token endpoint ${res.status}: ${await res.text()}`);
const { access_token, expires_in } = await res.json();
cached = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };
return access_token;
}
async function headers(extra = {}) {
return {
'X-API-Key': apiKey,
Authorization: `Bearer ${await accessToken()}`,
'Content-Type': 'application/json',
...extra,
};
}
// Signing-environment key, cached until expiresAt (re-fetched on a 1410).
let signer = null;
async function signerKey(force = false) {
if (!force && signer && Date.now() < signer.expiresAt) return signer;
const res = await fetch(`${apiBase}/v1/upbond/signer`, { headers: await headers() });
if (!res.ok) throw new Error(`signer ${res.status}: ${await res.text()}`);
signer = await res.json();
return signer;
}
// The request a bound envelope names: seven fields exactly as sent, LF-joined
// (feeLevel defaults to MEDIUM and note to "" when the body omits them).
function canonicalRequest(body) {
return [
body.assetId,
body.source.id,
body.destination.oneTimeAddress.address,
body.amount,
body.feeLevel ?? 'MEDIUM',
body.externalTxId,
body.note ?? '',
].join('\n');
}
// RSA-OAEP-SHA256 envelope, bound to `body` and stamped now:
// 0x01 || secret(32) || sha256(canonicalRequest)(32) || issuedAt(8, BE ms).
function envelope(key, body) {
const issuedAt = Buffer.alloc(8);
issuedAt.writeBigUInt64BE(BigInt(Date.now()));
const secret = Buffer.from(env.UPBOND_SIGNING_SECRET, 'base64');
const plaintext = Buffer.concat([
Buffer.from([0x01]),
secret,
createHash('sha256').update(canonicalRequest(body), 'utf8').digest(),
issuedAt,
]);
try {
const ciphertext = publicEncrypt(
{ key: key.publicKeyPem, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
plaintext,
);
return { keyId: key.keyId, envelope: ciphertext.toString('base64') };
} finally {
// Neither the plaintext nor the secret copy outlives the call.
plaintext.fill(0);
secret.fill(0);
}
}
// One refund = one transaction. externalTxId doubles as the Idempotency-Key.
export async function createTransfer({ externalTxId, address, amount, note }) {
const body = {
operation: 'TRANSFER',
assetId: env.UPBOND_ASSET_ID,
source: { type: 'VAULT_ACCOUNT', id: env.UPBOND_VAULT_ID },
destination: { type: 'ONE_TIME_ADDRESS', oneTimeAddress: { address } },
amount,
externalTxId,
...(note ? { note } : {}),
};
for (let attempt = 0; attempt < 2; attempt++) {
const key = await signerKey(attempt > 0);
const res = await fetch(`${apiBase}/v1/transactions`, {
method: 'POST',
headers: await headers({ 'Idempotency-Key': externalTxId }),
// A fresh envelope per attempt: it is bound to this body and to "now".
body: JSON.stringify({ ...body, signer: envelope(key, body) }),
signal: AbortSignal.timeout(90_000),
});
const result = await res.json();
// 1410: the signer key rotated — fetch it again and re-send the same request.
if (res.status === 422 && result.code === 1410 && attempt === 0) continue;
if (!res.ok) throw new Error(`create ${res.status}: ${JSON.stringify(result)}`);
return result; // { id, status }
}
}
export async function getTransfer(txId) {
const res = await fetch(`${apiBase}/v1/transactions/${txId}`, { headers: await headers() });
if (!res.ok) throw new Error(`get ${res.status}: ${await res.text()}`);
return res.json();
}
export async function getTransferByExternalTxId(externalTxId) {
const res = await fetch(
`${apiBase}/v1/transactions/external_tx_id/${encodeURIComponent(externalTxId)}`,
{ headers: await headers() },
);
if (!res.ok) throw new Error(`get ${res.status}: ${await res.text()}`);
return res.json();
}
// Polling: follow next-page until it disappears.
export async function listTransfers(params) {
let url = `${apiBase}/v1/transactions?${new URLSearchParams(params)}`;
const all = [];
while (url) {
const res = await fetch(url, { headers: await headers() });
if (!res.ok) throw new Error(`list ${res.status}: ${await res.text()}`);
all.push(...(await res.json()));
url = res.headers.get('next-page');
}
return all;
}
使い方の例です。
import { createTransfer, getTransfer } from './upbond-transfer.mjs';
const { id, status } = await createTransfer({
externalTxId: 'refund-2026-000123',
address: '0x1111111111111111111111111111111111111111',
amount: '12345.00',
note: 'Refund #000123',
});
console.log(id, status); // BROADCASTING(失敗時は FAILED)
const tx = await getTransfer(id);
console.log(tx.status, tx.subStatus, tx.txHash);
curl
アクセストークンと封筒は上の Node.js の関数で作ってから、環境変数に入れて呼ぶ例です。
# 1. アクセストークン($ASSERTION は clientAssertion() の出力)
curl -s -X POST "$UPBOND_AUTH_BASE/oauth/token" \
-d grant_type=client_credentials \
-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
-d "client_assertion=$ASSERTION"
# → { "access_token": "…", "token_type": "Bearer", "expires_in": 300 }
# 2. 署名環境の公開鍵
curl -s "$UPBOND_API_BASE/v1/upbond/signer" \
-H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN"
# 3. 送金の作成($KEY_ID と $ENVELOPE は、この本文と同じ assetId / source.id / 宛先 /
# amount / feeLevel / externalTxId で作った envelope() の出力。封筒は本文に束縛されるので、
# 本文を変えたら封筒も作り直す)
curl -s -X POST "$UPBOND_API_BASE/v1/transactions" \
-H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN" \
-H "Idempotency-Key: refund-2026-000123" -H "Content-Type: application/json" \
-d "{
\"operation\": \"TRANSFER\",
\"assetId\": \"$UPBOND_ASSET_ID\",
\"source\": { \"type\": \"VAULT_ACCOUNT\", \"id\": \"$UPBOND_VAULT_ID\" },
\"destination\": { \"type\": \"ONE_TIME_ADDRESS\", \"oneTimeAddress\": { \"address\": \"0x1111111111111111111111111111111111111111\" } },
\"amount\": \"12345.00\",
\"externalTxId\": \"refund-2026-000123\",
\"signer\": { \"keyId\": \"$KEY_ID\", \"envelope\": \"$ENVELOPE\" }
}"
# 4. 照会
curl -s "$UPBOND_API_BASE/v1/transactions/external_tx_id/refund-2026-000123" \
-H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN"
# 5. 一覧(next-page ヘッダーを見るため -i)
curl -si "$UPBOND_API_BASE/v1/transactions?after=1762470000000&limit=200" \
-H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN"
PHP
Laravel での例です。依存は firebase/php-jwt(クライアントアサーション)と phpseclib/phpseclib:^3(封筒)です。
PHP 8.4 以前の
openssl_public_encrypt() は使えませんPHP 8.4 以前の標準 openssl 拡張は OAEP のハッシュが SHA-1 固定で、この API が要求する SHA-256 の封筒を作れません(422 / 1411 になります。PHP 8.5 で digest_algo 引数が追加されました)。封筒には phpseclib 3 を使ってください。封筒の生成だけを Node.js の小さなプロセスに切り出す構成でも構いません。
<?php
namespace App\Services;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
final class UpbondTransfer
{
public function __construct(
private readonly string $apiKey, // UPBOND_API_KEY
private readonly string $authBase, // UPBOND_AUTH_BASE
private readonly string $apiBase, // UPBOND_API_BASE
private readonly string $vaultId, // UPBOND_VAULT_ID
private readonly string $assetId, // UPBOND_ASSET_ID
private readonly string $privateKeyPem, // file_get_contents(UPBOND_PRIVATE_KEY_FILE)
private readonly string $signingSecret, // UPBOND_SIGNING_SECRET (base64)
) {}
/** RFC 7523 client assertion (RS256), valid for 60 seconds. */
private function clientAssertion(): string
{
$now = time();
return JWT::encode([
'iss' => $this->apiKey,
'sub' => $this->apiKey,
'aud' => $this->authBase,
'jti' => (string) Str::uuid(),
'iat' => $now,
'exp' => $now + 60,
], $this->privateKeyPem, 'RS256');
}
/** Opaque access token, cached until 30 seconds before expiry. */
private function accessToken(): string
{
// Namespaced per auth server and API key so two configurations never share a token.
$cacheKey = 'upbond.access_token.'.sha1($this->authBase.'|'.$this->apiKey);
return Cache::remember($cacheKey, 270, function () {
$res = Http::asForm()->post($this->authBase.'/oauth/token', [
'grant_type' => 'client_credentials',
'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion' => $this->clientAssertion(),
])->throw();
return $res->json('access_token');
});
}
private function headers(array $extra = []): array
{
return array_merge([
'X-API-Key' => $this->apiKey,
'Authorization' => 'Bearer '.$this->accessToken(),
], $extra);
}
/** Signing-environment key, cached for a day and refreshed on a 1410. */
private function signerKey(bool $force = false): array
{
$cacheKey = 'upbond.signer_key.'.sha1($this->apiBase.'|'.$this->apiKey);
if ($force) {
Cache::forget($cacheKey);
}
return Cache::remember($cacheKey, 86400, function () {
return Http::withHeaders($this->headers())
->get($this->apiBase.'/v1/upbond/signer')
->throw()
->json();
});
}
/** The request a bound envelope names: seven fields exactly as sent, LF-joined
* (feeLevel defaults to MEDIUM and note to "" when the body omits them). */
private function canonicalRequest(array $body): string
{
return implode("\n", [
$body['assetId'],
$body['source']['id'],
$body['destination']['oneTimeAddress']['address'],
$body['amount'],
$body['feeLevel'] ?? 'MEDIUM',
$body['externalTxId'],
$body['note'] ?? '',
]);
}
/**
* RSA-OAEP with SHA-256 and MGF1-SHA-256, empty label, over the bound plaintext
* 0x01 || secret(32) || sha256(canonicalRequest)(32) || issuedAt(8, BE ms).
*/
private function envelope(array $key, array $body): array
{
$rsa = PublicKeyLoader::load($key['publicKeyPem'])
->withPadding(RSA::ENCRYPTION_OAEP)
->withHash('sha256')
->withMGFHash('sha256');
$secret = base64_decode($this->signingSecret, true);
$plaintext = "\x01"
.$secret
.hash('sha256', $this->canonicalRequest($body), true)
.pack('J', (int) floor(microtime(true) * 1000));
try {
return [
'keyId' => $key['keyId'],
'envelope' => base64_encode($rsa->encrypt($plaintext)),
];
} finally {
// Neither the plaintext nor the secret copy outlives the call.
sodium_memzero($plaintext);
sodium_memzero($secret);
}
}
/** One refund = one transaction. Returns ['id' => ..., 'status' => ...]. */
public function create(string $externalTxId, string $address, string $amount, ?string $note = null): array
{
$body = [
'operation' => 'TRANSFER',
'assetId' => $this->assetId,
'source' => ['type' => 'VAULT_ACCOUNT', 'id' => $this->vaultId],
'destination' => ['type' => 'ONE_TIME_ADDRESS', 'oneTimeAddress' => ['address' => $address]],
'amount' => $amount,
'externalTxId' => $externalTxId,
];
if ($note !== null) {
$body['note'] = $note;
}
for ($attempt = 0; $attempt < 2; $attempt++) {
// A fresh envelope per attempt: it is bound to this body and to "now".
$request = $body + ['signer' => $this->envelope($this->signerKey($attempt > 0), $body)];
$res = Http::withHeaders($this->headers(['Idempotency-Key' => $externalTxId]))
->timeout(90)
->post($this->apiBase.'/v1/transactions', $request);
// 1410: the signer key rotated — fetch it again and re-send the same request.
if ($res->status() === 422 && $res->json('code') === 1410 && $attempt === 0) {
continue;
}
return $res->throw()->json();
}
throw new \RuntimeException('unreachable');
}
public function get(string $txId): array
{
return Http::withHeaders($this->headers())
->get($this->apiBase.'/v1/transactions/'.$txId)
->throw()
->json();
}
public function getByExternalTxId(string $externalTxId): array
{
return Http::withHeaders($this->headers())
->get($this->apiBase.'/v1/transactions/external_tx_id/'.rawurlencode($externalTxId))
->throw()
->json();
}
}
Cache::remember の 270 秒は、5 分のトークン寿命から 30 秒引いた値です。複数プロセスで動かす場合も、キャッシュを共有すればトークンの取得は 5 分に 1 回で済みます。