PHP实现小程序OCR实名认证
此demo仅用于身份证识别,OCR内所有基本都通用,修改一下请求的接口及类型即可
基于laravel框架
public function demo(Request $request){
###文件上传至本地及获取绝对路径
$file = $request->file('file');
$newFile = date('Y-m-d');
$url_path = 'uploads/'.$newFile;
if ($file->isValid()) {
$clientName = $file->getClientOriginalName();
$entension = $file->getClientOriginalExtension();
$newName = md5(date("Y-m-d H:i:s") . $clientName) . "." . $entension;
$file->move($url_path, $newName);
$namePath = $url_path . '/' . $newName; #文件绝对路径
}
###进入正题
$file = $namePath; #获取本地文件路径
$type = 'photo';
#配置
$APPID = APPID;#小程序id
$APPSECRET = APPSEC;#小程序密钥
#获取access_token
$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
//缓存access_token
session_start();
$_SESSION['access_token'] = "";
$_SESSION['expires_in'] = 0;
if (!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
{
$json = file_get_contents($access_token);
$json = json_decode($json, true);
$_SESSION['access_token'] = $json['access_token'];
$_SESSION['expires_in'] = time() + 7200;
$ACCESS_TOKEN = $json["access_token"];
} else
{
$ACCESS_TOKEN = $_SESSION["access_token"];
}
#判断是否缓存access_token
if (!empty($ACCESS_TOKEN))
{
$url = "https://api.weixin.qq.com/cv/ocr/idcard?access_token=".$ACCESS_TOKEN."&type=".$type;
if(class_exists('\CURLFile')){
$data = ['img' => new \CURLFile($file)];
}else{
$data = ['img' => "@{$file}"];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
curl_close($ch);
$wxrs_id_card=json_decode($res,true);
return $wxrs_id_card; #输出结果
}else{
return "access_token获取失败,请重试";
}
}
返回示例:
{
“errcode”: 0,
“errmsg”: “ok”,
“type”: “Front”,#正面
“name”: “云墨”,#名称
“id”: “XXXXXXXXXXXXXXXXX”,#身份证号码
“addr”: “身份证详细地址”,
“gender”: “男”,
“nationality”: “汉”,
“birth”: “2002-12-12”,
“card_property”: 4
}
详见微信开发文档:
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/img-ocr/ocr/idCardOCR.html