Skip to content Skip to sidebar Skip to footer

企业信用代码严格校验

private function check_credit_code($credit_code){
        if(!is_string($credit_code)){
            return [
                'state' => false,
                'msg'   => '信用代码必须是字符串'
            ];
        }
        $pattern= '/^[0-9A-Z]+$/';
        if(strlen($credit_code) != 18 || !preg_match($pattern,$credit_code)){
            return [
                'state' => false,
                'msg'   => '信用代码长度不足18位或存在特殊字符'
            ];
        }
        $ancode = '';#统一社会信用代码的每一个值
        $ancodevalue = '';#统一社会信用代码每一个值的权重
        $total = 0;
        $weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];#加权因子
        $str = '0123456789ABCDEFGHJKLMNPQRTUWXY';#不用I、O、S、V、Z
        for($i=0; $i<(strlen($credit_code)-1); $i++){
            $ancode = mb_substr($credit_code,$i,1);
            $ancodevalue = strpos($str,$ancode);
            if($ancodevalue === false){
                $ancodevalue = -1;
            }
            $total = $total + $ancodevalue * $weightedfactors[$i];#//权重与加权因子相乘之和
        }
        $logiccheckcode = 31 - $total % 31;
        if ($logiccheckcode == 31){
            $logiccheckcode = 0;
        }
        $str2 = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
        $str_arr = explode(',',$str2);
        $logiccheckcode = $str_arr[$logiccheckcode];
        $checkcode = mb_substr($credit_code,17,1,'utf-8');
        if ($logiccheckcode != $checkcode){
            return [
                'state' => false,
                'msg'   => '校验失败'
            ];
        }
        return [
            'state' => true,
            'msg'   => '校验通过'
        ];
    }

Leave a comment