基于阿里云市场API服务实现增值税发票识别【OCR】

TOC

前言

我们在做系统的时候存在这么一个场景,客户如果要在平台充值金额,需要开票审核,由财务确认后进行充值,为了方便财务审核以及发票信息的记录查询,需要对发票内容进行记录,人工输入效率太低,这时候就需要用到OCR识别。

方案

市面上已经存在许多开放AI能力的平台,包括百度大脑,腾讯云,讯飞开放平台,阿里云等等,在经过多次尝试对比之后,最终采用阿里云市场里【四川涪擎大数据技术有限公司】所提供的API服务(不是在打广告)

这个API服务的价格、识别率的性价比比较高,上线之后也没有遇到什么问题。

实现

确认好API服务之后,点击进去查看相关信息

由于是API方式调用,所以非常简单,并且官方已经提供了原生http请求的示例代码,只需要复制粘贴封装一下即可。

这里贴出PHP的示例代码

<?php
error_reporting(E_ALL || ~E_NOTICE);


$host = "https://nvoiceocr.market.alicloudapi.com";
$path = "/taxinvoice";
$method = "POST";
$appcode = "你自己的AppCode";//开通服务后 买家中心-查看AppCode
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
//根据API的要求,定义相对应的Content-Type
array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
$querys = "";
$bodys = "image=http://img3.fegine.com/image/taxinvoice.jpg";
//或者base64
//$bodys = "image=data:image/jpeg;base64,/9j/4A......";
$url = $host . $path;


$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);


if (1 == strpos("$" . $host, "https://")) {
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
$out_put = curl_exec($curl);


$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);


list($header, $body) = explode("

", $out_put, 2);
if ($httpCode == 200) {
    print("正常请求计费(其他均不计费)<br>");
    print($body);
} else {
    if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
        print("参数错误");
    } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
        print("AppCode错误");
    } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
        print("请求的 Method、Path 或者环境错误");
    } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
        print("服务未被授权(或URL和Path不正确)");
    } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
        print("套餐包次数用完");
    } elseif ($httpCode == 500) {
        print("API网关错误");
    } elseif ($httpCode == 0) {
        print("URL错误");
    } else {
        print("参数名错误 或 其他错误");
        print($httpCode);
        $headers = explode("
", $header);
        $headList = array();
        foreach ($headers as $head) {
            $value = explode(':', $head);
            $headList[$value[0]] = $value[1];
        }
        print($headList['x-ca-error-message']);
    }
}

其中需要注意的是bodys支持url或者base64的上传,这里建议优先采用url,因为发票图片肯定需要上传的,上传完成之后上传url识别即可。

总结

不仅仅是发票识别,包括身份证,人脸,快递,驾驶证,车牌等等,都已存在成熟识别的服务,在未来越来越多的功能将以服务的方式提供,让专业的人干专业的事,使得我们能将更多的精力放在业务实现上,降低开发的成本。

原文地址:https://www.cnblogs.com/leestar54/p/14055687.html