1.接口说明
身份证合并(API)定义:将身份证正面与反面图片自动合并为一张标准图片,并识别返回结构化字段,降低用户录入成本,提升远程实名认证体验。
1.1主要功能
身份证合并接口能够自动合并身份证正反面图片为一张标准图片,并准确识别照片文字信息并返回。其主要功能包括:
- 智能合并:
- 自动合并身份证正反面图片到一张图片。
- 多类型覆盖:
- 支持模糊、光照不均、透视畸变、复杂背景等低质量图像。
- 证件风险检测:
- 智能判断图片完整度,支持复印件检测、翻拍检测。
- 服务稳定:
- 提供弹性服务,算法迭代优化对稳定性无影响。
- 高精度与性能:
- 识别准确率高,响应速度快,体验佳。
1.2接入场景
支持各种程序和设备接入,包括小程序、APP、采集设备等,灵活适用于不同应用场景。
2.请求信息
2.1请求地址(URL)
POST http(s)://ocr-api.shiliuai.com/api/id_card_merge/v1
2.2请求方式
POST
2.3请求头(header)
| 参数 | 类型 | 说明 |
|---|---|---|
| Content-Type | string | application/json |
| Authorization | string | 'APPCODE ' + 您的AppCode (注意英文空格) |
| 参数 | 类型 | 说明 |
|---|---|---|
| Content-Type | string | application/json |
| x-ca-key | string | 您的AppKey |
| x-ca-timestamp | string | 时间戳(毫秒) |
| x-ca-signature | string | 签名sign |
签名方法:
str = app_key×tamp&app_secret sign = md5(str)
2.4请求体(body)
| 参数 | 是否必填 | 类型 | 说明 |
|---|---|---|---|
| image_base64_1 | 必填 | string | base64编码的图片文件1 |
| image_base64_2 | 必填 | string | base64编码的图片文件2 |
| width | 选填 | int | 合并图的宽度,默认为1050 |
| height | 选填 | int | 合并图的高度,默认为1500 |
| card_margin_ratio | 选填 | float | 证件边距比例,定义为边距/证件长边,默认为0.1 |
| dpi | 选填 | int | 合并图dpi,默认为300 |
| min_file_size | 选填 | int | 最小文件大小(单位字节),例如102400表示100kB,默认不压缩 |
| max_file_size | 选填 | int | 最大文件大小,默认为None |
3.返回信息
3.1返回类型
JSON
3.2返回码
| 参数名 | 类型 | 说明 |
|---|---|---|
| code | int | 返回码,0表示成功 |
| message | string | 返回信息 |
3.3返回信息
| 参数 | 类型 | 说明 |
|---|---|---|
| code | int | 错误码 |
| msg | string | 错误信息(英文) |
| msg_cn | string | 错误信息(中文) |
| success | bool | 是否成功 |
| image_id | string | 图片ID |
| request_id | string | 唯一请求ID |
| data | object | 包含合并结果与识别信息 |
3.4返回示例
成功返回示例
{
'code': 200,
'msg': 'OK',
'msg_cn': '成功',
'success': True,
'image_id': image id,
'request_id': request id,
'data': data, 具体看下面
}
data = {
'data_1': data_1, ocr result of image 1, data_1和data_2见下面
'data_2': data_2, ocr result of image 2,
'result_base64': merged image base64
}
data_1[2] = {
'is_front': bool, 是否正面
'complete_score': float, [0, 1], 完整度
'is_complete': bool, 是否完整,当complete_score==1时,为True
'unoccluded_score': float, [0, 1], 无遮挡程度
'is_unoccluded': bool, 是否无遮挡,当unoccluded_score>0.99时,为True
'clear_score': float, [0, 1], 清晰度,用文字可识别度计算
'is_clear': bool, 是否清晰,当clear_score>0.5时,为True
# 如果是正面,有下列项:
'name': string, 姓名
'sex': string, 性别,"男"/"女"
'ethnicity': string, 民族,ex: "汉"
'birth_date': string, 出生日期,ex: "1999年1月10日"
'address': string, 地址
'id_number': string, 身份证号
# 如果是反面,有下列项:
'authority': string, 签发机关
'valid_period': string,有效期限
}
错误返回示例
{
'code': error code,
'msg': error message,
'msg_cn': 中文错误信息,
'success': False,
'image_id': image id,
'request_id': request id,
'data': {}
}
3.5错误码
| 错误码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 错误请求,比如参数错误 |
| 401 | 未经授权 |
| 403 | 禁止访问 |
| 500 | 内部错误 |
4.示例代码
4.1 Python
# -*- coding: utf-8 -*-
import requests
import base64
import json
# 请求接口
URL = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"
# 图片转base64
def get_base64(file_path):
with open(file_path, 'rb') as f:
data = f.read()
b64 = base64.b64encode(data).decode('utf8')
return b64
def demo(appcode, file_path_1, file_path_2):
# 请求头
headers = {
'Authorization': 'APPCODE %s' % appcode,
'Content-Type': 'application/json'
}
# 请求体
b64_1 = get_base64(file_path_1)
b64_2 = get_base64(file_path_2)
data = {"image_base64_1": b64_1, "image_base64_2": b64_2}
# 请求
response = requests.post(url=URL, headers=headers, json=data)
content = json.loads(response.content)
print(content)
if __name__=="__main__":
appcode = "你的APPCODE"
file_path_1 = "身份证正面图片路径"
file_path_2 = "身份证反面图片路径"
demo(appcode, file_path_1, file_path_2)
import requests
import base64
import json
import hashlib
import time
# 请求接口
URL = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"
# 图片转base64
def get_base64(file_path):
with open(file_path, 'rb') as f:
data = f.read()
b64 = base64.b64encode(data).decode('utf8')
return b64
# md5
def md5(s):
return hashlib.md5(s.encode("utf8")).hexdigest()
def demo(app_key, app_secret, file_path_1, file_path_2):
# 请求头
t = int(time.time() * 1000)
s = "%s&%s&%s" % (app_key, t, app_secret)
sign = md5(s)
headers = {
'x-ca-key': app_key,
'x-ca-timestamp': t,
'x-ca-signature': sign,
'Content-Type': 'application/json'
}
# 请求体
b64_1 = get_base64(file_path_1)
b64_2 = get_base64(file_path_2)
data = {
"image_base64_1": b64_1,
"image_base64_2": b64_2,
"width": 1050,
"height": 1500,
"dpi": 300,
"min_file_size": 102400,
"max_file_size": 204800
}
# 请求
response = requests.post(url=URL, headers=headers, json=data)
content = json.loads(response.content)
print(content)
if __name__=="__main__":
app_key = "你的APP_KEY"
app_secret = "你的APP_SECRET"
file_path_1 = "身份证正面图片路径"
file_path_2 = "身份证反面图片路径"
demo(app_key, app_secret, file_path_1, file_path_2)
4.2 PHP
//图片转base64
function get_base64($path){
if($fp = fopen($path, "rb", 0)) {
$binary = fread($fp, filesize($path)); // 文件读取
fclose($fp);
$b64 = base64_encode($binary); // 转base64
}else{
$b64="";
printf("%s 文件不存在", $path);
}
return $b64;
}
$url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1";
$appcode = "你的appcode";
$img_path_1 = "图片身份证正面图片路径";
$img_path_2 = "图片身份证反面图片路径";
$method = "POST";
//请求头
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
array_push($headers, "Content-Type:application/json");
//请求体
$b64_1 = get_base64($img_path_1);
$b64_2 = get_base64($img_path_2);
$data = array(
"image_base64_1" => $b64_1,
"image_base64_2" => $b64_2
);
$post_data = json_encode($data);
//请求
$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);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
var_dump($result);
function get_base64($path){
if($fp = fopen($path, "rb", 0)) {
$binary = fread($fp, filesize($path)); // 文件读取
fclose($fp);
$b64 = base64_encode($binary); // 转base64
}else{
$b64="";
printf("%s 文件不存在", $path);
}
return $b64;
}
$url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1";
$img_path_1 = "身份证正面图片路径";
$img_path_2 = "身份证反面图片路径";
$method = "POST";
//请求头
$app_key = "你的app_key";
$app_secret = "你的app_secret";
$timestamp=time();
$sign_string = $app_key . "&" . $timestamp . "&" . $app_secret;
$sign = md5($sign_string);
$headers = array();
array_push($headers, "Content-Type:application/json");
array_push($headers, "x-ca-key:" . $app_key);
array_push($headers, "x-ca-timestamp:" . $timestamp);
array_push($headers, "x-ca-signature:" . $sign);
//请求体
$b64_1 = get_base64($img_path_1);
$b64_2 = get_base64($img_path_2);
$data = array(
"image_base64_1" => $b64_1,
"image_base64_2" => $b64_2
);
$post_data = json_encode($data);
//请求
$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);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
var_dump($result);
4.3 Java
//main.java
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
public class Main {
public static String get_base64(String path) {
String b64 = "";
try {
byte[] content = FileUtils.readFileToByteArray(new File(path));
b64 = Base64.getEncoder().encodeToString(content);
} catch (IOException e) {
e.printStackTrace();
}
return b64;
}
public static void main(String[] args) {
String url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"; // 请求接口
String appcode = "你的APPCODE";
String imgFile1 = "本地身份证正面图片路径";
String imgFile2 = "本地身份证反面图片路径";
Map headers = new HashMap<>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/json");
// 请求体
JSONObject requestObj = new JSONObject();
requestObj.put("image_base64_1", get_base64(imgFile1));
requestObj.put("image_base64_2", get_base64(imgFile2));
String bodys = requestObj.toString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
StringEntity entity = new StringEntity(bodys, "UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int stat = response.getStatusLine().getStatusCode();
if (stat != 200) {
System.out.println("Http code: " + stat);
return;
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
System.out.println(res_obj.toJSONString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Demo {
public static String get_base64(String path) {
String b64="";
try {
File file = new File(path);
if (!file.exists()) {
System.err.println("文件不存在: " + path);
return b64;
}
byte[] content = FileUtils.readFileToByteArray(file);
b64 = Base64.getEncoder().encodeToString(content);
} catch (IOException e) {
System.err.println("读取文件失败: " + e.getMessage());
e.printStackTrace();
}
return b64;
}
public static String MD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"; // 请求接口
String imgFile1 = "本地身份证正面图片路径";
String imgFile2 = "本地身份证反面图片路径";
String app_key = "你的APPKEY";
String app_secret = "你的APPSECRET";
String timestamp = System.currentTimeMillis() + "";
String sign = MD5(app_key + "&" + timestamp + "&" + app_secret);
Map headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("x-ca-key", app_key);
headers.put("x-ca-timestamp", timestamp);
headers.put("x-ca-signature", sign);
JSONObject requestObj = new JSONObject();
requestObj.put("image_base64_1", get_base64(imgFile1));
requestObj.put("image_base64_2", get_base64(imgFile2));
String bodys = requestObj.toString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
StringEntity entity = new StringEntity(bodys, "UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int stat = response.getStatusLine().getStatusCode();
if (stat != 200) {
System.out.println("Http code: " + stat);
System.out.println("Http " + EntityUtils.toString(response.getEntity()));
return;
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
System.out.println(res_obj.toJSONString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.4 C#
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MyCSharpApp
{
public class Program
{
public static string GetBase64(string path)
{
string b64 = "";
try
{
byte[] content = File.ReadAllBytes(path);
b64 = Convert.ToBase64String(content);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return b64;
}
public static async Task Main(string[] args)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"; // 请求接口
string appcode = "你的APPCODE";
string imgFile_1 = "本地身份证正面图片路径";
string imgFile_2 = "本地身份证反面图片路径";
Dictionary headers = new Dictionary
{
{ "Authorization", "APPCODE " + appcode }
};
JObject requestObj = new JObject();
requestObj["image_base64_1"] = GetBase64(imgFile_1);
requestObj["image_base64_2"] = GetBase64(imgFile_2);
string body = requestObj.ToString();
try
{
using (HttpClient client = new HttpClient())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
StringContent content = new StringContent(body, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Http code: {(int)response.StatusCode}");
return;
}
string responseContent = await response.Content.ReadAsStringAsync();
JObject resObj = JObject.Parse(responseContent);
Console.WriteLine(resObj.ToString(Formatting.Indented));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MyCSharpApp
{
public class Program
{
public static string GetBase64(string path)
{
string b64 = "";
try
{
byte[] content = File.ReadAllBytes(path);
b64 = Convert.ToBase64String(content);
}
catch (Exception e)
{
Console.Error.WriteLine("读取文件失败: " + e.Message);
}
return b64;
}
public static string CalculateMD5(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
public static async Task Main(string[] args)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_merge/v1"; // 请求接口
string imgFile_1 = "本地身份证正面图片路径";
string imgFile_2 = "本地身份证反面图片路径";
string app_key = "你的APPKEY";
string app_secret = "你的APPSECRET";
string timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
string sign = CalculateMD5(app_key + "&" + timestamp + "&" + app_secret);
Dictionary headers = new Dictionary
{
{ "x-ca-key", app_key },
{ "x-ca-timestamp", timestamp },
{ "x-ca-signature", sign }
};
JObject requestObj = new JObject();
requestObj["image_base64_1"] = GetBase64(imgFile_1);
requestObj["image_base64_2"] = GetBase64(imgFile_2);
string body = requestObj.ToString();
try
{
using (HttpClient client = new HttpClient())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
StringContent content = new StringContent(body, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Http code: {(int)response.StatusCode}");
Console.WriteLine($"Http {await response.Content.ReadAsStringAsync()}");
return;
}
string responseContent = await response.Content.ReadAsStringAsync();
JObject resObj = JObject.Parse(responseContent);
Console.WriteLine(resObj.ToString(Formatting.Indented));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}