MENU

[PHP实用接口]身份证,二维码 OCR识别函数

March 31, 2019 • Read: 4498 • 程序源码

“利用PHP识别是假的,封装的接口到是真的”,emmmm.... 是的,就是这个意思,只不过封装的接口而已...

许久未更新博客,这两个函数之前写东西时搞的,分享出来做做水文吧。

1.身份证识别

接口来自于 腾讯AI开放平台 (免费),用自己的QQ登录一个平台,然后创建一个应用,审核之后得到app_idkey参数,再配置一下即可使用。

Ps:应用创建之后是需要审核的,大概一天左右吧;如果不想创建,复制下面代码直接用我的也行,但我不保证长期能用哈,所以还是推荐自己搞一个。

参数:card_type代表正反面;

身份证识别代码:

<?php
function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0, $async = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $httpheader[] = "Accept:*/*";
    $httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
    $httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
    $httpheader[] = "Connection:close";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    if ($async) {
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    }
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, true);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}

//本站签名算法
function getReqSign($params /* 关联数组 */ , $appkey /* 字符串*/ ) {
    // 1. 字典升序排序
    ksort($params);
    
    // 2. 拼按URL键值对
    $str = '';
    foreach ($params as $key => $value) {
        if ($value !== '') {
            $str .= $key . '=' . urlencode($value) . '&';
        }
    }
    
    // 3. 拼接app_key
    $str .= 'app_key=' . $appkey;
    
    // 4. MD5运算+转换大写,得到请求签名
    $sign = strtoupper(md5($str));
    return $sign;
}

/* 身份证照片识别,API提取自腾讯OCR */
function SFZ_OCR_($path) {
    if (!isset($path))
        return false;
    
    //腾讯AI开放平台
    $app_id = 2113119487;
    $key = 'fWA7BjyR3e4USb2B';
    $api = "https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr";
    
    $post['app_id'] = $app_id;
    $post['time_stamp'] = intval(time());
    $post['nonce_str'] = time();
    $post['card_type'] = 0; //正面
    $post['image'] = base64_encode(file_get_contents($path));
    $post['sign'] = getReqSign($post, $key);
    $ret = get_curl($api, $post);
    return $ret;
}

$path = 'https://open.youtu.qq.com/static/img/icon_id_02.26ed156.jpg';
echo "<img src='$path?" . time() . "' /><br/><br/>";
$ret = json_decode(SFZ_OCR_($path), true);
print_r($ret);

效果图:
PHP身份证识别效果图.PNG
简单讲解:get_curl() http请求函数,getReqSign();签名函数【重要】,SFZ_OCR_() 接口请求函数,函数返回的是json,所有需要Json_decode才能看到数组。

官方文档:https://ai.qq.com/doc/ocridcardocr.shtml


2.二维码识别

接口是抓自草料二维码识别,函数传入的二维码URL地址,暂不支持本地二维码。

<?php
/* 二维码图片识别,草料API提取自草料 */
function qrcode_OCR($img) {
    $api = "https://cli.im/apis/up/deqrimg";
    $post = 'img=' . urlencode($img);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $httpheader[] = "X-Requested-With: XMLHttpRequest";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}

$qrcode = 'http://qr.topscan.com/api.php?text=https://qzone.work/';
echo "<img src='$qrcode?" . time() . "' /><br/><br/>";
$ret = json_decode(qrcode_OCR($qrcode), true);
print_r($ret);

效果图:
PHP二维码识别.PNG

函数返回同样是 String json,需要json_decode();

Last Modified: June 13, 2020
Leave a Comment

16 Comments
  1. cialis commercial 2012 in descending order
    cialis vs viagra comparison submit.pl
    generic cialis
    - ed side effects
    cialis presciption form gp

  2. http://mewkid.net/who-is-xandra/ - Amoxicillin Amoxicillin 500mg Capsules wno.cado.qzone.work.plj.bf http://mewkid.net/who-is-xandra/

  3. http://mewkid.net/who-is-xandra/ - Amoxil Causes Gallstones Amoxicillin 500mg Capsules dgv.upks.qzone.work.vcw.id http://mewkid.net/who-is-xandra/

  4. У нас вы найдете Ремонт очистных сооружений, а также блоки биологической загрузки для очистных сооружений, мы можем произвести Монтаж насоса и настройка автоматики. Бурение неглубоких скважин, Инженерные изыскания, Монтаж водоснабжения.

    В нашей фирме вы можете купить ЁМКОСТНОЕ И РЕЗЕРВУАРНОЕ ОБОРУДОВАНИЕ, Резервуары и емкости цилиндрические (РВС, РГС), Мешалка на заказ, Ленточный фильтр-пресс, Поворотные колодцы, БиоБлок (ББ), Нефтеотделители (отстойники), ОДЪЕМНЫЕ УСТРОЙСТВА И МЕТАЛЛОКОНСТРУКЦИИ Шнековые питатели, ВОДООЧИСТНОЕ ОБОРУДОВАНИЕ Флокуляторы, ПОДЪЕМНЫЕ УСТРОЙСТВА И МЕТАЛЛОКОНСТРУКЦИИ Нестандартные металлоконструкции, ОЧИСТКА ЛИВНЕВЫХ СТОЧНЫХ ВОД Песколовки тангенциальные, НАСОСНОЕ И КОМПРЕССОРНОЕ ОБОРУДОВАНИЕ (Грунфос, КСБ, Вило, КИТ, Взлёт, ТВП) Дренажные насосы, ВОДОПОДГОТОВКУ Озонаторы и хлотаторы, а также все для автомойки Очистное сооружение для моек легкового транспорта.

    У нас проектирует, производит Монтаж водоснабжения.

    обезвоживание осадка сточных вод а главное блоки биологической загрузки для очистных сооружений биозагрузка купить

  5. http://mewkid.net/buy-amoxicillin/ - Amoxicillin Online Amoxicillin oow.gevl.qzone.work.fov.ds http://mewkid.net/buy-amoxicillin/

  6. http://mewkid.net/buy-amoxicillin/ - Buy Amoxicillin Online Amoxicillin 500 Mg mbh.xhyf.qzone.work.cie.gj http://mewkid.net/buy-amoxicillin/

  7. cXpvbmUud29yaw## uarihsog-a.anchor.com [URL=http://mewkid.net/generic-cialis/#uarihsog-u]uarihsog-u.anchor.com[/URL] http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t http://mewkid.net/generic-cialis/#uarihsog-t asomerji

  8. http://mewkid.net/buy-amoxicillin/ - 18 Amoxicillin vok.mand.qzone.work.ovi.ol http://mewkid.net/buy-amoxicillin/

  9. http://mewkid.net/buy-amoxicillin/ - Amoxicillin Amoxicillin - Prix.achetercommander.fr oin.nmuo.qzone.work.xnq.hj http://mewkid.net/buy-amoxicillin/

  10. Агрегатор Яндекс такси Самара даёт возможность вам вызвать автов нужное место и в любое время дня и ночи. Сделать вызов машины возможно как на веб-сайте, по мобильнику позвонив диспетчеру, так и с помощью мобильного онлайн-сервиса . Вам надлежит назвать время когда требуется авто, ваш телефонный номер, местоположение.

    Можно заказать Яндекс такси вместе с детским креслом для перевозки детей, в вечернее время после встреч надежнее прибегнуть к такси, чем, например, садиться в машину нетрезвым, в аэропорт или на вокзал удобнее воспользоваться Я. такси и не искать где оставить своё транспортное средство. Оплата выполняется наличным или безналичным переводом. Время приезда Yandex такси составляет от 5 до семи мин ориентировочно.

    Положительные моменты работы в Я. такси: Моментальная регистрация в приложение, Незначительная комиссия, Выплаты мгновенные, Постоянный поток заказов, Оператор круглыми сутками на связи.

    Для выполнения работ в Яндекс такси владельцу автомобиля необходимо оформиться самому и средство передвижения, перечисленное займёт пять минут. Процент агрегатора составит не более тридцати процентов. Вы сможете получить зарплату в любое время. У вас всегда обязательно будут заявки. В случае проблем можно связаться с постоянно функционирующей службой сопровождения. Яндекс такси помогает людям быстро добраться до места назначения. Заказывая наше Yandex такси вы приобретаете люксовый сервис в городе.

    работа в яндекс такси на автомобиле компании - такси работа на машине фирмы

  11. Sorry for making you review this message which is more than likely to be considered by you as spam. Yes, spamming is a bad thing.

    On the other hand, the best method to discover something new, heretofore unknown, is to take your mind off your day-to-day inconveniences and show passion in a subject that you may have taken into consideration as spam prior to. Right? Turquoise band

    We are a team of young guys that have actually determined to begin our very own company and also make some money like numerous other individuals in the world.

    What do we do? We offer our visitors a wide selection of terrific hand-crafted rings. All the rings are made by the best artisans from all over the United States.

    Have you ever before seen or used an eco-friendly opal ring, timber ring, fire opal ring, Damascus ring, silver opal ring, Blue-green ring, blue opal ring, pink ring, meteorite ring, black ring or silver ring? This is only a tiny part of what you can constantly discover in our shop.

    Made in the UNITED STATES, our handmade rings are not just beautiful as well as initial gifts for, claim, a wedding celebration or birthday celebration, however likewise your talisman, a thing that will definitely bring you all the best in life.

    As compensation for your time spent on reading this message, we give you a 5% discount rate on any type of thing you are interested in.

    We are looking forward to conference you in our store!

  12. Our team are actually an special Northeast Yihi distributor. Our company are additionally authorized reps of Poor Drip, Port Vape, Charlie's Chalk Dirt, Beard Vape, SVRF through Saveur Vape, Ripe Vapes, Smok, Segeli, Lost Vape, Kangertech, Triton and many more. Do not find one thing you are actually looking for on our website? Certainly not a issue! Simply let our company understand what you are trying to find and our experts will certainly discover it for you at a reduced cost. Possess a concern regarding a certain item? Our vape professionals will definitely be glad to offer even more particulars concerning anything our company offer. Simply deliver us your inquiry or even contact us. Our staff will certainly rejoice to aid!

    If you are actually a vaper or even making an effort to leave smoke cigarettes, you reside in the correct area. Intend to save some money in process? Rush and join our email subscriber list to receive special nightclub VIP, vape4style savings, promos and free of cost giveaways! Yihi SX Mini MX

    Our objective at vape4style.com is to deliver our clients with the most effective vaping knowledge feasible, helping them vape with style!. Based in NYC as well as in company since 2015, we are actually a personalized vaping supermarket offering all kinds of vape mods, e-liquids, pure nicotine salts, husk systems, storage tanks, rolls, and also various other vaping accessories, like electric batteries and external battery chargers. Our e-juices are actually regularly fresh because our experts certainly not just market our items retail, but likewise distribute to local area New York City shops and also give wholesale options. This enables our company to consistently spin our stock, delivering our consumers and shops along with the best freshest stock achievable.

  13. Cleaner Bronx - house cleaning services in my area

    Our specialists organizations Baychester ready to hold complex spring cleaning of territories.

    Our enterprise does spring cleaning plot in the district, we can put in order private households and cottage districts .

    Our Limited liability Partnership cleaning company Bensonhurst WILLIAM, is engaged spring cleaning 2019 in Remsen Village under the direction of ROSALIE.

    Cleaning in the spring is chance implement a huge mass of work on tidying up urban areas, rooms and also in my apartment.
    Streets, courtyards, gardens, squares and other urban areas not only required clean up after last winter Spring cleaning the premises is opportunity do a huge mass of work on tidying up urban areas, cottage and also in my apartment.
    Streets, courtyards, gardens, squares and urban square need not only clear from the pollution caused by the winter, take out the garbage, and also prepare the territory for the summer. For this purpose should be restored damaged sidewalks and curbs, fix broken architectural small forms sculptures, flowerpots,artificial reservoirs,benches, fences, and so on, refresh fences, painting and many other things.
    Our Partnership production company carries out spring cleaning 2018 in areas , we can put in order your personal parcel square, apartment, tanhaus.
    Specialists companies West Village do spring garden cleaning.

  14. Our goal at vape4style.com is actually to deliver our customers along with the best vaping expertise feasible, helping them vape with style!. Located in New York City and also in service since 2015, our company are actually a personalized vaping superstore offering all forms of vape mods, e-liquids, smoking salts, husk devices, tanks, rolls, as well as other vaping add-ons, like batteries and also external chargers. Our e-juices are constantly fresh due to the fact that our experts not merely market our products retail, yet additionally distribute to nearby New York City stores along with deliver retail alternatives. This enables our team to constantly rotate our sell, providing our customers as well as establishments along with one of the most best inventory possible.

    If you are a vaper or making an effort to get off smoke cigarettes, you are in the right location. Wish to spare some funds in process? Hurry and join our e-mail subscriber list to get special club VIP, vape4style rebates, promotions and totally free giveaways!

    We are actually an special Northeast Yihi supplier. Our company are actually additionally accredited reps of Bad Drip, Harbour Vape, Charlie's Chalk Dirt, Beard Vape, SVRF by Saveur Vape, Ripe Vapes, Smok, Segeli, Dropped Vape, Kangertech, Triton and much more. Don't observe one thing you are searching for on our website? Not a problem! Only let our team know what you are trying to find as well as we are going to locate it for you at a affordable rate. Have a question regarding a specific item? Our vape professionals are going to rejoice to supply additional information regarding everything our experts offer. Only send our team your question or call our company. Our group is going to rejoice to assist!

    uncle junks honey do outlet - Yihi SX Mini MX

  15. Моё почтение! команда по поисковой оптимизации для продвижения и раскрутки веб-сайтов в поисковых системах и также социальных интернет-сетях. И меня зовут Антон, я создатель группы разработчиков, рерайтеров/копирайтеров, профессионалов, линкбилдеров, оптимизаторов, копирайтеров, маркетологов, специалистов, link builders. Мы - команда опытных фрилансеров. Ваш личный интернет-сайт выйдет с нашей командой на сверхновую высоту. Для вас мы предлагаем высококачественную раскрутку интернет-ресурсов в поисковых системах! Все наши сотрудники прошли гигантский профессиональный путь, мы в точности знаем, как грамотно организовывать ваш личный онлайн-проект, продвинуть его на 1 место, трансформировать web-трафик в заказы. У нашей конторы имеется для Лично для вас абсолютно бесплатное предложение по раскрутке всех ваших интернет-ресурсов. Мы ждем Вас.

    сео анализ сайта онлайн бесплатно курсы сео бесплатно

  16. Приветствую Вас! Мы -студия разработки и создания online-проектов. Меня зовут Антон, я учредитель большой группы рерайтеров/копирайтеров, специалистов, оптимизаторов, разработчиков, маркетологов, линкбилдеров, link builders, профессионалов, копирайтеров. Мы — команда амбициозных профи с 8-летним опытом работы в сфере фриланса. Ваш бизнес выйдет с нашей командой на новую высоту. Мы предлагаем качественную раскрутку интернет-сайтов в поисковиках! Специалисты что работают в команде прошли большой высокопрофессиональный путь, мы точно знаем, каким образом грамотно организовывать ваш личный интернет-сервис, продвигать его на 1 место, преобразовать web-трафик в заказы. Наша Для вашей фирмы мы предлагаем бесплатное предложение по раскрутке ваших сайтов. Мы ждем Вас!

    продвижение сайтов онлайн бесплатно бесплатное сео