メインコンテンツへスキップ

トランザクション履歴の表示

トランザクション履歴は、Omiseアカウント残高に影響するすべてのアクティビティの完全な記録を提供します。このガイドでは、トランザクションデータの表示、フィルタリング、検索、およびエクスポートについて説明します。

概要

トランザクション履歴には以下が含まれます:

  • チャージ: 受け取った顧客の支払い
  • 返金: 顧客に返金された金額
  • 振込: 受取人への支払い
  • 手数料: プラットフォームおよびトランザクション手数料
  • 調整: 手動残高修正
  • 紛争: チャージバック関連のトランザクション

主要な機能

  • 完全な履歴: 残高に影響するすべてのトランザクション
  • 高度なフィルタリング: タイプ、日付、金額、ステータスでフィルター
  • 検索機能: 特定のトランザクションを素早く検索
  • ページネーション: 大量のトランザクションを処理
  • エクスポートオプション: レポート用のデータダウンロード
  • リアルタイム更新: トランザクションが発生すると表示

トランザクションの取得

すべてのトランザクションをリスト

const omise = require('omise')({
secretKey: 'skey_test_123456789',
});

// 最近のトランザクションを取得
async function getTransactions(limit = 20) {
try {
const transactions = await omise.transactions.list({
limit: limit,
order: 'reverse_chronological'
});

console.log(`${transactions.total}件のトランザクションを発見しました`);
console.log(`${transactions.total}件中${transactions.data.length}件を表示中`);

transactions.data.forEach(txn => {
console.log(`${txn.id}: ${txn.type} - ${txn.amount / 100} ${txn.currency.toUpperCase()}`);
});

return transactions;
} catch (error) {
console.error('トランザクションの取得に失敗しました:', error.message);
throw error;
}
}

// ページネーション付きトランザクション取得
async function getPaginatedTransactions(page = 1, perPage = 20) {
const offset = (page - 1) * perPage;

const transactions = await omise.transactions.list({
limit: perPage,
offset: offset,
order: 'reverse_chronological'
});

return {
data: transactions.data,
pagination: {
page: page,
per_page: perPage,
total: transactions.total,
total_pages: Math.ceil(transactions.total / perPage),
has_more: transactions.data.length === perPage
}
};
}

// 日付範囲でトランザクションを取得
async function getTransactionsByDateRange(startDate, endDate) {
const from = new Date(startDate).toISOString();
const to = new Date(endDate).toISOString();

const transactions = await omise.transactions.list({
from: from,
to: to,
order: 'reverse_chronological'
});

console.log(`${startDate}から${endDate}までのトランザクション:`);
console.log(`合計: ${transactions.total}`);

return transactions;
}

// 使用例
getTransactions(10);
getPaginatedTransactions(1, 20).then(result => {
console.log(`${result.pagination.total_pages}ページ中${result.pagination.page}ページ目`);
});

APIレスポンス

{
"object": "list",
"data": [
{
"object": "transaction",
"id": "trxn_test_5xyz789abc",
"type": "credit",
"amount": 100000,
"currency": "thb",
"created": "2024-01-15T10:30:00Z",
"source": "chrg_test_123456789"
}
],
"limit": 20,
"offset": 0,
"total": 150,
"location": "/transactions",
"order": "chronological",
"from": "2024-01-01T00:00:00Z",
"to": "2024-01-31T23:59:59Z"
}

フィルタリングと検索

高度なフィルタリング

class TransactionFilter {
constructor() {
this.filters = {};
}

async byDateRange(startDate, endDate) {
this.filters.from = new Date(startDate).toISOString();
this.filters.to = new Date(endDate).toISOString();
return this;
}

async byType(type) {
this.filters.type = type; // 'credit' または 'debit'
return this;
}

async byAmountRange(minAmount, maxAmount) {
this.filters.minAmount = minAmount;
this.filters.maxAmount = maxAmount;
return this;
}

async execute() {
const transactions = await omise.transactions.list({
from: this.filters.from,
to: this.filters.to,
limit: 100,
order: 'reverse_chronological'
});

let filtered = transactions.data;

if (this.filters.type) {
filtered = filtered.filter(txn => txn.type === this.filters.type);
}

if (this.filters.minAmount || this.filters.maxAmount) {
filtered = filtered.filter(txn => {
if (this.filters.minAmount && txn.amount < this.filters.minAmount) return false;
if (this.filters.maxAmount && txn.amount > this.filters.maxAmount) return false;
return true;
});
}

return filtered;
}
}

// 使用例
const filter = new TransactionFilter();
const results = await filter
.byDateRange('2024-01-01', '2024-01-31')
.byType('credit')
.byAmountRange(100000, 1000000)
.execute();

console.log(`${results.length}件のマッチするトランザクションを発見しました`);

トランザクションのエクスポート

CSVへのエクスポート

import csv
from datetime import datetime, timedelta

def export_transactions_csv(start_date, end_date, filename='transactions.csv'):
"""トランザクションをCSVにエクスポート"""

# トランザクションを取得
transactions = omise.Transaction.retrieve(
created={
'gte': start_date.isoformat(),
'lte': end_date.isoformat()
},
limit=1000,
order='chronological'
)

# CSVに書き込み
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)

# ヘッダーを書き込み
writer.writerow([
'トランザクションID',
'日付',
'タイプ',
'金額',
'通貨',
'ソース',
'説明'
])

# データを書き込み
for txn in transactions.data:
writer.writerow([
txn.id,
datetime.fromtimestamp(txn.created).strftime('%Y-%m-%d %H:%M:%S'),
txn.type,
txn.amount / 100,
txn.currency.upper(),
txn.source if hasattr(txn, 'source') else 'N/A',
f"{txn.type.capitalize()}トランザクション"
])

print(f"{len(transactions.data)}件のトランザクションを{filename}にエクスポートしました")
return filename

# 使用例
start = datetime.now() - timedelta(days=30)
end = datetime.now()
export_transactions_csv(start, end, 'monthly_transactions.csv')

一般的なユースケース

1. 月次財務レポート

async function generateMonthlyFinancialReport(year, month) {
const startDate = new Date(year, month - 1, 1);
const endDate = new Date(year, month, 0);

const transactions = await omise.transactions.list({
from: startDate.toISOString(),
to: endDate.toISOString(),
limit: 1000,
order: 'chronological'
});

const report = {
period: `${startDate.toLocaleDateString('ja-JP', { month: 'long', year: 'numeric' })}`,
summary: {
total_transactions: transactions.total,
credits: 0,
debits: 0,
net: 0
},
daily_breakdown: {},
transactions: transactions.data
};

transactions.data.forEach(txn => {
if (txn.type === 'credit') {
report.summary.credits += txn.amount;
} else if (txn.type === 'debit') {
report.summary.debits += txn.amount;
}

const day = new Date(txn.created).toISOString().split('T')[0];
if (!report.daily_breakdown[day]) {
report.daily_breakdown[day] = { credits: 0, debits: 0, count: 0 };
}
report.daily_breakdown[day].count++;
report.daily_breakdown[day][txn.type === 'credit' ? 'credits' : 'debits'] += txn.amount;
});

report.summary.net = report.summary.credits - report.summary.debits;

console.log(`月次レポート: ${report.period}`);
console.log(`トランザクション数: ${report.summary.total_transactions}`);
console.log(`入金: ${report.summary.credits / 100} THB`);
console.log(`出金: ${report.summary.debits / 100} THB`);
console.log(`純額: ${report.summary.net / 100} THB`);

return report;
}

// 使用例
generateMonthlyFinancialReport(2024, 1);

ベストプラクティス

1. 大規模データセットにページネーションを実装

async function getAllTransactions() {
const allTransactions = [];
let offset = 0;
const limit = 100;
let hasMore = true;

while (hasMore) {
const batch = await omise.transactions.list({
limit: limit,
offset: offset,
order: 'reverse_chronological'
});

allTransactions.push(...batch.data);

offset += limit;
hasMore = batch.data.length === limit;

console.log(`${allTransactions.length}件のトランザクションを取得しました...`);
}

return allTransactions;
}

2. トランザクションデータのキャッシュ

import json
from datetime import datetime

class TransactionCache:
def __init__(self, cache_file='transaction_cache.json'):
self.cache_file = cache_file
self.cache = self.load_cache()

def load_cache(self):
"""ファイルからキャッシュを読み込む"""
try:
with open(self.cache_file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}

def save_cache(self):
"""キャッシュをファイルに保存"""
with open(self.cache_file, 'w') as f:
json.dump(self.cache, f)

def get_transactions(self, start_date, end_date, force_refresh=False):
"""キャッシュ付きでトランザクションを取得"""
cache_key = f"{start_date}_{end_date}"

if not force_refresh and cache_key in self.cache:
print("キャッシュされたデータを使用")
return self.cache[cache_key]

print("新しいデータを取得")
transactions = omise.Transaction.retrieve(
created={
'gte': start_date.isoformat(),
'lte': end_date.isoformat()
},
limit=1000
)

self.cache[cache_key] = {
'data': [self.serialize_transaction(t) for t in transactions.data],
'cached_at': datetime.now().isoformat()
}
self.save_cache()

return self.cache[cache_key]

def serialize_transaction(self, txn):
"""キャッシュ用にトランザクションを辞書に変換"""
return {
'id': txn.id,
'type': txn.type,
'amount': txn.amount,
'currency': txn.currency,
'created': txn.created
}

よくある質問

どのくらい前のトランザクションを取得できますか?

アカウントが作成されてからのすべての期間のトランザクションを取得できます。ただし、非常に古いトランザクションの場合は、APIパフォーマンスを最適化するために日付範囲を使用することを検討してください。

支払い方法でトランザクションをフィルタリングできますか?

APIは支払い方法による直接フィルタリングをサポートしていません。トランザクションを取得し、sourceフィールドに基づいてクライアント側でフィルタリングする必要があります。

リアルタイムのトランザクション更新を取得するにはどうすればよいですか?

トランザクションが発生したときにリアルタイム通知を受信するには、Webhookを使用してください。これはトランザクションリストをポーリングするよりも効率的です。

1回のリクエストで取得できるトランザクションの最大数は?

リクエストごとの最大制限は100です。より大きなデータセットの場合は、offsetパラメータでページネーションを使用してください。

履歴からトランザクションを削除できますか?

いいえ、トランザクションは削除できません。これらは永続的な監査証跡を形成します。レポートから特定のトランザクションを除外する必要がある場合は、アプリケーションロジックでフィルタリングしてください。

会計ソフトウェア用にトランザクションをエクスポートするにはどうすればよいですか?

CSVエクスポート機能を使用するか、Omise APIを使用して会計ソフトウェアと直接統合してください。多くの会計プラットフォームはOmise統合を提供しています。

最近のトランザクションがリストに表示されないのはなぜですか?

トランザクションがリストに表示されるまでに数秒かかる場合があります。Webhookを使用すると、すぐに通知されますが、トランザクションがまだリストAPIに含まれていない可能性があります。

顧客のメールでトランザクションを検索できますか?

トランザクションAPIは顧客の詳細による検索をサポートしていません。トランザクションに関連付けられたチャージを取得し、その顧客情報を確認する必要があります。

関連リソース

  • 残高概要 - アカウント残高の理解
  • 照合 - トランザクションと決済の照合
  • チャージ - チャージトランザクションの表示
  • 返金 - 返金トランザクションの表示
  • 振込 - 振込トランザクションの表示
  • APIリファレンス - 完全なトランザクションAPI

次のステップ