-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract_invoice.php
More file actions
142 lines (124 loc) · 5.36 KB
/
Copy pathextract_invoice.php
File metadata and controls
142 lines (124 loc) · 5.36 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
/**
* Extract structured data from invoices using the Photon Commerce API.
*
* Submits an invoice (PDF, image, Word, HTML, or email) and returns 100+
* structured fields including vendor, line items, amounts, PO numbers,
* due dates, GL codes, payment terms, and bank details.
* 25+ languages supported; handwriting, stamps, and tables handled.
*
* Processing times (Managed Agents):
* Trial accounts: up to 24 hours
* Production: 5 minutes to 24 hours
*
* AI extraction (seconds, no Managed Agents):
* Contact support@photoncommerce.com to activate.
* Once active, submit to /api/v4 instead of /api/pro.
*
* Requires: guzzlehttp/guzzle (composer require guzzlehttp/guzzle)
*
* Docs: https://apidocs.photoncommerce.com
* Sandbox: https://sandbox-api.photoncommerce.com/api/v4/register (20 free calls)
*/
require 'vendor/autoload.php';
use GuzzleHttp\Client;
// Credentials — all four headers are required.
// Get yours from the dashboard at app.photoncommerce.com
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('USERNAME', 'YOUR_USERNAME');
define('API_KEY', 'YOUR_API_KEY');
define('PASSWORD', 'YOUR_PASSWORD');
define('SECRET_KEY', 'YOUR_SECRET_KEY');
// Sandbox: https://sandbox-api.photoncommerce.com (20 free calls, no card needed)
// Production: https://api.photoncommerce.com
define('BASE_URL', 'https://sandbox-api.photoncommerce.com');
$client = new Client([
'base_uri' => BASE_URL,
'headers' => [
'CLIENT-ID' => CLIENT_ID,
'AUTHORIZATION' => 'apikey ' . USERNAME . ':' . API_KEY,
'PASSWORD' => PASSWORD,
'SECRET-KEY' => SECRET_KEY,
],
]);
/**
* Submit an invoice for extraction. Returns the photon_key for result retrieval.
* Supply either $filePath (local file) or $url (publicly accessible document URL).
*/
function submitInvoice(
Client $client,
string $filePath = null,
string $url = null,
string $webhookUrl = null,
string $authToken = null,
string $id = null,
string $subaccount = null,
int $pageStart = null,
int $pageEnd = null
): string {
if (!$filePath && !$url) {
throw new InvalidArgumentException('Provide either filePath or url.');
}
$query = ['doctype' => 'invoice'];
if ($url) $query['url'] = $url;
if ($webhookUrl) $query['webhook_url'] = $webhookUrl;
if ($authToken) $query['auth_token'] = $authToken;
if ($id) $query['ID'] = $id;
if ($subaccount) $query['subaccount'] = $subaccount;
if ($pageStart !== null) $query['page_start'] = $pageStart;
if ($pageEnd !== null) $query['page_end'] = $pageEnd;
$options = ['query' => $query];
if ($filePath) {
$options['multipart'] = [
['name' => 'pdf', 'contents' => fopen($filePath, 'r'), 'filename' => basename($filePath)],
];
}
// For AI extraction (seconds), replace /api/pro with /api/v4 — contact support@photoncommerce.com to activate.
$response = $client->post('/api/pro', $options);
$data = json_decode($response->getBody(), true);
return $data['photon_key'];
}
/** Retrieve the extracted JSON for a submitted invoice. */
function fetchResult(Client $client, string $photonKey): array
{
$response = $client->get('/api/v4/json', ['query' => ['photon_key' => $photonKey]]);
$data = json_decode($response->getBody(), true);
return $data['data'] ?? [];
}
/** Poll until the extraction is complete and return the result. */
function waitForResult(Client $client, string $photonKey, int $pollInterval = 20, int $timeout = 3600): array
{
$deadline = time() + $timeout;
while (time() < $deadline) {
$result = fetchResult($client, $photonKey);
$status = $result['Status'] ?? null;
if ($status && $status !== 'pending' && $status !== 'processing') {
return $result;
}
echo " Status: " . ($status ?? 'pending') . " — retrying in {$pollInterval}s...\n";
sleep($pollInterval);
}
throw new RuntimeException("Extraction not complete after {$timeout}s");
}
// --- Option A: submit from a local file ---
$photonKey = submitInvoice($client, filePath: 'invoice.pdf');
// --- Option B: submit via a publicly accessible URL ---
// $photonKey = submitInvoice($client, url: 'https://example.com/invoice.pdf');
echo "Submitted. photon_key: $photonKey\n";
echo "Waiting for extraction to complete...\n";
// Poll until ready (or pass webhookUrl to submitInvoice to receive a callback instead)
$result = waitForResult($client, $photonKey);
echo "\n--- Invoice Data ---\n";
echo "Vendor: " . ($result['Vendor_Name'] ?? '') . "\n";
echo "Invoice No: " . ($result['Invoice_Number'] ?? '') . "\n";
echo "Invoice Date: " . ($result['Date'] ?? '') . "\n";
echo "Due Date: " . ($result['Due_Date'] ?? '') . "\n";
echo "PO Number: " . ($result['PO_Number'] ?? '') . "\n";
echo "Subtotal: " . ($result['Subtotal'] ?? '') . "\n";
echo "Tax: " . ($result['Tax'] ?? '') . "\n";
echo "Total: " . ($result['Total'] ?? '') . ' ' . ($result['Currency_Code'] ?? '') . "\n";
echo "Payment Terms: " . ($result['Payment_Terms'] ?? '') . "\n";
echo "\n--- Line Items ---\n";
foreach ($result['Line_Items'] ?? [] as $item) {
echo " Line {$item['Line']}: {$item['Description']} — Qty {$item['QTY']} x {$item['Price']} = {$item['Amount']}\n";
}