Tải hóa đơn
API tải file hóa đơn (PDF hoặc XML) theo mã tracking code, trả về nội dung file dạng base64.
API Endpoint
GET
https://einvoice-api-sandbox.sepay.vn/v1/invoices/{tracking_code}/downloadAPI Request
tracking_codestringrequired
Mã tracking của hóa đơn
typeenumrequired
Loại file cần tải (pdf hoặc xml)
API Response
Response thành công (200)
{
"success": true,
"data": {
"file_type": "pdf",
"file_name": "HD_0000589_20251215.pdf",
"content": "JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL1hPYmplY3Q..."
}
}successboolean
dataobject
Xử lý lỗi
400Bad RequestTham số type không hợp lệ (không phải pdf hoặc xml).
401UnauthorizedThiếu hoặc sai Bearer token.
404Not FoundKhông tìm thấy hóa đơn theo tracking_code.
Lưu ý
Lưu ý
- API trả về nội dung file dạng base64. Bạn cần decode base64 để lưu thành file PDF hoặc XML.
- Tham số
typechỉ chấp nhận hai giá trị:pdfhoặcxml. - Đảm bảo hóa đơn đã được phát hành thành công trước khi tải file.
Xử lý Base64 thành File
Sau khi gọi API thành công, bạn cần decode nội dung base64 và lưu thành file. Dưới đây là ví dụ với PHP:
PHPDecode Base64 và lưu file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php// Giả sử $response là kết quả từ API$response = json_decode($apiResult, true);if ($response['success']) {// Lấy nội dung base64 từ response$base64Content = $response['data']['content'];$fileName = $response['data']['file_name'];// Decode base64 thành binary$binaryContent = base64_decode($base64Content);// Kiểm tra decode thành côngif ($binaryContent === false) {throw new Exception('Lỗi decode base64');}// Lưu file$bytesWritten = file_put_contents($fileName, $binaryContent);if ($bytesWritten === false) {throw new Exception('Lỗi ghi file');}echo "Đã lưu file: {$fileName} ({$bytesWritten} bytes)";}
Các bước xử lý:
- Parse JSON response - Chuyển đổi response thành mảng PHP
- Lấy nội dung base64 - Truy cập
$response['data']['content'] - Decode base64 - Sử dụng
base64_decode()để chuyển thành binary - Lưu file - Sử dụng
file_put_contents()để ghi ra file
Lưu ý quan trọng
- Luôn kiểm tra kết quả
base64_decode()vì có thể trả vềfalsenếu chuỗi base64 không hợp lệ. - Đảm bảo thư mục lưu file có quyền ghi (write permission).
- Với file PDF, có thể kiểm tra header
%PDFsau khi decode để xác nhận file hợp lệ.
Code mẫu
1
2
3
curl --request GET \--url 'https://einvoice-api-sandbox.sepay.vn/v1/invoices/084e179d-d95a-11f0-aef4-52c7e9b4f41b/download?type=pdf' \--header 'Authorization: Bearer REPLACE_BEARER_TOKEN'