FastAdmin 中生成插件
在 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
,上传发票图片测试识别效果。