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

 '你的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

发票识别
    
        
            
                上传发票
                
                    
                
            
            
                
                    开始识别
                
            
        

        
        {if isset($result)}
        
            识别结果
            {:json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)}
{/if}

5. 注册插件路由

在 /addons/ocr/config.php 中添加:

php

return [
    'invoice' => 'ocr/invoice/index', // 访问路径 /addons/ocr/invoice
];

6. 测试插件

  1. 启用插件

    • 进入 FastAdmin 后台 系统管理 -> 插件管理,找到 发票识别插件 并启用。

  2. 访问插件

    • 打开 http://你的域名/addons/ocr/invoice,上传发票图片测试识别效果。

posted on 2025-07-29 18:58  ljbguanli  阅读(34)  评论(0)    收藏  举报