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