在?FastAdmin?中生成一個?OCR 發票識別插件,可以按照以下步驟進行開發。這里假設你已經熟悉 FastAdmin 插件開發的基本流程,并會使用 Composer 和 PHP 擴展。
1. 創建插件骨架
使用 FastAdmin 命令行工具生成插件基礎結構:
php think addon -a ocr -c create
這會生成一個插件目錄?/addons/ocr/
,包含以下關鍵文件:
text
/addons/ocr/ ├── controller/ │ └── Invoice.php # 發票識別控制器 ├── model/ │ └── Invoice.php # 數據模型(可選) ├── view/ │ └── index/ │ └── index.html # 前端頁面 ├── config.php # 插件配置 ├── info.ini # 插件信息(你提供的元數據) └── OCR.php # 插件主類
2. 配置插件信息
編輯?/addons/ocr/info.ini
:
ini
name = ocr title = 發票識別插件 intro = 通過OCR技術識別增值稅發票、電子發票等 author = A website = https://www.seacent.com version = 1.0.4 state = 1 url = /addons/ocr/invoice license = regular licenseto = 102801
3. 編寫發票識別邏輯
(1)集成 OCR 服務
可以選擇以下 OCR API:
百度 OCR(高精度版,適合增值稅發票)
騰訊云 OCR(支持多種發票類型)
阿里云 OCR(穩定,適合企業級應用)
這里以?百度 OCR?為例(需安裝?aip-php-sdk
):
bash
composer require baidu/aip-sdk
(2)編寫控制器?/addons/ocr/controller/Invoice.php
php
<?php namespace addons\ocr\controller;use think\addons\Controller; use AipOcr; // 百度OCR SDKclass Invoice extends Controller {// 百度OCR配置protected $config = ['app_id' => '你的APP_ID','api_key' => '你的API_KEY','secret_key' => '你的SECRET_KEY',];// 上傳圖片并識別public function index(){if ($this->request->isPost()) {$file = $this->request->file('invoice_image');if (!$file) {$this->error('請上傳發票圖片');}$imagePath = $file->getRealPath();$client = new AipOcr($this->config['app_id'], $this->config['api_key'], $this->config['secret_key']);// 調用百度OCR增值稅發票識別$result = $client->vatInvoice($imagePath);if (isset($result['words_result'])) {$this->success('識別成功', null, $result['words_result']);} else {$this->error('識別失敗:' . ($result['error_msg'] ?? '未知錯誤'));}}return $this->fetch();} }
4. 前端頁面?/addons/ocr/view/index/index.html
html
<div class="panel panel-default"><div class="panel-heading">發票識別</div><div class="panel-body"><form class="form-horizontal" method="post" enctype="multipart/form-data"><div class="form-group"><label class="col-sm-2 control-label">上傳發票</label><div class="col-sm-10"><input type="file" name="invoice_image" accept="image/*" class="form-control"></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10"><button type="submit" class="btn btn-primary">開始識別</button></div></div></form><!-- 識別結果顯示 -->{if isset($result)}<div class="alert alert-success"><h4>識別結果</h4><pre>{:json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)}</pre></div>{/if}</div> </div>
5. 注冊插件路由
在?/addons/ocr/config.php
?中添加:
php
return ['invoice' => 'ocr/invoice/index', // 訪問路徑 /addons/ocr/invoice ];
6. 測試插件
啟用插件:
進入 FastAdmin 后臺?
系統管理 -> 插件管理
,找到?發票識別插件
?并啟用。
訪問插件:
打開?
http://你的域名/addons/ocr/invoice
,上傳發票圖片測試識別效果。