php封装curl 调用接口的client类 阿里身份证认证接口 根据指定分隔符 分隔 字符串

https://market.aliyun.com/products/56928004/cmapi014760.html?spm=5176.2020520132.101.4.60c57218dntqVM#sku=yuncode876000009

* RequestClient.php

<?php
/**
 * Created by PhpStorm.
 * User: Mch
 * Date: 2019-09-21
 * Time: 21:54
 */

namespace index\Common;

class RequestClient
{
    /** @var string */
    protected $url;

    /** @var array assoc */
    protected $requestHeaders = [];

    /** @var string */
    protected $requestBody = "";

    /** @var int */
    protected $statusCode = 0;

    /** @var string */
    protected $statusMsg = "";

    /** @var array assoc */
    protected $responseHeaders = [];

    /** @var string */
    protected $responseBody = "";

    /** @var string */
    protected $protocol;

    /** @var int curl errno */
    protected $chErrno = 0;

    /** @var string curl error string */
    protected $chError = "";

    public function __construct() {
        $this->ch = curl_init();
    }

    /**
     * $.param
     * @param $map array assoc
     * @return string
     */
    public static function params($map) {
        $a = [];
        array_walk($map, function($value, $name) use (&$a) {
            array_push($a, sprintf("%s=%s", $name, urlencode($value)));
        });
        return implode('&', $a);
    }

    public function setUrl($url) {
        $this->url = $url;
    }

    /**
     * 设置http请求头 可以调用多次
     */
    public function setRequestHeader($name, $value) {
        $this->requestHeaders[ $name ] = $value;
    }

    /**
     * 设置http请求body 只能调用一次
     * @param $body
     */
    public function setRequestBody($body) {
        $this->requestBody = $body;
    }

    /**
     * GET请求RequestBody为空
     */
    public function get() {
        $this->requestBody = "";
        $this->exec(0);
    }

    /**
     * @param $body
     */
    public function post($body = '') {
// 参数非空的情况下 覆盖原来的requestBody
        if (!empty($body)) {
            $this->requestBody = $body;
        }
        $this->exec(1);
    }

    private function exec($isPost) {
        curl_setopt($this->ch, CURLOPT_URL, $this->url);

        // http request header
        $headers = [];
        foreach ($this->requestHeaders as $name => $value) {
            array_push($headers, $name.': '.$value);
        }
        // http request body
        if (empty($this->requestBody)) {
            // GET or: Empty request body POST
            curl_setopt($this->ch, CURLOPT_POST, $isPost);
        } else {
            // POST with request body
            curl_setopt($this->ch, CURLOPT_POST, 1);
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->requestBody);
            curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
            // Content-Length: xx
            if (!isset($this->requestHeaders['Content-Length'])) {
                array_push($headers,
                           sprintf("Content-Length: %d", strlen($this->requestBody)));
            }
        }
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);

        // 不验证https
        $matches = [];
        preg_match('/^https:\/\/.*$/', $this->url, $matches);
        if (! empty($matches) ) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_HEADER, 1);

        $data = curl_exec($this->ch);
        // curl on error
        $errno = curl_errno($this->ch);
        if ($errno) {
            $this->chErrno = $errno;
            $this->chError = curl_error($this->ch);
            return;
        }
        $lines = $this->handleHeaders($data);

        // http/2 100 continue\r\n\r\n
        // http/1.1 200 OK\r\n
        // ... 第1次处理的body部分作为第2次的head + body
        if ($this->statusCode === 100) {
            $data = self::extractHttpBody($data);
            $lines = $this->handleHeaders($data);
        }
        // set http response header assoc
        for ($i = 1; $i < count($lines); $i++) {
            $b = explode(": ", $lines[$i]);
            $this->responseHeaders[ $b[0] ] = $b[1];
        }

        // set http response body
        $this->responseBody = self::extractHttpBody($data);
    }

    /**
     * @param $data string response header + body
     * @return array headers
     */
    private function handleHeaders($data) {
        // curl success
        $respHeader = self::extractHttpHeader($data);
        // extract http response header and split lines
        $lines = explode("\r\n", $respHeader);
        // get status code "HTTP/1.1 200 OK"
        $a = explode(' ', $lines[0]);
        $this->protocol = $a[0];
        $this->statusCode = intval($a[1]);
        $this->statusMsg = isset($a[2]) ? $a[2]: ''; // http/2
        return $lines;
    }

    public function getStatusCode() {
        return $this->statusCode;
    }


    /**
     * 取得curl响应的http body内容
     * @return string
     */
    public function getResponseBody() {
        return $this->responseBody;
    }

    public function getResponseHeaderByName($name) {
        if (!isset($this->responseHeaders[$name])) {
            return "";
        }
        return $this->responseHeaders[$name];
    }

    public function getResponseHeadersAsString() {
        $a = [
            implode(' ', [$this->protocol, $this->statusCode, $this->statusMsg])
        ];
        foreach ($this->responseHeaders as $name => $value) {
            array_push($a, $name.': '.$value);
        }
        return implode("\r\n", $a)."\r\n";
    }

    private static function findIndexFollowDelim($s, $delim, $startAt=0) {
        $n = strlen($delim);
        $j = 0;
        for ($i = $startAt; isset($s[$i]) && $j < $n; $i++) {
            if ($delim[$j] === $s[$i]) {
                $j += 1;
            } else {
                $j = 0;
            }
        }
        if (!isset($s[$i]) && $j < $n) {
            return -1;
        }
        return $i;
    }

    protected static function extractHttpBody($s, $delim = "\r\n\r\n") {
        return substr($s, self::findIndexFollowDelim($s, $delim));
    }

    protected static function extractHttpHeader($s, $delim = "\r\n\r\n") {
        $i = self::findIndexFollowDelim($s, $delim);
        if ($i < 0) {
            return $s;
        }
        $len = strlen($delim);
        return substr($s, 0, $i-$len);
    }

    public function __destruct() {
        curl_close($this->ch);
    }
}

 

* Usage:

use index\Common\RequestClient;

     if (!class_exists("RequestClient")) {
                include dirname(dirname(__FILE__)).'/Common/RequestClient.php';
            }
            // @ref: https://market.aliyun.com/products/56928004/cmapi014760.html?spm=5176.2020520132.101.4.60c57218dntqVM#sku=yuncode876000009
            $ADDR = "http://idcard.market.alicloudapi.com/lianzhuo/idcard";
            $APP_CODE = "你的appcode";
            $client = new RequestClient();
            $param = [
                'cardno' => $idcard,  // 身份证号码
                'name'   => $name  // 姓名
            ];
            $url = $ADDR."?".RequestClient::params($param);
            Log::write($url, LOG_INFO);
            // echo $url; die;
            $client->setUrl($url);
            $client->setRequestHeader("Authorization", "APPCODE ".$APP_CODE);
            $client->get();
            $statusCode = $client->getStatusCode();
            if ($statusCode !== 200) {
                // 调用接口出错了 打印出http响应头和响应体
                $curlResp = $client->getResponseHeadersAsString()."\r\n".$client->getResponseBody();
                // echo $curlResp; die;
                Log::write($curlResp, LOG_ERR);
                msg("调用接口http返回出错:".$statusCode.' '.
                    $client->getResponseHeaderByName("X-Ca-Error-Message") );
            }
            // true: array
            $resp = json_decode($client->getResponseBody(), true);

            $code = $resp['resp']['code'];
            if ($code === 5) {
                msg('姓名和身份证号码不匹配!');
            } else if ($code === 14) {
                msg('无此身份证号码!');
            } else if ($code == 96) {
                msg('网络繁忙,请稍后重试!');
            } else if ($code !== 0) {
                msg("查身份证未知错误");
            }

            $data = array('name' => $name, 'idcard' => $idcard, 'auth' => 1);
            if (editData('user', $data, 'id = \'' . $uid . '\'')) {
                msg('认证成功!');
            } else {
                msg('认证失败!');
            }

测试post:

** 对于常规的form表单提交

仿照jQuery的 $.params方法的设计

body 可以用 \index\Common\RequestClient::params方法生成字符串name1=value1&name2=value2&...

这样的话,http request header需要设置Content-Type: application/x-www-form-urlencoded; charset=utf-8

** 对于json提交

body 需要用stdClass或者array类型 json_encode成字符串 {"name1":"value1, "name2": ["e1", "e2", "e3], ...}

http request header需要设置Content-Type: application/json; charset=utf-8

--

如果设计ClientClient的post方法, request body通过 关联数组传入,仅支持常规的form表单提交 

<?php

include dirname(__FILE__)."/CurlClient.php";

$client = new \index\Common\RequestClient();
$client->setUrl("https://passport.aliyun.com/newlogin/account/check.do?appName=aliyun&fromSite=-2");

$body = <<<EOF
loginId=1335250574%40qq.com&ua=120%23bX1bSVub5%2F151eoj6L8cfVharPVUbAEZiT12GyVrpQxXvZTkRFHd99vqkoOjrPv4XLtNapThL3UHwLM13zW8LLtlEWo5v6%2FEmNIy%2FOGnAfGDZuxmBj8ZYDl%2F7E8KMoPugXfmYv9%2FHOdxdDOEq%2BIkYoKhsuYSYbkIPXIbbUhpNee%2FP8Lw6HMXSR27a0DVSxtkOyzbRn454T9YtKhOdGFNpJDTX8OtJ1Z4IZjGm3osq2aa3zXTR957vCMqnmE5CcWG7r9yUZwajrgr6LXzrmP8npmB0aZ5UvpAU8NMGLe0Ha1PxFHBLzMdB9hKEs0RcHIlJBVYU9IZsmdBFhDY6yFutgGgpYeftt1Bk0ka5Ivwb%2FdgszaXYZt%2F9q4JXYeusHsTPbhBCAAfUSMFzp%2FlzkM3hYY8j%2FIIMlLo1ih3a132x1X9DI3kh9gqLKeVVvnt80qhku%2B9ArcN63J76zNLGDjKVzaqtOnM4kPcUXsx1OS0U4w6J%2BxOs1nSDAnv8Z405pzcVqFGzdf34jH5Xa0XSNLQKspbb9x4mjKf%2FcaLuTt%2FXovVSzr7XWo8qW8BZYlO%2FkEcI67JWe3h2dA1OxlBZNCpWVsP%2FZPT47mPXQYtR5MR6ilMuB4i5SRx5gGj5EKnYqibTbzfcuFcVkYZpHPsd0hnXKhlpYR5g2EfZTguLIYp%2B9eXahC0J0b12XQRodSl1XuRdiPo0MrZctflybVHQsSDxC8aZhXREw%2FYCEOIMyp0nsspBCpBXqu8Lf%2BQw4cH4M0xg8Nqe4bS0u7VuwBK2ojUxEQjk3975n6FPgoQJoBxNBdQ5b21NaE4FrXFr1z8E%2FS72zUVdkI8piidproh1SjZCgB9ce4exjgEAn%2Bc6cGF9mzZFUIL9VfPy5A0%2Fz6NSSZNbIWdxvjme%2FbKaEe2KhrLHbwZSS8uP6BEzE99mPUcaHga0miJ2TYazrpYSzEzf2I2zedixhnjSJIFus4FeHyR9A7BpAfObXWXPCKt43wJ33ypXHOxg9Fwrcocj6PAt5MziEKVDF52b7rz%2F25JMa0FKSJzk4eFNqHDMSa5cfg8ACr9%2BJrLoTG0lw64usHeWjM94NBRIn11lq2xly%2FL9sxF%2FK3bVd8dJxqOHqCRhbtNTPnTHz9mkNfm4%2BJDOfhvgYrb5dmmTrfIm4NeeuKJz6xiNPyWMLyjxTtFmdD4CHS4ReCcnQvx8kASXldPBhha4Np%3D&umidGetStatusVal=255&screenPixel=375x812&navlanguage=en&navUserAgent=Mozilla%2F5.0%20%28iPhone%3B%20CPU%20iPhone%20OS%2011_0%20like%20Mac%20OS%20X%29%20AppleWebKit%2F604.1.38%20%28KHTML%2C%20like%20Gecko%29%20Version%2F11.0%20Mobile%2F15A372%20Safari%2F604.1&navPlatform=MacIntel&appEntrance=aliyun&appName=aliyun&bizParams=&csrf_token=SNZ0aXoePdfP9OLh5oAE85&fromSite=-2&hsiz=1fdcb8d00907015458ff4778a302ab56&isMobile=true&lang=zh_CN&mobile=true&returnUrl=http%3A%2F%2Faccount.aliyun.com%2Flogin%2Flogin_aliyun.htm%3Foauth_callback%3Dhttps%253A%252F%252Fmarket.console.aliyun.com%252Fimageconsole%252Findex.htm&umidToken=2f38273aed58e8be8a8fa351d655fe1ba5ae6c05
EOF;

// $client->setRequestBody($body);
// $client->post();
$client->post($body);

$header = $client->getResponseHeadersAsString();
var_dump($header);
$resp = $client->getResponseBody();
var_dump($resp);

 

银行卡认证接口: https://market.aliyun.com/products/57000002/cmapi012976.html?spm=5176.730006-56956004-57000002-cmapi012976.content.8.2e953c6419oEwt&accounttraceid=1d091e9b-0ae7-40f2-bb8c-d7c9d2e38575#sku=yuncode697600007

相关文章:

常用的正则表达式 regexp 表单验证, 测试表单自动填充 身份证号校验

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要用PHP调用聚合证件识别API接口,可以使用PHPCURL库。在调用API接口时,需要注意TLS版本的问题。 可以通过以下方式设置CURL的TLS版本: ```php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); $output = curl_exec($ch); curl_close($ch); ``` 在上面的代码中,通过设置CURLOPT_SSLVERSION选项来指定TLS版本。这里设置为CURL_SSLVERSION_TLSv1_2,表示使用TLS 1.2版本。 另外,为了避免SSL证书验证失败的问题,还需要设置CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST两个选项为false。 在调用API接口时,需要将请求参数以POST方式发送到API接口,可以使用curl_setopt函数来设置POST参数: ```php $post_data = array( 'key1' => 'value1', 'key2' => 'value2', ); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); ``` 在上面的代码中,首先定义了一个$post_data数组,包含了API接口所需的请求参数。然后,通过curl_setopt函数设置CURLOPT_POST选项为1,表示这是一个POST请求,接着设置CURLOPT_POSTFIELDS选项为http_build_query($post_data),将请求参数以URL编码的形式发送到API接口。 最后,执行curl_exec函数发送请求,并通过curl_close函数关闭CURL句柄。 希望这些信息对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值