NAV
php csharp java javascript python

App Applets ocr 設計概要

安全性設計

App Applets ocr是為滿足企業及個人身份資料影像辨識需要: 我們提供介接方式是透過https連線,只接受POST方式傳送交易資料。 本機制可以讓企業及個人透過此API,辨識個人身份証,健保卡,行照,駕照。

App Applets 目前提供之服務與格式

有1支API,各功能說明如下::

(1)影像資料辨識設定:讓企業及個人透過此API,辨識個人身份証,健保卡,行照,駕照。

我們提供介接方式是透過https連線,只接受POST方式傳送交易資料。

圖檔傳輸每次最多4mb

每個圖檔採用base64傳送 ,每個圖檔最大1mb,每個圖檔寬高不得低於800*600

介接網址

經銷商模式

位置 API介接網址 備註
測試區 https://ka.usecase.cc/api/init
正式區 https://ka.mypay.tw/api/init

資料加密方式

AES 256編碼 + base64編碼(附錄三資料加密方式)

加密金鑰

金鑰會透過mail發送,也可從管理後台取得

文字編碼

一律使用UTF-8相容編碼

影像資料辨識設定

<?php
/**
 * 經銷商串接-身分資料影像辨識
 */
final class AgentIdentification
{
    /**
     * 經銷商商務代號
     * @var string
     */
    public $agentUid = "518169081001";
    /**
     * 經銷商金鑰或認證碼
     * @var string
     */
    public $agentKey = "0DZP5XgV1dLXXNQqNUFZ7UXvSP6DBalS";
    /**
     * 特約商店商務代號(代特約商店發動)
     * @var string
     */
    public $storeUid = "289151880002";
    /**
     * 串接交易位置
     * @var string
     */
    public $url = "https://ka.usecase.cc/api/agent";
    /**
     * 取得串接欄位資料
     * @return array
     */
    public function getRawData()
    {
        $rawData = array();
        $rawData['store_uid'] = $this->storeUid;
        $rawData['images'] = [
                                 [
                                  'image_name' => '00001.jpg',
                                  'image_content' => '圖檔資料',
                                  'type' => 'identityFront'
                                 ],
                                 [
                                  'image_name' => '00002.jpg',
                                  'image_content' => '圖檔資料',
                                  'type' => 'catDriving'
                                 ],
                                 [
                                  'image_name' => '00003.jpg',
                                  'image_content' => '圖檔資料',
                                  'type' => 'scooterLicense'
                                 ],
                                 [
                                  'image_name' => '00004.jpg',
                                  'image_content' => '圖檔資料',
                                  'type' => 'carLicenseFront'
                                 ],
                                 [
                                  'image_name' => '00005.jpg',
                                  'url_path' => '圖檔url',
                                  'type' => 'healthIdCard'
                                 ]
                             ];

        return $rawData;
    }
    /**
     * 取得服務位置
     * @return array
     */
    public function getService()
    {
        return array(
            'service_name' => 'ocr',
            'cmd' => 'api/textdetection'
        );
    }
    /**
     * AES 256 加密
     * @param array $fields
     * @param string $key
     * @return string
     */
    public function encrypt($fields, $key)
    {
        $data = json_encode($fields);
        $size = openssl_cipher_iv_length('AES-256-CBC');
        $iv   = openssl_random_pseudo_bytes($size);
        $data = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        $data = base64_encode($iv . $data);
        return $data;
    }
    /**
     * 資料 POST 到主機
     * @param array $postData
     * @return mixed
     */
    public function post($postData = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    /**
     * 取得送出欄位資料
     * @return array
     */
    public function getPostData ()
    {
        $postData = array();
        $postData['agent_uid'] = $this->agentUid;
        $postData['service'] = $this->encrypt($this->getService(), $this->agentKey);
        $postData['encry_data'] = $this->encrypt($this->getRawData(), $this->agentKey);
        return $postData;
    }
    /**
     * 執行
     */
    public function run()
    {
        $json = $this->post($this->getPostData());
        echo $json;
    }
}

$AgentIdentification = new AgentIdentification();
$AgentIdentification->run();
?>

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Dynamic;
/// <summary>
/// 建議使用.net framework4.5以上版本
/// 1.請透過NuGet安裝Newtonsoft.Json,若.net framework小於4.5請安裝Newtonsoft.Json 7.0以下版本
/// 2.若貴司.net framework小於4 可能無法使用dynamic,若是自行組陣列
/// 3.若貴司.net framework小於3.5 可能無法使用AES類別,若是參閱微軟網站使用較舊方式進行加密
/// 4.若貴司.net framework小於3.5 可能沒有Linq可使用,故data只能組字串,Newtonsoft.Json也可能無法使用
/// </summary>
namespace MyPay {
    /// <summary>
    /// 經銷商串接-身分資料影像辨識
    /// </summary>
    public class AgentIdentification {
        /// <summary>
        /// 經銷商商務代號
        /// </summary>
        public string agentUid = "518169081001";
        /// <summary>
        /// 經銷商金鑰或認證碼
        /// </summary>
        public string agentKey = "0DZP5XgV1dLXXNQqNUFZ7UXvSP6DBalS";
        /// <summary>
        /// 特約商店商務代號
        /// </summary>
        public string storeUid = "289151880002";

        /// <summary>
        /// 串接交易位置
        /// </summary>
        public string url = "https://ka.usecase.cc/api/agent";
        /// <summary>
        /// 執行
        /// </summary>
        static void Main() {
            AgentIdentification simulator = new AgentIdentification();
            //僅限走https的Tls 1.2以上版本
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //發送至遠端
            var result = simulator.Post(simulator.GetPostData());

            System.Console.WriteLine(result);
        }
        /// <summary>
        /// 取得串接欄位資料
        /// </summary>
        private dynamic GetRawData() {

            ArrayList images = new ArrayList();

            dynamic image1 = new ExpandoObject();
            image1.image_name = "00001.jpg";
            image1.image_content = "圖檔資料";
            image1.type = "identityFront";
            images.Add(image1);

            dynamic image2 = new ExpandoObject();
            image2.image_name = "00002.jpg";
            image2.image_content = "圖檔資料";
            image2.type = "catDriving";
            images.Add(image2);

            dynamic image3 = new ExpandoObject();
            image3.image_name = "00003.jpg";
            image3.image_content = "圖檔資料";
            image3.type = "scooterLicense";
            images.Add(image3);

            dynamic image4 = new ExpandoObject();
            image4.image_name = "00004.jpg";
            image4.image_content = "圖檔資料";
            image4.type = "carLicenseFront";
            images.Add(image4);

            dynamic image5 = new ExpandoObject();
            image5.image_name = "00005.jpg";
            image5.url_path = "圖檔url";
            image5.type = "healthIdCard";
            images.Add(image5);


            dynamic rawData = new ExpandoObject();
            rawData.store_uid = this.storeUid;
            rawData.images = images;

            return rawData;
        }
        /// <summary>
        /// 取得服務位置
        /// </summary>
        private ServiceRequest GetService() {
            ServiceRequest rawData = new ServiceRequest();
            rawData.service_name = "ocr";
            rawData.cmd = "api/textdetection";
            return rawData;
        }
        /// <summary>
        /// 取得送出欄位資料
        /// </summary>
        private NameValueCollection GetPostData() {
            string data_json = JsonConvert.SerializeObject(GetRawData(), Formatting.None);
            string svr_json = JsonConvert.SerializeObject(GetService(), Formatting.None);; //依API種類調整

            //產生AES向量
            var IV = GetBytesIV();

            //進行加密
            var data_encode = Encrypt(data_json, this.agentKey, IV);
            var svr_encode = Encrypt(svr_json, this.agentKey, IV);

            //請注意使用的 Http Post 套件是否會自動加上UrlEncode,本Post範例為原始方式,故須加上UrlEncode
            //若自行使用的套件會自動補上UrlEncode,則請忽略下面的UrlEncode,避免做了兩次UrlEncode
            string data_toUrlEncode = HttpUtility.UrlEncode(data_encode);
            string svr_toUrlEncode = HttpUtility.UrlEncode(svr_encode);

            NameValueCollection postData = new NameValueCollection();
            postData["agent_uid"] = this.agentUid;
            postData["service"] = svr_toUrlEncode;
            postData["encry_data"] = data_toUrlEncode;
            return postData;
        }
        /// <summary>
        /// AES 256 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <param name="byteIV"></param>
        /// <returns></returns>
        private string Encrypt(string data, string key, byte[] byteIV) {
            var byteKey = System.Text.Encoding.UTF8.GetBytes(key);
            var enBytes = AES_Encrypt(data, byteKey, byteIV);
            return Convert.ToBase64String(BytesAdd(byteIV, enBytes));
        }
        /// <summary>
        /// AES 256 加密處理
        /// </summary>
        /// <param name="original"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        private byte[] AES_Encrypt(string original, byte[] key, byte[] iv) {
            try {
                var data = Encoding.UTF8.GetBytes(original);

                var cipher = Aes.Create().CreateEncryptor(key, iv);

                var de = cipher.TransformFinalBlock(data, 0, data.Length);
                return de;
            } catch {
                return null;
            }
        }
        /// <summary>
        /// 轉換Bytes
        /// </summary>
        /// <param name="a"></param>
        /// <param name="arryB"></param>
        /// <returns></returns>
        private byte[] BytesAdd(byte[] a, params byte[][] arryB) {
            List < byte > c = new List < byte > ();
            c.AddRange(a);
            arryB.ToList().ForEach(b => {
                c.AddRange(b);
            });
            return c.ToArray();
        }
        /// <summary>
        /// 產生AES的IV
        /// </summary>
        /// <returns></returns>
        private static byte[] GetBytesIV() {
            var aes = System.Security.Cryptography.AesCryptoServiceProvider.Create();
            aes.KeySize = 256;
            aes.GenerateIV();
            return aes.IV;
        }
        /// <summary>
        /// 資料 POST 到主機
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        private string Post(NameValueCollection pars) {
            string result = string.Empty;
            string param = string.Empty;
            if (pars.Count > 0) {
                pars.AllKeys.ToList().ForEach(key => {
                    param += key + "=" + pars[key] + "&";
                });
                if (param[param.Length - 1] == '&') {
                    param = param.Remove(param.Length - 1);
                }
            }
            byte[] bs = Encoding.UTF8.GetBytes(param);

            try {
                HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(this.url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                using(Stream reqStream = req.GetRequestStream()) {
                    reqStream.Write(bs, 0, bs.Length);
                }
                using(WebResponse wr = req.GetResponse()) {
                    Encoding myEncoding = Encoding.GetEncoding("UTF-8");
                    using(StreamReader myStreamReader = new StreamReader(wr.GetResponseStream(), myEncoding)) {
                        result = myStreamReader.ReadToEnd();
                    }
                }

                req = null;
            } catch (WebException ex) {
                throw new WebException(ex.Message + "params : " + param, ex, ex.Status, ex.Response);
            }
            return result;
        }
    }
    /// <summary>
    /// 串接服務請求欄位
    /// </summary>
    public class ServiceRequest {
        public string service_name { get; set; }
        public string cmd { get; set; }
    }
}

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URLEncoder;
import java.util.*;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.spongycastle.crypto.engines.AESEngine;
import org.spongycastle.crypto.modes.CBCBlockCipher;
import org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.params.ParametersWithIV;
import java.security.SecureRandom;
/**
 * 經銷商串接-身分資料影像辨識
 * 1. jackson-core 下載 https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
 * 2. jackson-databind 下載 https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
 * 3. jackson-annotations 下載 https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
 * 4. Spongy Castle 下載 https://mvnrepository.com/artifact/com.madgag.spongycastle/core
 */
public class AgentIdentification {
    /**
     * 經銷商商務代號
     */
    String agentUid = "518169081001";
    /**
     * 經銷商金鑰或認證碼
     */
    String agentKey = "0DZP5XgV1dLXXNQqNUFZ7UXvSP6DBalS";
    /**
     * 特約商店商務代號
     */
    String storeUid = "289151880002";
    /**
     * 串接交易位置
     */
    String url = "https://ka.usecase.cc/api/agent";
    /**
     * 執行
     * @param  args
     */
    public static void main(String[] args) {
        AgentIdentification simulator = new AgentIdentification();
        String json = simulator.post(simulator.getPostData());
        System.out.print(json);
    }

    @SuppressWarnings(value = { "unchecked", "deprecation" })
    /**
     * 取得串接欄位資料
     * @return 串接原始資料
     */
    public Map getRawData() {

        ArrayList images = new ArrayList();

        Map<Object, Object> image1 = new HashMap<Object, Object>();
        image1.put("image_name", "00001.jpg");
        image1.put("image_content", "圖檔資料");
        image1.put("type", "identityFront");
        images.add(image1);

        Map<Object, Object> image2 = new HashMap<Object, Object>();
        image2.put("image_name", "00002.jpg");
        image2.put("image_content", "圖檔資料");
        image2.put("type", "catDriving");
        images.add(image2);

        Map<Object, Object> image3 = new HashMap<Object, Object>();
        image3.put("image_name", "00003.jpg");
        image3.put("image_content", "圖檔資料");
        image3.put("type", "scooterLicense");
        images.add(image3);

        Map<Object, Object> image4 = new HashMap<Object, Object>();
        image4.put("image_name", "00004.jpg");
        image4.put("image_content", "圖檔資料");
        image4.put("type", "carLicenseFront");
        images.add(image4);

        Map<Object, Object> image5 = new HashMap<Object, Object>();
        image5.put("image_name", "00005.jpg");
        image5.put("url_path", "圖檔url");
        image5.put("type", "healthIdCard");
        images.add(image5);


        Map<Object, Object> rawData = new HashMap<Object, Object>();
        rawData.put("store_uid", this.storeUid);
        rawData.put("images", images);

        return rawData;
    }
    /**
     * 取得服務位置
     * @return 串接服務資料
     */
    public Map getService() {
        Map<Object, Object> rawData = new HashMap<Object, Object>();
        rawData.put("service_name", "ocr");
        rawData.put("cmd", "api/textdetection");
        return rawData;
    }
    /**
     * AES 256 加密
     * @param rawData 原始資料
     * @param AesKey AES256金鑰字串
     * @return 轉換成Base64資料
     */
    public String encrypt(Map rawData, String AesKey) {

        try {
            ObjectMapper objMapper = new ObjectMapper();

            byte[] data = objMapper.writeValueAsString(rawData).getBytes(UTF_8);
            byte[] key = AesKey.getBytes(UTF_8);

            // 16 bytes is the IV size for AES256
            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                    new CBCBlockCipher(new AESEngine()));
            // Random iv
            SecureRandom rng = new SecureRandom();
            byte[] ivBytes = new byte[16];
            rng.nextBytes(ivBytes);

            cipher.init(true, new ParametersWithIV(new KeyParameter(key),
                    ivBytes));
            byte[] outBuf = new byte[cipher.getOutputSize(data.length)];

            int processed = cipher
                    .processBytes(data, 0, data.length, outBuf, 0);
            processed += cipher.doFinal(outBuf, processed);

            byte[] outBuf2 = new byte[processed + 16]; // Make room for iv
            System.arraycopy(ivBytes, 0, outBuf2, 0, 16); // Add iv
            System.arraycopy(outBuf, 0, outBuf2, 16, processed);

            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(outBuf2);
            return base64;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
    /**
     * 資料 POST 到主機
     * @param qstr 串接資料
     * @return 服務回傳JSON資訊
     */
    public String post(String qstr) {
        String result = "";
        try {
            // 資料
            byte[] qstr_bytes = qstr.getBytes(StandardCharsets.UTF_8);

            URL iurl = new URL(this.url);
            SSLContext sc = SSLContext.getInstance("TLSv1.2"); // $NON-NLS-1$
            sc.init(null, null, new java.security.SecureRandom());

            HttpsURLConnection con = (HttpsURLConnection) iurl.openConnection();
            con.setSSLSocketFactory(sc.getSocketFactory());
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length",
                    String.valueOf(qstr_bytes.length));
            con.setRequestProperty("Accept-Charset", "UTF-8");

            con.setDoOutput(true);
            con.setDoInput(true);

            con.getOutputStream()
                    .write(qstr.getBytes(Charset.forName("UTF-8")));
            con.getOutputStream().flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine + "\r\n");
            }

            try {
                result = response.toString();
            } finally {
                in.close();
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return result;
    }
    /**
     * 取得送出欄位資料
     * @return POST完整資料
     */
    public String getPostData() {
        String postData = "";
        try {
            // Base64需要使用UrlEncode做傳輸
            String data_toUrlEncode = URLEncoder.encode(
                    this.encrypt(this.getRawData(), this.agentKey), "UTF-8");
            String svr_toUrlEncode = URLEncoder.encode(
                    this.encrypt(this.getService(), this.agentKey), "UTF-8");

            postData = "agent_uid=" + this.agentUid + "&service="
                    + svr_toUrlEncode + "&encry_data=" + data_toUrlEncode;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return postData;
    }
}

const crypto = require('crypto');
const httpRequest = require('https');

/**
 * 經銷商串接-身分資料影像辨識
 */
function AgentIdentification() {
    // 經銷商商務代號
    this.agentUid = "518169081001";
    // 經銷商金鑰或認證碼
    this.agentKey = "0DZP5XgV1dLXXNQqNUFZ7UXvSP6DBalS";
    // 特約商店商務代號
    this.storeUid = "289151880002";
    // 串接交易位置
    this.url = "https://ka.usecase.cc/api/agent";
};
/**
 * 取得串接欄位資料
 */
AgentIdentification.prototype.getRawData = function () {
    return {
        store_uid: this.storeUid,
        images: [
                    {
                     'image_name': "00001.jpg",
                     'image_content': "圖檔資料",
                     'type': "identityFront"
                    },
                    {
                     'image_name': "00002.jpg",
                     'image_content': "圖檔資料",
                     'type': "catDriving"
                    },
                    {
                     'image_name': "00003.jpg",
                     'image_content': "圖檔資料",
                     'type': "scooterLicense"
                    },
                    {
                     'image_name': "00004.jpg",
                     'image_content': "圖檔資料",
                     'type': "carLicenseFront"
                    },
                    {
                     'image_name': "00005.jpg",
                     'url_path': "圖檔url",
                     'type': "healthIdCard"
                    }
                ],

    };
};
/**
 * 取得服務位置
 */
AgentIdentification.prototype.getService = function () {
    return {
        service_name: "ocr",
        cmd: "api/textdetection"
    };
};
/**
 * AES 256 加密
 */
AgentIdentification.prototype.encrypt = function (fields, key) {
    let eData = JSON.stringify(fields);
    const blockSize = 16;
    const iv = crypto.randomBytes(blockSize);
    const encryptor = crypto.createCipheriv('aes-256-cbc', key, iv);
    let tmpCipher = encryptor.update(Buffer.from(eData));
    let finalCipher = encryptor.final();
    const tempData = Buffer.concat([tmpCipher, finalCipher], tmpCipher.length + finalCipher.length);
    let data = Buffer.concat([iv, tempData], iv.length + tempData.length).toString('base64');
    return data;
};
/**
 * 資料 POST 到主機
 */
AgentIdentification.prototype.post = function (postData) {
    return new Promise((res, rej) => {
        let options = {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            rejectUnauthorized: false
        };

        let send_process = httpRequest.request(this.url, options, (api_res) => {
            let res_data = "";
            api_res.on('data', (tmp_data) => {
                res_data += tmp_data;
            });
            api_res.on('end', () => {
                res(res_data);
            });
        });

        send_process.write(JSON.stringify(postData));
        send_process.end();
    });
};
/**
 * 取得送出欄位資料
 */
AgentIdentification.prototype.getPostData = function () {
    return {
        "agent_uid": this.agentUid,
        "service": this.encrypt(this.getService(), this.agentKey),
        "encry_data": this.encrypt(this.getRawData(), this.agentKey)
    };
};
/**
 * 執行
 */
AgentIdentification.prototype.run = async function () {
    json = await this.post(this.getPostData())
    console.log(json);
};

AgentIdentification = new AgentIdentification();
AgentIdentification.run();

# -*- coding: utf-8 -*-
import json
import base64
import requests
from Crypto.Cipher import AES
from Crypto.Util import Padding
from Crypto.Random import get_random_bytes

"""經銷商串接-身分資料影像辨識
"""
class AgentIdentification:
    # 經銷商商務代號
    agentUid = "518169081001";
    # 經銷商金鑰或認證碼
    agentKey = b"0DZP5XgV1dLXXNQqNUFZ7UXvSP6DBalS";
    # 特約商店商務代號
    storeUid = "289151880002"
    # 串接交易位置
    url = "https://ka.usecase.cc/api/agent"

    def getRawData(self):
        """取得串接欄位資料

        Returns:
            {dict}: 欄位資料
        """
        rawData = {
            'store_uid': self.storeUid,
            'images': [
                          {
                           'image_name': "00001.jpg",
                           'image_content': "圖檔資料",
                           'type': "identityFront"
                          },
                          {
                           'image_name': "00002.jpg",
                           'image_content': "圖檔資料",
                           'type': "catDriving"
                          },
                          {
                           'image_name': "00003.jpg",
                           'image_content': "圖檔資料",
                           'type': "scooterLicense"
                          },
                          {
                           'image_name': "00004.jpg",
                           'image_content': "圖檔資料",
                           'type': "carLicenseFront"
                          },
                          {
                           'image_name': "00005.jpg",
                           'url_path': "圖檔url",
                           'type': "healthIdCard"
                          }
                      ],
        }
        return rawData

    def getService(self):
        """取得服務位置

        Returns:
            {dict}: 服務位置資料
        """
        return {
            'service_name': 'ocr',
            'cmd': 'api/textdetection'
        }

    def encrypt(self, fields, key):
        """AES 256 加密

        Args:
            fields {dict}: 欄位資料
            key {bytes}: AES金鑰

        Returns:
            {string}: 加密資料
        """
        data = json.dumps(fields, separators=(',', ':'))
        data = Padding.pad(data.encode('utf-8'), AES.block_size)
        iv = get_random_bytes(AES.block_size)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        data = cipher.encrypt(data)
        data = base64.b64encode(iv + data)
        return data

    def post(self, postData):
        """資料 POST 到主機

        Args:
            postData {dict}: 欄位資料

        Returns:
            {string}: JSON資料
        """
        result = requests.post(self.url, postData)
        return result.text

    def getPostData(self):
        """取得送出欄位資料

        Returns:
            {dict}: 欄位資料
        """
        postData = {
            'agent_uid': self.agentUid,
            'service': self.encrypt(self.getService(), self.agentKey),
            'encry_data': self.encrypt(self.getRawData(), self.agentKey)
        }
        return postData

    def run(self):
        """執行
        """
        json = self.post(self.getPostData())
        print(json)

AgentIdentification = AgentIdentification()
AgentIdentification.run()

回傳 JSON 結構如下:

{
    "content":[影像回傳參數,後面會說明,基本上images傳幾個,就會回傳幾個],
    "code": "B200",
    "msg": "執行成功"
}

『影像辨識』參數說明

欄位 型態 說明
agent_uid string(16) 經銷商商務代號
service text {"service_name": "ocp", "cmd": "api\/textdetection"}
JSON格式,AES256加密資料
encry_data text 『身份資料影像辨識』欄位參考
JSON格式,AES256加密資料

『身份資料影像辨識』欄位

參數名稱 型態 說明 必須
store_uid string 特約商店商務代號 必填
images array 收款人資訊 必填
『身分資料影像辨識圖檔陣列內容』欄位參考

『影像辨識』回傳欄位

參數名稱 型態 說明 備註
code string 執行狀態碼 『身分資料解析狀態碼』值參考
msg string 執行狀態訊息
content array 身分資料影像辨識回傳 『身分資料影像辨識回傳』值參考

『身分資料影像辨識圖檔陣列內容』欄位

參數名稱 型態 說明 必須
image_name string 圖檔名稱(本次唯一值+副檔名) 必填
image_content string 圖檔本體base64
url_path string url圖檔路徑
type string 辨識內容:identityFront(身分證正面),identityBack(身分證反面),catDriving(駕照), scooterLicense(機車行照), carLicenseFront(汽車行照正面),carLicenseBack(汽車行照反面), healthIdCard(健保卡) 必填

『身分資料解析狀態碼』欄位

value Description Type Additional Information
100 資料不正確 string
400 系統錯誤 string
B200 執行成功 string
B500 執行失敗 string

『身分資料影像辨識回傳』欄位

參數名稱 型態 說明 備註
code string 執行狀態碼 『身分資料解析狀態碼』值參考
msg string 執行狀態訊息
image_name string 身分資料影像辨識圖檔名稱
type string 身分資料影像辨識執行方式 辨識內容:identityFront(身分證正面),identityBack(身分證反面),catDriving(駕照), scooterLicense(機車行照), carLicenseFront(汽車行照正面),carLicenseBack(汽車行照反面), healthIdCard(健保卡)
result array 回傳辨識結果 每筆『機車行照回傳資料』欄位參考
每筆『身份證正面回傳資料』欄位參考
每筆『身份證背面回傳資料』欄位參考
每筆『健保卡回傳資料』欄位參考
每筆『駕照回傳資料』欄位參考
每筆『汽車行照正面回傳資料』欄位參考
每筆『汽車行照背面回傳資料』欄位參考

『機車行照回傳資料』欄位

參數名稱 型態 說明 備註
license string 牌照
car_owner string 車主
address string 住址
brand_type string 廠牌型式
engine_number string 引擎號碼
body_number string 車身號碼
color string 顏色
displacement string 排氣量
issue_date string 發照日期MYYMMDD
factory_year_month string 出廠年月YYYYMM
replacement_date string 換補照日期MYYMMDD
expired_date string 有效日期MYYMMDD或[免定換]字串
jurisdiction_number string 管轄編號

『身份證正面回傳資料』欄位

參數名稱 型態 說明 備註
name string 姓名
birthday string 出生年月日MYYMMDD
gender string 性別
issue_date string 發照日期MYYMMDD
issue_site_id string 發證地點
id string 身份證號
category_code string 領補換類別代碼

『身份證背面回傳資料』欄位

參數名稱 型態 說明 備註
father string 父親
mother string 母親
spouse string 配偶
service_type string 役別
address string 地址

『健保卡回傳資料』欄位

參數名稱 型態 說明 備註
name string 姓名
id string 身分證號
birthday string 出生年月日MYYMMDD
card_number string 卡號

『駕照回傳資料』欄位

參數名稱 型態 說明 備註
name string 姓名
gender string 性別
birthday string 出生年月日MYYMMDD
types_of_drivers_license string 駕照類型
drivers_license_number string 駕照號碼
license_conditions string 持照條件
address string 住址
jurisdiction_number string 管轄編號
issue_date string 發照日期MYYMMDD

『汽車行照正面回傳資料』欄位

參數名稱 型態 說明 備註
license string 牌照
name string 姓名
address string 住址
factory string 廠牌
year_of_manufacture string 出廠年月YYYYMM
pattern string 型式
exhaust_volume string 排氣量
fuel_type string 燃料種類
engine_number string 引擎號碼

『汽車行照背面回傳資料』欄位

參數名稱 型態 說明 備註
ag_title string 牌照標頭
original_issue_date string 原發照日期MYYMMDD
replacement_date string 更換日期MYYMMDD
expired_date string 有效日期MYYMMDD或[免定換]字串
color string 顏色

附錄一:金鑰管理

附錄二:資料加密方式說明

  1. 所有的API送出HTTPs請求之欄位中,service 和 encry_data 欄位皆進行 AES256+BASE64 加密處理。
  2. AES加密,格式為CBC,長度為256bits,金鑰長度32,IV長度16,傳遞內文為加密後組合IV並經過Base64轉換後傳出。
  3. IV資料建議隨機產生。

附錄三:API模擬串接服務

提供模擬使用HTTP Protocol,透過POST方式傳遞資料到MYTIX, 並且得到回傳結果。