ข้ามไปยังเนื้อหาหลัก

การดู Transaction History

Transaction history ให้บันทึกที่สมบูรณ์ของกิจกรรมทั้งหมดที่ส่งผลต่อ balance ในบัญชี Omise ของคุณ คู่มือนี้ครอบคลุมการดู กรอง ค้นหา และส่งออกข้อมูล transaction

ภาพรวม

Transaction history ประกอบด้วย:

  • Charge: การชำระเงินจากลูกค้าที่ได้รับ
  • Refund: เงินที่คืนให้ลูกค้า
  • Transfer: การจ่ายเงินให้ผู้รับ
  • Fee: ค่าธรรมเนียมแพลตฟอร์มและ transaction
  • Adjustment: การแก้ไข balance ด้วยตนเอง
  • Dispute: Transaction ที่เกี่ยวข้องกับ chargeback

คุณสมบัติหลัก

  • ประวัติที่สมบูรณ์: Transaction ทั้งหมดที่ส่งผลต่อ Balance
  • การกรองขั้นสูง: กรองตามประเภท วันที่ จำนวนเงิน สถานะ
  • ความสามารถในการค้นหา: ค้นหา transaction เฉพาะอย่างรวดเร็ว
  • Pagination: จัดการ transaction ปริมาณมาก
  • ตัวเลือกการส่งออก: ดาวน์โหลดข้อมูลสำหรับรายงาน
  • การอัปเดตแบบเรียลไทม์: เห็น transaction เมื่อเกิดขึ้น

การดึง Transaction

แสดงรายการ Transaction ทั้งหมด

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

// Get recent transactions
async function getTransactions(limit = 20) {
try {
const transactions = await omise.transactions.list({
limit: limit,
order: 'reverse_chronological'
});

console.log(`Found ${transactions.total} transactions`);
console.log(`Showing ${transactions.data.length} of ${transactions.total}`);

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

return transactions;
} catch (error) {
console.error('Failed to retrieve transactions:', error.message);
throw error;
}
}

// Get transactions with pagination
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
}
};
}

// Get transactions by date range
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(`Transactions from ${startDate} to ${endDate}:`);
console.log(`Total: ${transactions.total}`);

return transactions;
}

// Example usage
getTransactions(10);
getPaginatedTransactions(1, 20).then(result => {
console.log(`Page ${result.pagination.page} of ${result.pagination.total_pages}`);
});

API Response

{
"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' or '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;
}
}

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

console.log(`Found ${results.length} matching transactions`);

การส่งออก Transaction

ส่งออกเป็น CSV

import csv
from datetime import datetime, timedelta

def export_transactions_csv(start_date, end_date, filename='transactions.csv'):
"""Export transactions to CSV"""

# Get transactions
transactions = omise.Transaction.retrieve(
created={
'gte': start_date.isoformat(),
'lte': end_date.isoformat()
},
limit=1000,
order='chronological'
)

# Write to CSV
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)

# Write header
writer.writerow([
'Transaction ID',
'Date',
'Type',
'Amount',
'Currency',
'Source',
'Description'
])

# Write data
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()} transaction"
])

print(f"Exported {len(transactions.data)} transactions to {filename}")
return filename

# Usage
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('en-US', { 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(`Monthly Report: ${report.period}`);
console.log(`Transactions: ${report.summary.total_transactions}`);
console.log(`Credits: ${report.summary.credits / 100} THB`);
console.log(`Debits: ${report.summary.debits / 100} THB`);
console.log(`Net: ${report.summary.net / 100} THB`);

return report;
}

// Usage
generateMonthlyFinancialReport(2024, 1);

แนวทางปฏิบัติที่ดีที่สุด

1. ใช้ Pagination สำหรับชุดข้อมูลขนาดใหญ่

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(`Fetched ${allTransactions.length} transactions...`);
}

return allTransactions;
}

2. แคชข้อมูล Transaction

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):
"""Load cache from file"""
try:
with open(self.cache_file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}

def save_cache(self):
"""Save cache to file"""
with open(self.cache_file, 'w') as f:
json.dump(self.cache, f)

def get_transactions(self, start_date, end_date, force_refresh=False):
"""Get transactions with caching"""
cache_key = f"{start_date}_{end_date}"

if not force_refresh and cache_key in self.cache:
print("Using cached data")
return self.cache[cache_key]

print("Fetching fresh data")
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):
"""Convert transaction to dict for caching"""
return {
'id': txn.id,
'type': txn.type,
'amount': txn.amount,
'currency': txn.currency,
'created': txn.created
}

คำถามที่พบบ่อย

ฉันสามารถดึง transaction ย้อนหลังได้ไกลแค่ไหน?

คุณสามารถดึง transaction จากช่วงเวลาใดก็ได้ตั้งแต่สร้างบัญชีของคุณ อย่างไรก็ตาม สำหรับ transaction ที่เก่ามาก ให้พิจารณาใช้ช่วงวันที่เพื่อเพิ่มประสิทธิภาพ API

ฉันสามารถกรอง transaction ตามวิธีการชำระเงินได้หรือไม่?

API ไม่รองรับการกรองโดยตรงตามวิธีการชำระเงิน คุณจะต้องดึง transaction และกรองฝั่งไคลเอนต์ตามฟิลด์ source

ฉันจะได้รับการอัปเดต transaction แบบเรียลไทม์ได้อย่างไร?

ใช้ webhook เพื่อรับการแจ้งเตือนแบบเรียลไทม์เมื่อ transaction เกิดขึ้น นี่มีประสิทธิภาพมากกว่าการ poll รายการ transaction

ฉันสามารถดึง transaction ได้สูงสุดกี่รายการต่อคำขอ?

จำกัดสูงสุดต่อคำขอคือ 100 สำหรับชุดข้อมูลที่ใหญ่กว่า ใช้ pagination ด้วยพารามิเตอร์ offset

ฉันสามารถลบ transaction ออกจากประวัติได้หรือไม่?

ไม่ได้ transaction ไม่สามารถลบได้ พวกเขาสร้างบันทึกการตรวจสอบถาวร หากคุณต้องการยกเว้น transaction บางรายการจากรายงาน ให้กรองออกในตรรกะแอปพลิเคชันของคุณ

ฉันจะส่งออก transaction สำหรับซอฟต์แวร์บัญชีได้อย่างไร?

ใช้ฟังก์ชัน CSV export หรือรวมโดยตรงกับซอฟต์แวร์บัญชีของคุณโดยใช้ Omise API แพลตฟอร์มบัญชีหลายแห่งเสนอการรวม Omise

ทำไม transaction ล่าสุดของฉันไม่ปรากฏในรายการ?

Transaction อาจใช้เวลาสองสามวินาทีจึงจะปรากฏในรายการ หากใช้ webhook คุณจะได้รับการแจ้งเตือนทันที แต่ transaction อาจยังไม่อยู่ใน list API

ฉันสามารถค้นหา transaction ด้วยอีเมลลูกค้าได้หรือไม่?

Transaction API ไม่รองรับการค้นหาตามรายละเอียดลูกค้า คุณจะต้องดึง charge ที่เกี่ยวข้องกับ transaction และตรวจสอบข้อมูลลูกค้า

แหล่งข้อมูลที่เกี่ยวข้อง

  • Balance Overview - ทำความเข้าใจ Account Balance ของคุณ
  • Reconciliation - จับคู่ Transaction กับ Settlement
  • Charges - ดู Charge Transaction
  • Refunds - ดู Refund Transaction
  • Transfers - ดู Transfer Transaction
  • API Reference - Transaction API ที่สมบูรณ์

ขั้นตอนถัดไป