Chapter 4: Let AI Be Your Financial Assistant โ Building an ECPay Payment Reconciliation Tool
In Chapter 2, we learned how to write a "web scraping tool." That sounds cool, but honestly, there are plenty of scraping tools on the market that can do similar things.
If you want to use AI to land big freelance projects worth over $3,000 (or 100,000 NTD), you must embed AI into your client's most critical pain point: cash flow and reconciliation.
Imagine you run an e-commerce site or a crowdfunding platform. Every day, you receive dozens of orders from ECPay (Green World, Taiwan's leading payment gateway). Every evening before leaving, the boss has to log into the ECPay backend and manually check each transaction: which customer paid, which credit card failed.
What if we could build a CrewAI tool that lets a "Financial Accounting Agent" automatically call ECPay's API to check payments, then write a daily reconciliation report and email it to the boss?
That is the moment when technology transforms into extreme business value.
๐ฏ Chapter Objectives
- Quickly understand the basic integration concepts of the ECPay API (Why can't you just call the API directly? What is HashKey encryption?).
- Use Vibe Prompts to wrap the tedious ECPay query logic into a CrewAI tool.
- Build a strict "Financial Accounting Agent" that handles billing for us.
๐ Step 1: Core Concepts of ECPay Integration
ECPay, Taiwan's most popular payment gateway, has very strict API rules to ensure transaction and query security.
You cannot simply send a GET request to a URL and get data like you would with a public API.
Before sending any request, you must:
- Sort all parameters (e.g.,
MerchantID,MerchantTradeNo) alphabetically. - Prepend and append your unique
HashKeyandHashIV. - Then apply SHA256 hashing to generate a unique
CheckMacValue. - ECPay will recalculate the check code on its end. If it doesn't match yours, the request is rejected immediately.
๐ฅ [Vibe Coder's Pitfall Guide]
Payment APIs involve real money. It is strongly recommended that during development and testing, you absolutely use the official ECPay "Test Environment" with dedicated MerchantID and HashKey. Never use production keys for testing, or you may create real bad debts.
Why This Matters (Business Value)
For a business owner, every minute spent manually reconciling payments is a minute not spent on growth. A single missed payment can lead to shipping goods without receiving money โ a direct loss. By automating this with an AI agent, you:
- Save labor costs: A part-time accountant costs at least $500/month. Your agent works 24/7 for free after initial setup.
- Reduce errors: Humans make mistakes when tired. AI never does.
- Speed up cash flow: Real-time payment confirmation means faster order fulfillment and happier customers.
- Scale without hiring: As order volume grows, your agent handles it effortlessly.
How We Will Implement (Vibe Coding Approach)
We will use CrewAI's @tool decorator to create a custom tool that simulates ECPay's query API (for safety). Then we'll assign that tool to a financial agent who will use it to check orders and produce a professional report. The entire process is driven by Vibe Prompts โ you describe what you want, and AI writes the code.
๐ ๏ธ Step 2: Build the ECPay Query Tool with Vibe
Implementing SHA256 encryption from scratch is painful for beginners. Fortunately, this is where Vibe Coding shines!
We don't need to calculate encryption ourselves. We simply ask AI to wrap ECPay's encryption logic into a @tool that the agent can use.
(Note: For teaching safety and to avoid leaking real payment keys, the following prompt will ask AI to use mock data. But the architecture is identical to a production version.)
๐ฅ [Vibe Prompt Battle Spell]
I am using CrewAI. Please write a Custom Tool named ECPayOrderInquiryTool.
Requirements:
1. Use the @tool decorator.
2. This tool must accept one parameter: order_id (string, representing the order number).
3. Internal logic: This tool queries the payment status of an ECPay order. (For teaching safety, use a mock dictionary to simulate database response, e.g., {"status": "SUCCESS", "amount": 1500, "buyer": "Mr. Wang from Taichung"}. Do not actually implement SHA256 encryption and API calls, but leave a comment block for future expansion.)
4. [Most Important] Provide extremely detailed Docstring so the agent knows exactly when to call this tool and how to pass the order_id.
AI will perfectly produce this weapon for the financial agent:
from crewai.tools import tool
import json
@tool("ECPayOrderInquiryTool")
def check_ecpay_order(order_id: str) -> str:
"""
This is the ultimate reconciliation tool for querying the real payment status of an ECPay (Green World) order.
When your task requires confirming whether a specific order has been paid successfully, call this tool.
The input parameter must be the exact order ID string (order_id), e.g., 'VT202606270001'.
The tool returns JSON-formatted status information for that order.
"""
# โ ๏ธ [Future Implementation Area] In the production version, this section will implement:
# - Sorting parameters (MerchantID, MerchantTradeNo, etc.) alphabetically
# - Prepend/append HashKey and HashIV
# - SHA256 hashing to generate CheckMacValue
# - Use requests.post to call https://payment.ecpay.com.tw/Cashier/QueryTradeInfo
# [Teaching Simulation Area] Simulate ECPay's response
mock_db = {
"VT202606270001": {
"status": "PAID",
"amount": 3999,
"buyer": "Mr. Wang from Taichung",
"payment_date": "2026/06/27 10:00:00"
},
"VT202606270002": {
"status": "PENDING",
"amount": 300,
"buyer": "Ms. Lin from Taipei",
"payment_date": ""
}
}
if order_id in mock_db:
# Data returned to the agent must be converted to a string
return json.dumps(mock_db[order_id], ensure_ascii=False)
else:
return json.dumps({
"status": "NOT_FOUND",
"message": "Order not found. Please verify the order ID."
})
What Just Happened?
- What: We created a custom CrewAI tool that mimics querying ECPay's payment status. The tool accepts an order ID and returns a JSON string with status, amount, buyer, and payment date.
- Why: This tool encapsulates the complex API logic (encryption, HTTP request) into a simple function call. The agent doesn't need to know how ECPay works โ it just calls
check_ecpay_order("VT..."). - How: We used a Vibe Prompt to instruct AI to write the code. The prompt specified the tool name, parameter, mock logic, and detailed docstring. AI generated the implementation, including future expansion comments.
Expanding the Tool for Production
In a real deployment, you would replace the mock dictionary with actual API calls. Here's a skeleton of what that code would look like (you can ask AI to generate this later):
import hashlib
import requests
from urllib.parse import urlencode
def real_ecpay_query(order_id: str) -> dict:
merchant_id = "YOUR_MERCHANT_ID"
hash_key = "YOUR_HASH_KEY"
hash_iv = "YOUR_HASH_IV"
params = {
"MerchantID": merchant_id,
"MerchantTradeNo": order_id,
"TimeStamp": int(time.time())
}
# Sort params alphabetically
sorted_params = sorted(params.items())
raw_string = f"HashKey={hash_key}&" + urlencode(sorted_params) + f"&HashIV={hash_iv}"
check_mac = hashlib.sha256(raw_string.encode('utf-8')).hexdigest().upper()
params["CheckMacValue"] = check_mac
response = requests.post(
"https://payment.ecpay.com.tw/Cashier/QueryTradeInfo",
data=params
)
return response.json()
But for now, the mock version is perfect for learning and testing.
๐ผ Step 3: Hire a Super Strict Financial Accounting Agent
Now that the weapon is ready, we hand it to an agent that never makes mistakes and is extremely sensitive to numbers.
from crewai import Agent, Task, Crew
# Assume check_ecpay_order is imported from above
accountant = Agent(
role='Senior Financial Controller',
goal='Ensure every company cash flow is successfully received. Absolutely no bad debts or unconfirmed payments allowed.',
backstory='You have worked at one of the Big Four accounting firms for 20 years. You are extremely sensitive to numbers and hate it when people demand shipment without paying. You speak precisely and never smile.',
verbose=True,
tools=[check_ecpay_order], # ๐ฐ Give him the query tool!
allow_delegation=False
)
# Create a daily reconciliation task
inquiry_task = Task(
description='The boss asks you to check the latest payment status of two new orders: "VT202606270001" and "VT202606270002". Please call the tool to query them, then write a two-sentence formal briefing for me.',
expected_output='A short, formal payment status report containing buyer names and amounts.',
agent=accountant
)
# Assemble the crew and execute
crew = Crew(agents=[accountant], tasks=[inquiry_task])
result = crew.kickoff()
print(result)
When you run this, the accounting agent will call ECPayOrderInquiryTool twice in the terminal. After querying both orders, he will produce a stunning report in the tone of a 20-year veteran accountant:
"Report to the boss, regarding the two orders you asked me to check: The first order VT...01 (Mr. Wang from Taichung) has been confirmed received at 3,999 NTD, transaction normal. However, the second order VT...02 (Ms. Lin from Taipei) is currently in PENDING status โ 300 NTD has not been received yet. Please hold shipment until payment clears. I will continue monitoring for you."
What Just Happened?
- What: We created a CrewAI agent with a specific role (Senior Financial Controller), a clear goal (no bad debts), and a backstory that defines its personality. We gave it the ECPay tool and a task to check two orders.
- Why: By defining a strict, professional persona, the agent produces output that is trustworthy and actionable. The boss can immediately act on the report without second-guessing.
- How: The agent uses the tool automatically when the task requires it. CrewAI handles the orchestration โ the agent decides to call the tool, receives the result, and incorporates it into the final output.
Business Value Deep Dive
Let's quantify the return on investment for a small e-commerce business:
- Manual reconciliation time: 30 minutes per day (checking 50 orders). That's 15 hours per month.
- Hourly cost of a part-time accountant: $20/hour (or 600 NTD). Monthly cost: $300.
- AI agent setup time: 2 hours (once). After that, zero recurring cost.
- Error rate: Manual: ~2% (missed payments, wrong amounts). AI: 0%.
- Cost of one missed payment: Average order value $50. If 2% of 1500 monthly orders are missed, that's $1,500 loss per month.
By deploying this agent, the business saves $300/month in labor and avoids $1,500/month in potential losses โ a total of $1,800/month. For a freelance developer, building this for a client can easily command a $3,000โ$5,000 project fee.
โ Chapter Summary
Amazing! You have successfully used Vibe Coding to create a virtual financial assistant that understands Taiwan's payment gateway and even gives professional advice.
This is the ultimate commercial potential of CrewAI combined with Custom Tools. As long as you can wrap any complex API (ECPay, Google Sheets, Line Bot, etc.) into a Tool, your agent can handle any tedious business process, saving you thousands of dollars in monthly labor costs!
Key Takeaways
- ECPay integration requires SHA256 encryption with HashKey/HashIV โ but you don't need to write it yourself; Vibe Coding can generate the mock and production code.
- CrewAI Custom Tools allow you to encapsulate any external service into a simple function that agents can call.
- Agent persona matters: a strict, professional backstory makes the output more reliable and actionable.
- Business value: Automating financial reconciliation saves labor, reduces errors, and speeds up cash flow โ directly impacting the bottom line.
Transition to the Next Chapter
Now that you have built a financial agent that can query payment statuses, you might be thinking: "This is great, but what about actually sending the reconciliation report to the boss's email? And what if we need to handle hundreds of orders automatically every day?"
In the next chapter, Chapter 5: Automating the Full Workflow โ Email Reports and Scheduled Tasks, we will take this agent to the next level. You will learn how to:
- Integrate an email-sending tool (e.g., SMTP or SendGrid) so the agent can automatically email the daily reconciliation report to the boss.
- Use CrewAI's scheduling capabilities (or external cron jobs) to run the agent every evening without manual intervention.
- Expand the mock database to a real database (SQLite or Google Sheets) so the agent can query live order data.
- Add error handling and notifications so the boss gets alerted immediately if a payment fails.
By the end of Chapter 5, you will have a fully autonomous financial assistant that runs 24/7, saving your client thousands of dollars every month. Get ready to turn your AI agent into a true business automation powerhouse!