PHP 调用微信小程序 OCR 接口
添加插件
在小程序后台 设置 - 第三方设置 - 插件管理 中添加 OCR支持 插件。
服务购买
在 微信OCR识别 | 微信服务平台 中购买接口配额。
免费版本目前配额为 100 次/日,可用 36500 天。
接入
如果是小程序前端接入,参考上方网页“接入文档”即可。
定义接口常量
const OCR_BANKCARD = 'https://api.weixin.qq.com/cv/ocr/bankcard';
const OCR_BIZ_LICENSE = 'https://api.weixin.qq.com/cv/ocr/bizlicense';
const OCR_DRIVER_LICENSE = 'https://api.weixin.qq.com/cv/ocr/drivinglicense';
const OCR_ID_CARD = 'https://api.weixin.qq.com/cv/ocr/idcard';
const OCR_PRINTED_TEXT = 'https://api.weixin.qq.com/cv/ocr/comm';
const OCR_VEHICLE_LICENSE = 'https://api.weixin.qq.com/cv/ocr/driving';
CURL 接入
/*** @param string $api* @param string $access_token* @param UploadedFile|null $image UploadedFile 强制数据类型可删除或替换,该参数为已上传文件对象* @param string|null $image_url** @return array|null*/
public function imageOcr(string $api, string $access_token, ?UploadedFile $image = null, ?string $image_url = null): ?array {if ((!$image && !$image_url)) {return null;}$cFile = curl_file_create($image->getPathname(),mime_content_type($image->getPathname()),$image->getFilename());$ch = curl_init();curl_setopt_array($ch, [CURLOPT_URL => $api . '?' . http_build_query(['access_token' => $access_token,'img_url' => $image_url]),CURLOPT_POST => true,CURLOPT_POSTFIELDS => ['img' => $cFile],CURLOPT_RETURNTRANSFER => true]);$response = curl_exec($ch);curl_close($ch);return json_decode($response, true);
}
GuzzleHttp 客户端接入
/*** @param string $api* @param string $access_token* @param UploadedFile|null $image UploadedFile 强制数据类型可删除或替换,该参数为已上传文件对象* @param string|null $image_url** @return array|null*/
public function imageOcr(string $api, string $access_token, ?UploadedFile $image = null, ?string $image_url = null): ?array {if ((!$image && !$image_url)) {return null;}$response = (new \GuzzleHttp\Client())->post($api, ['query' => ['access_token' => $access_token,'img_url' => $image_url],'multipart' => [['name' => 'img','contents' => file_get_contents($image->getPathname()),'filename' => $image->getFilename()]]])->getBody();return json_decode($response, true);
}
使用
假定 imageOcr
方法位于 WeChatOCR
类:
$ocr = new WeChatOCR();// 大多数框架中可以通过 $request->file('image') 的方式获得上传文件对象
$ocr->imageOcr(WeChatOCR::OCR_PRINTED_TEXT, $request->file('image'));// Image URL 方式
$ocr->imageOcr(WeChatOCR::OCR_ID_CARD, null, 'https://example.com/id_card.jpg');