*
  • -41001: encodingAesKey 非法
  • *
  • -41003: aes 解密失败
  • *
  • -41004: 解密后得到的buffer非法
  • *
  • -41005: base64加密失败
  • *
  • -41016: base64解密失败
  • * */ class Weixin_ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; } /** * 检验数据的真实性,并且获取解密后的明文. * @param $encryptedData string 加密的用户数据 * @param $iv string 与用户数据一同返回的初始向量 * @param $data string 解密后的原文 * @return int 成功0,失败返回对应的错误码 */ function weixin_decryptData($appid, $sessionKey, $encryptedData, $iv){ eeglobal_log_handler('weixin_decryptData','info',"start appid=$appid sessionKey=$sessionKey encryptedData=$encryptedData iv=$iv "); if (empty($sessionKey) || strlen($sessionKey) != 24) { throw new GeneralException('无效的会话Key IllegalAesKey','无效的会话Key IllegalAesKey'); } $aesKey = base64_decode($sessionKey); if (strlen($iv) != 24) { throw new GeneralException('无效的iv IllegalIv','无效的iv IllegalIv'); } $aesIV = base64_decode($iv); if (empty($encryptedData)) { throw new GeneralException('无效的encryptedData','无效的encryptedData'); } $aesCipher = base64_decode($encryptedData); $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV); eeglobal_log_handler('weixin_decryptData','info',"finish $result"); // $result=mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$aesKey,$aesCipher,MCRYPT_MODE_CBC,$aesIV); // $loc = strpos($result,"}}"); // $result=substr($result, 0, $loc+2); $dataObj = @json_decode($result,true); if (empty($dataObj)) { throw new GeneralException('解密失败 IllegalBuffer','解密失败 IllegalBuffer'); } if ($dataObj["watermark"]["appid"] != $appid) { throw new GeneralException('解密失败 appid不一致','解密失败 appid不一致'); } return $dataObj; } function weixin_sign_xml($paySignKey,$package){ ksort($package, SORT_STRING); $string1 = ''; foreach($package as $key => $v) { if(empty($v)){ throw new Exception("微信提交的数据项的值不能为空!!:".@json_encode($package)); } $string1 .= "{$key}={$v}&"; } if(empty($paySignKey)) throw new Exception("与微信通信过程中的数据项的签名值不能为空!!"); $string1 .= "key=".$paySignKey; $package['sign'] = strtoupper(md5($string1)); $xml = ""; foreach ($package as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val.""; }else $xml.="<".$key.">"; } $xml.=""; return $xml; } function weixin_getOAuth2AccessToken($appid,$appSecret,$code){ session_start(); $reqres=$_SESSION["OAuth2AccessToken_{$appid}_{$code}"]; if(empty($reqres)){ $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appSecret&code=$code&grant_type=authorization_code"; $reqres = http_get($url); } $jsonres = @json_decode($reqres, true); if(empty($jsonres['openid'])){ eeglobal_log_handler('weixin_handle','debug'," 获取oauth2 AccessToken时发生异常 url=$url postdata=$reqres"); throw new GeneralException('',"获取oauth2 AccessToken时发生异常,没有返回openid"); } $_SESSION["OAuth2AccessToken_{$appid}_{$code}"]=$reqres; return $jsonres; } function weixin_getOAuth2Userinfo($access_token,$appid){ $url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$appid&lang=zh_CN"; $reqres = http_get($url); $jsonres = @json_decode($reqres, true); if(empty($jsonres['openid'])){ eeglobal_log_handler('weixin_handle','debug'," 获取oauth2 Userinfo时发生异常 url=$url postdata=$reqres"); throw new GeneralException('',"获取oauth2 Userinfo时发生异常,没有返回openid"); } return $jsonres; } function weixin_oauthCallBack($logCatalog,$bizPreHandle,$userInfoHandle){ try{ $GPC=input_param_handle(false);//提取参数 $ajaxdata = input_getPostObj(); $cb302=isset($ajaxdata["cb302"])?$ajaxdata["cb302"]:$GPC["cb302"]; if(empty($cb302)) throw new GeneralException("","没有传递必要的参数cb302"); $appid=isset($ajaxdata["appid"])?$ajaxdata["appid"]:$GPC["appid"]; if(empty($appid)) throw new GeneralException("","没有传递必要的参数appid"); $code=isset($ajaxdata["code"])?$ajaxdata["code"]:$GPC["code"]; if(empty($code)) throw new GeneralException("","没有传递必要的参数code"); $state=isset($ajaxdata["state"])?$ajaxdata["state"]:$GPC["state"]; $bizData=$bizPreHandle($appid,$state); $needUnionid=$bizData["needUnionid"]; $needUserInfo=$bizData["needUserInfo"]; $appSecret=$bizData["appSecret"]; $jsonres=weixin_getOAuth2AccessToken($appid,$appSecret,$code); $openid=$jsonres["openid"]; $cb302.=(mb_strpos($cb302,"?")===false?"?":"&")."openid=".urlencode($openid); $unionid=$jsonres["unionid"]; if((empty($unionid) && !empty($needUnionid) && $needUnionid==true) ||(!empty($needUserInfo) && $needUserInfo==true)){ $jsonres=weixin_getOAuth2Userinfo($jsonres["access_token"],$appid); $userInfoHandle($appid,$state,$jsonres); $unionid=$jsonres["unionid"]; if(empty($unionid) && !empty($needUnionid) && $needUnionid==true) throw new GeneralException('',"获取oauth2 Userinfo时发生异常,没有返回unionid"); } $cb302.=(mb_strpos($cb302,"?")===false?"?":"&")."unionid=".urlencode($unionid); ob_clean(); header("Location:$cb302"); exit; }catch(Throwable $e){ $friendMsg=get_class($e)=='GeneralException'?$e->friendmsg:"非常抱歉,获取微信登录信息时发生错误"; if(empty($cb302)) throw new GeneralException("获取微信登录信息时发生错误",$friendMsg.$e->getMessage(),$logCatalog,0,$e); ob_clean(); header("Location:$cb302".(mb_strpos($cb302,"?")===false?"?":"&")."errmsg=".urlencode($friendMsg)); exit; } } function weixin_getAccessToken($appid,$appSecret){ $WXbyAPPID = basecfg_getConfig("WXbyAPPID",$appid); if(!empty($WXbyAPPID['access_token']) && !empty($WXbyAPPID['expires_in']) && !empty($WXbyAPPID['fetchtime']) && (time()-intval($WXbyAPPID['fetchtime']))<3600 ){ eeglobal_log_handler('weixin_handle','debug'," 从缓存提取token appid=$appid "); return $WXbyAPPID['access_token']; }else{ $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret"; $reqres = http_get($url); $jsonres = @json_decode($reqres, true); if(empty($jsonres['access_token'])){ eeglobal_log_handler('weixin_handle','debug'," 获取base AccessToken时发生异常 url=$url postdata=$reqres"); throw new GeneralException('',"获取base AccessToken时发生异常"); } $jsonres['fetchtime'] = time(); basecfg_setConfig("WXbyAPPID", $appid, $jsonres); eeglobal_log_handler('weixin_handle','debug'," 刷新获取新token appid=$appid "); return $jsonres['access_token']; } } function weixin_getMinaQCode($appid,$appSecret,$savePath,$bizCatalog,$bizId,$userId,$minaPagePath="", $width=280,$auto_color=false,$line_color=null,$is_hyaline=false){ $access_token=weixin_getAccessToken($appid,$appSecret); $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token"; $len=mb_strlen($bizCatalog)+mb_strlen($bizId)+mb_strlen($userId); if (($len + 2) > 32) throw new GeneralException('', "生成小程序码时,scene信息超出32位"); $width=intval($width); if($width<280) $width=280; if($width>1280) $width=1280; $postdata=array( 'scene'=>"$bizCatalog:$bizId:$userId", 'page'=>$minaPagePath, 'width'=>$width, 'auto_color'=>$auto_color, 'line_color'=>empty($line_color)?array("r"=>0,"g"=>0,"b"=>0):$line_color, 'is_hyaline'=>$is_hyaline, ); $postdata = json_encode($postdata); eeglobal_log_handler('weixin_handle','debug'," 生成小程序码 appid=$appid postdata=$postdata"); $httpHeader = array(); $data = http_post($url, $httpHeader, $postdata); if(strpos($data,'errcode')!=false||strpos($data,'404')!=false){ eeglobal_log_handler('weixin_handle','error','获取生成小程序码失败,错误信息:'.$data."--".$postdata); throw new GeneralException('', "获取生成小程序码失败 $data"); } $savePathDIR=dirname($savePath); if(!is_dir($savePathDIR)){ if(!mkdir($savePathDIR,0777,true)){ throw new Exception("创建相关目录时发生错误!"); } chmod($savePathDIR,0777); } if (file_put_contents($savePath, $data) == false) { eeglobal_log_handler('weixin_handle','error','保存小程序码失败 savePath=>'.$savePath); throw new GeneralException('', "保存小程序码失败"); } return $data; } function weixin_buildPayInstV2($mchid,$apiKeyV2){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; //获取微信api证书 $api_cert_pem_path = WEB_PHY_ROOT."/ssl/wxpaycert_".$mchid.".abc"; $api_cert_key_path = WEB_PHY_ROOT."/ssl/wxpaycert_".$mchid.".xyz"; if(!file_exists($api_cert_pem_path)){ throw new GeneralException('微信打款必须在微信支付中配置API证书,请先配置API证书:)','微信打款必须在微信支付中配置API证书,请先配置API证书:)'); } if(!file_exists($api_cert_key_path)){ throw new GeneralException('微信打款必须在微信支付中配置API证书,请先配置API证书:)','微信打款必须在微信支付中配置API证书,请先配置API证书:)'); } $instance = WeChatPay\Builder::factory([ 'mchid' => $mchid, 'serial' => 'nop', 'privateKey' => 'any', 'certs' => ['any' => null], 'secret' => $apiKeyV2,//apiv2密钥 'merchant' => [ 'cert' => $api_cert_pem_path, 'key' => $api_cert_key_path, ], ]); return $instance; } function weixin_buildPayInstV3($mchid,$apiKeyV3){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $merchantCertificateFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.abc"; $merchantCertificateSerial = WeChatPay\Util\PemUtil::parseCertificateSerialNo($merchantCertificateFilePath); $merchantPrivateKeyFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.xyz"; $merchantPrivateKeyInstance = WeChatPay\Crypto\Rsa::from($merchantPrivateKeyFilePath, WeChatPay\Crypto\Rsa::KEY_TYPE_PRIVATE); $platformCertificateFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.wxp"; $platformPublicKeyInstance = WeChatPay\Crypto\Rsa::from($platformCertificateFilePath, WeChatPay\Crypto\Rsa::KEY_TYPE_PUBLIC); $platformCertificateSerial = WeChatPay\Util\PemUtil::parseCertificateSerialNo($platformCertificateFilePath); $instance = WeChatPay\Builder::factory([ 'mchid' => $mchid, 'serial' => $merchantCertificateSerial, 'privateKey' => $merchantPrivateKeyInstance, 'certs' => [ $platformCertificateSerial => $platformPublicKeyInstance, ], ]); return $instance; } function weixin_transfers($appid,$openid,$trade_no,$realname,$total_fee,$desc=''){ $mchId=WeiXinPay_mchId; if(empty($mchId)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $paySignKey=WeiXinPay_apiKey; if(empty($paySignKey)) throw new GeneralException('还没有配置微信商户apikey','还没有配置微信商户apikey'); $package = array(); $package['mch_appid'] = $appid; $package['mchid'] = $mchId; $package['nonce_str'] = random(8); $package['partner_trade_no'] = $trade_no; $package['openid'] = $openid; $package['check_name'] = empty($realname)?"NO_CHECK":'FORCE_CHECK'; $package['re_user_name'] = empty($realname)?"":trim($realname); $package['amount'] = intval($total_fee); $package['desc'] = $desc; $package['spbill_create_ip'] = '127.0.0.1'; ksort($package, SORT_STRING); $string1 = ''; foreach($package as $key => $v) { $string1 .= "{$key}={$v}&"; } $string1 .= "key=".$paySignKey; $package['sign'] = strtoupper(md5($string1)); $xml = ""; foreach ($package as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val.""; }else $xml.="<".$key.">"; } $xml.=""; $api_cert_pem_path = WEB_PHY_ROOT."/ssl/wxpaycert_".$mchId.".abc"; $api_cert_key_path = WEB_PHY_ROOT."/ssl/wxpaycert_".$mchId.".xyz"; if(!file_exists($api_cert_pem_path)){ throw new GeneralException('微信打款必须在微信支付中配置API证书,请先配置API证书:)','微信打款必须在微信支付中配置API证书,请先配置API证书:)'); } if(!file_exists($api_cert_key_path)){ throw new GeneralException('微信打款必须在微信支付中配置API证书,请先配置API证书:)','微信打款必须在微信支付中配置API证书,请先配置API证书:)'); } $httpHeader = array(); $result =http_post("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",$httpHeader,$xml,true,$api_cert_pem_path,$api_cert_key_path); // 向微信发起企业付款请求 eeglobal_log_handler('weixin_transfers','info','微信提现 xml=>'.$xml.' result=>'.$result); try{ $data= new SimpleXMLElement($result,LIBXML_NOCDATA); $data = @json_decode(json_encode($data),true); }catch(Throwable $ex){ $data=null; } if($data && !empty($data["payment_no"])){ return $data; }else{ eeglobal_log_handler('weixin_transfers','error','微信企业付款发生错误:微信返回失败信息 xml=>'.$xml.' result=>'.$result); $message=""; if($data && !empty($data["return_code"])) $message.="【".$data["return_code"]."】"; if($data && !empty($data["return_msg"])) $message.=" ".$data["return_msg"].""; if($data && !empty($data["err_code"])) $message.="【".$data["err_code"]."】"; if($data && !empty($data["err_code_des"])) $message.=" ".$data["err_code_des"].""; $message=empty($message)?"向微信发起企业付款请求发生错误":"微信企业付款失败:".$message; throw new GeneralException($message,$message); } } function weixin_transfersV2($appid,$openid,$trade_no,$realname,$total_fee,$desc=''){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $paySignKey=WeiXinPay_apiKey; if(empty($paySignKey)) throw new GeneralException('还没有配置微信商户apikey','还没有配置微信商户apikey'); $instance = weixin_buildPayInstV2($mchid,$paySignKey); $reqData=[ 'xml' => [ 'mch_appid' => $appid, 'mchid' => $mchid, 'partner_trade_no' => $trade_no, 'openid' => $openid, 'check_name' => 'FORCE_CHECK', 're_user_name' => $realname, 'amount' => $total_fee, 'desc' => $desc, 'spbill_create_ip' => '192.168.0.1', ], 'security' => true, 'debug' => false ]; $strResult=""; try{ $strResult = (string)$instance->v2->mmpaymkttransfers->promotion->transfers->post($reqData)->getBody(); }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } if ($e instanceof \GuzzleHttp\Promise\RejectionException && $e->getReason() instanceof \GuzzleHttp\Psr7\Response) { $r = $e->getReason(); $rejectReason=$r->getBody(); if(!empty($rejectReason)){//直接设置为结果信息 $strResult=(string)$r->getBody(); }else{ $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } } } try{ $data= new SimpleXMLElement($strResult,LIBXML_NOCDATA); $data = @json_decode(json_encode($data),true); }catch(Throwable $ex){ $data=null; } if($data && !empty($data["payment_no"])){ return $data; }else{ eeglobal_log_handler('weixin_transfers','error','微信企业付款发生错误:微信返回失败信息 reqData=>'.@json_encode($reqData).' result=>'.$strResult); $message=""; if($data && !empty($data["return_code"])) $message.="【".$data["return_code"]."】"; if($data && !empty($data["return_msg"])) $message.=" ".$data["return_msg"].""; if($data && !empty($data["err_code"])) $message.="【".$data["err_code"]."】"; if($data && !empty($data["err_code_des"])) $message.=" ".$data["err_code_des"].""; $message=empty($message)?"向微信发起企业付款请求发生错误":"微信企业付款失败:".$message; throw new GeneralException($message,$message); } } function weixin_prepayV2($payScene,$appid,$out_trade_no,$total,$description,$attach,$openid="",$product_id=""){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $paySignKey=WeiXinPay_apiKey; if(empty($paySignKey)) throw new GeneralException('还没有配置微信商户apikey','还没有配置微信商户apikey'); $instance = weixin_buildPayInstV2($mchid,$paySignKey); $notify_url=WeiXinPay_notifyurlV2; $reqData=[ 'xml' => [ 'appid' => $appid, 'mch_id' => $mchid, 'nonce_str' => random(8), 'body' => $description, 'out_trade_no' => $out_trade_no, 'total_fee' => $total, 'notify_url' => $notify_url, 'attach' => $attach, 'trade_type' => $payScene, 'openid' => $openid, 'product_id' => $product_id, 'time_start' => date("YmdHis",time()), 'time_expire' => date("YmdHis",time()+15*60), 'spbill_create_ip' => $_SERVER['HTTP_X_REAL_IP']?$_SERVER['HTTP_X_REAL_IP']:$_SERVER['REMOTE_ADDR'], ], 'security' => false, 'debug' => false ]; $strResult=""; try{ $strResult = (string)$instance->v2->pay->unifiedorder->post($reqData)->getBody(); }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } if ($e instanceof \GuzzleHttp\Promise\RejectionException && $e->getReason() instanceof \GuzzleHttp\Psr7\Response) { $r = $e->getReason(); $rejectReason=$r->getBody(); if(!empty($rejectReason)){//直接设置为结果信息 $strResult=(string)$r->getBody(); }else{ $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } } } try{ $data= new SimpleXMLElement($strResult,LIBXML_NOCDATA); $data = @json_decode(json_encode($data),true); }catch(Throwable $ex){ $data=null; } if($data && !empty($data["prepay_id"])){ return $data; }else{ eeglobal_log_handler('weixin_prepay','error','生成预支付订单异常:微信返回失败信息 reqData=>'.@json_encode($reqData).' result=>'.$strResult); $message=""; if($data && !empty($data["return_code"])) $message.="【".$data["return_code"]."】"; if($data && !empty($data["return_msg"])) $message.=" ".$data["return_msg"].""; if($data && !empty($data["err_code"])) $message.="【".$data["err_code"]."】"; if($data && !empty($data["err_code_des"])) $message.=" ".$data["err_code_des"].""; $message=empty($message)?"生成预支付订单异常":"生成预支付订单异常:".$message; throw new GeneralException($message,$message); } } function weixin_prepayBuildV2($logCatalog,$bizHandle){ //提取参数 $GPC=input_param_handle(false); $ajaxdata = input_getPostObj(); $bizCatalog=isset($ajaxdata["bizCatalog"])?$ajaxdata["bizCatalog"]:$GPC["bizCatalog"]; if(empty($bizCatalog)) throw new GeneralException("","没有传递必要的参数bizCatalog"); $bizId=isset($ajaxdata["bizId"])?$ajaxdata["bizId"]:$GPC["bizId"]; if(empty($bizId)) throw new GeneralException("","没有传递必要的参数bizId"); $payScene=isset($ajaxdata["payScene"])?$ajaxdata["payScene"]:$GPC["payScene"]; if(empty($payScene)) throw new GeneralException("","没有传递必要的参数payScene"); $bizCatalog=intval($bizCatalog); $bizId=intval($bizId); $bizAttach="$bizCatalog:$bizId"; $payInfo=$bizHandle($bizCatalog,$bizId,$ajaxdata,$GPC); $prepayData = weixin_prepayV2($payScene,$payInfo["appid"],$payInfo["out_trade_no"],$payInfo["total"],$payInfo["description"],$bizAttach,$payInfo["openid"],$payInfo["product_id"]); $prepayid = $prepayData["prepay_id"]; $ajaxData=array(); switch($payScene){ case "JSAPI": $ajaxData['appId'] = $payInfo["appid"]; $ajaxData['timeStamp'] = time(); $ajaxData['nonceStr'] = random(8); $ajaxData['package'] = 'prepay_id='.$prepayid; $ajaxData['signType'] = 'MD5'; ksort($ajaxData, SORT_STRING); $string=""; foreach($ajaxData as $key => $v) { $string .= "{$key}={$v}&"; } $string .= "key=".$payInfo["mch_paykeyV2"]; $ajaxData['paySign'] = strtoupper(md5($string)); break; case "APP": $ajaxData['appId'] = $payInfo["appid"]; $ajaxData['partnerId'] = $payInfo["mchId"]; $ajaxData['prepayId'] = $prepayid; $ajaxData['packageValue'] = 'Sign=WXPay'; $ajaxData['nonceStr'] = random(8); $ajaxData['timeStamp'] = time(); ksort($ajaxData, SORT_STRING); $string=""; foreach($ajaxData as $key => $v) { $string .= "{$key}={$v}&"; } $string .= "key=".$payInfo["mch_paykeyV2"]; $ajaxData['sign'] = strtoupper(md5($string)); break; case "MWEB": $mweb_url = $prepayData["mweb_url"]; if(empty($mweb_url)){ throw new GeneralException("","H5预支付订单没有生成出mweb_url,无法继续"); } $ajaxData['mweb_url']=$mweb_url; $ajaxData['out_trade_no']=$payInfo["out_trade_no"]; break; case "NATIVE": $code_url = $prepayData["code_url"]; if(empty($code_url)){ throw new GeneralException("","NATIVE预支付订单没有生成出code_url,无法继续"); } require_once WEB_PHY_ROOT."/base/lib_qr.php"; $ajaxData['base64QR']=lib_qrbuild("png",$code_url); break; default: throw new GeneralException("","传递的支付场景payScene参数值不正确!"); } return $ajaxData; } function weixin_prepayV3($payScene,$appid,$out_trade_no,$total,$description,$attach,$openid="",$product_id=""){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $apiKeyV3=WeiXinPay_apiKeyV3; if(empty($apiKeyV3)) throw new GeneralException('还没有配置微信商户apiKeyV3','还没有配置微信商户apiKeyV3'); $instance = weixin_buildPayInstV3($mchid,$apiKeyV3); $notify_url=WeiXinPay_notifyurlV3; $reqData=['json' => [ 'mchid' => $mchid, 'out_trade_no' => $out_trade_no, 'appid' => $appid, 'description' => $description, 'notify_url' => $notify_url, "attach" => $attach, 'time_expire' => (date("Y-m-d\TH:i:s+08:00",time()+15*60)),//15分钟超时 'amount' => [ 'total' => intval($total), 'currency' => 'CNY' ], ]]; $strResult=""; try{ switch($payScene){ case "JSAPI": $reqData['json']["payer"]= [ 'openid' => $openid ]; $strResult = (string)$instance->v3->pay->transactions->jsapi ->postAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_prepayV3','info',"then正常返回JSAPI"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_prepayV3','info',"otherwise异常返回JSAPI"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse();//直接设置为结果信息,即跳过验签异常 $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); break; case "NATIVE": $strResult = (string)$instance->v3->pay->transactions->native ->postAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_prepayV3','info',"then正常返回NATIVE"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_prepayV3','info',"otherwise异常返回NATIVE"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse();//直接设置为结果信息,即跳过验签异常 $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); break; case "APP": $strResult = (string)$instance->v3->pay->transactions->app ->postAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_prepayV3','info',"then正常返回APP"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_prepayV3','info',"otherwise异常返回APP"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse();//直接设置为结果信息,即跳过验签异常 $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); break; default: throw new GeneralException("","传递的支付场景payScene参数值不正确!"); } }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); } try{ $data = @json_decode($strResult,true); }catch(Throwable $ex){ $data=null; } if($data && (!empty($data["prepay_id"]) || !empty($data["code_url"]))){ return $data; }else{ eeglobal_log_handler('weixin_prepayV3','error','生成预支付订单异常:reqData=>'.@json_encode($reqData).' result=>'.$strResult); $message=""; if($data && !empty($data["code"])) $message.="【".$data["code"]."】"; if($data && !empty($data["message"])) $message.=" ".$data["message"].""; if($data && !empty($data["detail"])) $message.=" ".@json_encode($data["detail"]).""; $message=empty($message)?"生成预支付订单异常":"生成预支付订单异常:".$message; throw new GeneralException($message,$message); } } function weixin_payRsaSignV3($mchid,$apiKeyV3,$appid,$prepay_id){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $merchantPrivateKeyFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.xyz"; $merchantPrivateKeyInstance = WeChatPay\Crypto\Rsa::from($merchantPrivateKeyFilePath); $params = [ 'appId' => $appid, 'timeStamp' => (string)WeChatPay\Formatter::timestamp(), 'nonceStr' => WeChatPay\Formatter::nonce(), 'package' => 'prepay_id='.$prepay_id, ]; $params += ['paySign' => WeChatPay\Crypto\Rsa::sign( WeChatPay\Formatter::joinedByLineFeed(...array_values($params)), $merchantPrivateKeyInstance ), 'signType' => 'RSA']; return $params; } function weixin_prepayBuildV3($prePayArgs,$bizArgs,$bizHandle){ if(!isset($prePayArgs["payBackBizCatalog"])) throw new GeneralException("","没有传递必要的参数payBackBizCatalog"); $bizCatalog=$prePayArgs["payBackBizCatalog"]; $bizId=$prePayArgs["payBackBizId"]; if (intval($bizId) <= 0) throw new GeneralException("", "没有传递必要的参数payBackBizId"); $payScene=$prePayArgs["payScene"]; if(empty($payScene)) throw new GeneralException("","没有传递必要的参数payScene"); $bizCatalog=intval($bizCatalog); $bizId=intval($bizId); $bizAttach="$bizCatalog:$bizId"; $payInfo=$bizHandle($bizCatalog,$bizId,$bizArgs); $prepayData = weixin_prepayV3($payScene,$payInfo["appid"],$payInfo["out_trade_no"],$payInfo["total"],$payInfo["description"],$bizAttach,$payInfo["openid"],$payInfo["product_id"]); $ajaxData=array(); switch($payScene){ case "JSAPI": $prepayid = $prepayData["prepay_id"]; $signedData=weixin_payRsaSignV3($payInfo["mchId"],$payInfo["mch_paykeyV3"],$payInfo["appid"],$prepayid); $ajaxData['appId'] = $payInfo["appid"]; $ajaxData['timeStamp'] = $signedData["timeStamp"]; $ajaxData['nonceStr'] = $signedData["nonceStr"]; $ajaxData['package'] = 'prepay_id='.$prepayid; $ajaxData['signType'] = 'RSA'; $ajaxData['paySign'] = $signedData["paySign"]; break; case "APP": $prepayid = $prepayData["prepay_id"]; $signedData=weixin_payRsaSignV3($payInfo["mchId"],$payInfo["mch_paykeyV3"],$payInfo["appid"],$prepayid); $ajaxData['appId'] = $payInfo["appid"]; $ajaxData['partnerId'] = $payInfo["mchId"]; $ajaxData['prepayId'] = $prepayid; $ajaxData['packageValue'] = 'Sign=WXPay'; $ajaxData['nonceStr'] = $signedData["nonceStr"]; $ajaxData['timeStamp'] = $signedData["timeStamp"]; $ajaxData['sign'] = $signedData["paySign"]; break; case "NATIVE": $code_url = $prepayData["code_url"]; if(empty($code_url)){ throw new GeneralException("","NATIVE预支付订单没有生成出code_url,无法继续"); } require_once WEB_PHY_ROOT."/base/lib_qr.php"; $ajaxData['base64QR']=lib_qrbuild("png",$code_url); break; default: throw new GeneralException("","传递的支付场景payScene参数值不正确!"); } return $ajaxData; } function weixin_orderqueryV2($appid,$out_trade_no,$transaction_id){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $paySignKey=WeiXinPay_apiKey; if(empty($paySignKey)) throw new GeneralException('还没有配置微信商户apikey','还没有配置微信商户apikey'); $instance = weixin_buildPayInstV2($mchid,$paySignKey); $reqData=[ 'xml' => [ 'appid' => $appid, 'mch_id' => $mchid, 'nonce_str' => random(8), 'out_trade_no' => $out_trade_no, 'transaction_id' => $transaction_id, ], 'security' => false, 'debug' => false ]; $strResult=""; try{ $strResult = (string)$instance->v2->pay->orderquery->post($reqData)->getBody(); }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } if ($e instanceof \GuzzleHttp\Promise\RejectionException && $e->getReason() instanceof \GuzzleHttp\Psr7\Response) { $r = $e->getReason(); $rejectReason=$r->getBody(); if(!empty($rejectReason)){//直接设置为结果信息 $strResult=(string)$r->getBody(); }else{ $strResult.=" innerResponse=>".$r->getStatusCode().' '.$r->getReasonPhrase(); $strResult.=" body=>".$r->getBody(); } } } try{ $data= new SimpleXMLElement($strResult,LIBXML_NOCDATA); $data = @json_decode(json_encode($data),true); }catch(Throwable $ex){ $data=null; } if($data && !empty($data["trade_state"])){ return $data; }else{ eeglobal_log_handler('weixin_orderquery','error','查询支付订单时发生异常:微信返回失败信息 reqData=>'.@json_encode($reqData).' result=>'.$strResult); $message=""; if($data && !empty($data["return_code"])) $message.="【".$data["return_code"]."】"; if($data && !empty($data["return_msg"])) $message.=" ".$data["return_msg"].""; if($data && !empty($data["err_code"])) $message.="【".$data["err_code"]."】"; if($data && !empty($data["err_code_des"])) $message.=" ".$data["err_code_des"].""; $message=empty($message)?"查询支付订单时发生异常":"查询支付订单时发生异常:".$message; throw new GeneralException($message,$message); } } function weixin_orderqueryV3($appid,$out_trade_no,$transaction_id){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $apiKeyV3=WeiXinPay_apiKeyV3; if(empty($apiKeyV3)) throw new GeneralException('还没有配置微信商户apiKeyV3','还没有配置微信商户apiKeyV3'); $instance = weixin_buildPayInstV3($mchid,$apiKeyV3); $strResult=""; try{ if(!empty($transaction_id)){ $reqData=[ 'query' => ['mchid' => $mchid ], 'transaction_id' => $transaction_id, ]; $strResult = (string) $instance->v3->pay->transactions->id->{'{transaction_id}'} ->getAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_orderquery3','info',"then正常返回transaction_id"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_orderquery3','info',"otherwise异常返回transaction_id"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); }else{ $reqData=[ 'query' => ['mchid' => $mchid ], 'out_trade_no' => $out_trade_no, ]; $strResult= (string) $instance->v3->pay->transactions->outTradeNo->{'{out_trade_no}'} ->getAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_orderquery3','info',"then正常返回out_trade_no"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_orderquery3','info',"otherwise异常返回out_trade_no"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); } }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); } try{ $data = @json_decode($strResult,true); }catch(Throwable $ex){ $data=null; } if($data && !empty($data["trade_state"])){ return $data; }else{ eeglobal_log_handler('weixin_orderquery3','error',"查询支付订单时发生异常:reqData=>".@json_encode($reqData)." result=>$strResult"); $message=""; if($data && !empty($data["code"])) $message.="【".$data["code"]."】"; if($data && !empty($data["message"])) $message.=" ".$data["message"].""; if($data && !empty($data["detail"])) $message.=" ".@json_encode($data["detail"]).""; $message=empty($message)?"查询支付订单时发生异常":"查询支付订单时发生异常:".$message; throw new GeneralException($message,$message); } } function weixin_ordercloseV3($out_trade_no){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $mchid=WeiXinPay_mchId; if(empty($mchid)) throw new GeneralException('还没有配置微信商户号','还没有配置微信商户号'); $apiKeyV3=WeiXinPay_apiKeyV3; if(empty($apiKeyV3)) throw new GeneralException('还没有配置微信商户apiKeyV3','还没有配置微信商户apiKeyV3'); $instance = weixin_buildPayInstV3($mchid,$apiKeyV3); $strResult=""; try{ $reqData=[ 'json' => ['mchid' => $mchid], 'out_trade_no' => $out_trade_no, ]; $strResult= (string) $instance->v3->pay->transactions->outTradeNo->{'{out_trade_no}'}->close ->postAsync($reqData) ->then(static function($response) { eeglobal_log_handler('weixin_ordercloseV3','info',"then正常返回out_trade_no"); return (string)$response->getBody(); }) ->otherwise(static function($e) { eeglobal_log_handler('weixin_ordercloseV3','info',"otherwise异常返回out_trade_no"); $owReturn=""; $owReturn.="【".$e->getMessage()."】"; $owReturn.=" trace=>".$e->getTraceAsString(); if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); $owReturn=(string)$r->getBody(); } return $owReturn; }) ->wait(); }catch(Throwable $e){ $strResult.="【".$e->getMessage()."】"; $strResult.=" trace=>".$e->getTraceAsString(); } try{ if ($strResult == "") $strResult = "\"SUCCESS\""; $data = @json_decode($strResult,true); }catch(Throwable $ex){ $data=null; } if($data=="SUCCESS"){ return $data; }else{ eeglobal_log_handler('weixin_ordercloseV3','error',"关闭支付订单时发生异常:reqData=>".@json_encode($reqData)." result=>$strResult"); $message=""; if($data && !empty($data["code"])) $message.="【".$data["code"]."】"; if($data && !empty($data["message"])) $message.=" ".$data["message"].""; if($data && !empty($data["detail"])) $message.=" ".@json_encode($data["detail"]).""; $message=empty($message)?"关闭支付订单时发生异常":"关闭支付订单时发生异常:".$message; throw new GeneralException($message,$message); } } function weixin_payedNotifyV2($logCatalog,$bizHandle){ try{ error_reporting(0); eeglobal_log_handler($logCatalog,"debug","支付后回调-start"); $xml = file_get_contents('php://input'); eeglobal_log_handler($logCatalog,"debug","支付后回调-xml=$xml"); $dom_xml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); $array_result =@json_decode(@json_encode($dom_xml),true); $out_trade_no=$array_result["out_trade_no"]; $transaction_id=$array_result["transaction_id"]; if(empty($out_trade_no) || empty($transaction_id)) throw new Exception("无效回调,out_trade_no或transaction_id为空"); $attach=$array_result["attach"]; $attachInfo=explode(":",$attach); $bizCatalog=0; $bizId=0; if(count($attachInfo)==2){ $bizCatalog=intval($attachInfo[0]); $bizId=intval($attachInfo[1]); } eeglobal_log_handler($logCatalog,"debug","支付后回调 attach=$attach bizCatalog=$bizCatalog bizId=$bizId"); $bizHandle($bizCatalog,$bizId,$array_result); ob_clean(); header("Content-type: text/xml;charset=utf-8"); echo ""; echo ""; echo ""; echo ""; exit; }catch(Throwable $e){ eeglobal_log_handler($logCatalog,"error","支付后回调处理异常:xml=>$xml 异常消息:".$e->getMessage()." trace=>".$e->getTraceAsString()); ob_clean(); echo $logCatalog.""; exit; } } function weixin_payedNotifyV3($logCatalog,$bizHandle){ try{ error_reporting(0); $mchid=WeiXinPay_mchId; $apiv3Key =WeiXinPay_apiKeyV3;// 在商户平台上设置的APIv3密钥 require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; eeglobal_log_handler($logCatalog,"debug","支付后回调-start"); $inBody = file_get_contents('php://input'); eeglobal_log_handler($logCatalog,"debug","支付后回调-inBody=$inBody"); $inBodyArray = input_getPostObj(); // 使用PHP7的数据解构语法,从Array中解构并赋值变量 ['resource' => [ 'ciphertext' => $ciphertext, 'nonce' => $nonce, 'associated_data' => $aad ]] = $inBodyArray; // 加密文本消息解密 $inBodyResource = WeChatPay\Crypto\AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad); eeglobal_log_handler($logCatalog,"debug","支付后回调-inBodyResource=$inBodyResource"); // 把解密后的文本转换为PHP Array数组 $array_result = (array)json_decode($inBodyResource, true); $out_trade_no=$array_result["out_trade_no"]; $transaction_id=$array_result["transaction_id"]; if(empty($out_trade_no) || empty($transaction_id)) throw new Exception("无效回调,out_trade_no或transaction_id为空"); $attach=$array_result["attach"]; $attachInfo=explode(":",$attach); $bizCatalog=0; $bizId=0; if(count($attachInfo)==2){ $bizCatalog=intval($attachInfo[0]); $bizId=intval($attachInfo[1]); } eeglobal_log_handler($logCatalog,"debug","支付后回调 attach=$attach bizCatalog=$bizCatalog bizId=$bizId"); $bizHandle($bizCatalog,$bizId,$array_result); ob_clean(); header("Content-type:application/json;charset=utf-8"); echo `{"code":"SUCCESS","message":"成功"}`; exit; }catch(Throwable $e){ eeglobal_log_handler($logCatalog,"error","支付后回调处理异常:inBody=>$inBody inBodyResource=$inBodyResource 异常消息:".$e->getMessage()." trace=>".$e->getTraceAsString()); ob_clean(); echo $logCatalog.""; exit; } } function weixin_getPlatCertificatesV3($mchid){ require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $merchantCertificateFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.abc"; $merchantCertificateSerial = WeChatPay\Util\PemUtil::parseCertificateSerialNo($merchantCertificateFilePath); $merchantPrivateKeyFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.xyz"; $merchantPrivateKeyInstance = WeChatPay\Crypto\Rsa::from($merchantPrivateKeyFilePath, WeChatPay\Crypto\Rsa::KEY_TYPE_PRIVATE); $platformCertificateFilePath = "file://".WEB_PHY_ROOT."/ssl/wxpaycert_$mchid.wxp"; $platformPublicKeyInstance = WeChatPay\Crypto\Rsa::from($platformCertificateFilePath, WeChatPay\Crypto\Rsa::KEY_TYPE_PUBLIC); $platformCertificateSerial = WeChatPay\Util\PemUtil::parseCertificateSerialNo($platformCertificateFilePath); $url="https://api.mch.weixin.qq.com/v3/certificates"; $http_method="GET"; $timestamp = time();//时间戳 $nonce = $timestamp . rand(10000, 99999);//随机字符串 $url_parts = parse_url($url); $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : "")); $body=""; $message = $http_method . "\n" . $canonical_url . "\n" . $timestamp . "\n" . $nonce . "\n" . $body . "\n"; openssl_sign($message, $raw_sign, $merchantPrivateKeyInstance, 'sha256WithRSAEncryption'); $raw_sign = base64_encode($raw_sign); $sign = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $merchantCertificateSerial, $raw_sign); $header[] = 'User-Agent:https://WS.COM/User_agent'; $header[] = 'Accept:application/json'; $header[] = 'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign; $rawdata = http_get($url, $header); $jsondata = json_decode($rawdata, true); $jsondata = $jsondata["data"]; /* "serial_no": "50062CE505775F070CAB06E697F1BBD1AD4F4D87", "effective_time ": "2018-12-07T10:34:56+08:00", "expire_time ": "2020-12-07T10:34:56+08:00", "encrypt_certificate": { "algorithm": "AEAD_AES_256_GCM", "nonce": "35f9c719727b", "associated_data": "certificate", "ciphertext": "aBvt… " } */ return $jsondata; } /***************** */ use TencentCloud\Common\Credential; use TencentCloud\Common\Profile\ClientProfile; use TencentCloud\Common\Profile\HttpProfile; use TencentCloud\Common\Exception\TencentCloudSDKException; use TencentCloud\Ocr\V20181119\OcrClient; use TencentCloud\Ocr\V20181119\Models\IDCardOCRRequest; use TencentCloud\Ocr\V20181119\Models\BizLicenseOCRRequest; /***************** */ function txcloud_ocr($catalog,$params){ try { require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $cred = new Credential(TXCLOUD_SecretId, TXCLOUD_SecretKey); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("ocr.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $client = new OcrClient($cred, "ap-beijing", $clientProfile); switch($catalog){ case "IDCardOCR": $req = new IDCardOCRRequest(); $params["Config"]=array( "InvalidDateWarn"=>true, "DetectPsWarn"=>true, ); $params = array( "ImageUrl" => empty($params["ImageUrl"])?"":$params["ImageUrl"], "ImageBase64" => empty($params["ImageBase64"])?"":$params["ImageBase64"], "CardSide" => empty($params["CardSide"])?"":$params["CardSide"], "Config" => empty($params["Config"])?array("Quality"=>50,"BorderCheckWarn"=>50,"ReflectWarn"=>true):json_encode($params["Config"]), ); $req->fromJsonString(json_encode($params)); $resp = $client->IDCardOCR($req); txcloud_ocrErr($resp); $validDate=$resp->getValidDate(); //2010.07.21-2020.07.21 if(!empty($validDate)){ $validDate2=explode("-",$validDate)[1]; $validDate2=mb_ereg_replace("\.","-",$validDate2); $validDate2=strtotime($validDate2); if(strtotime(date("Y-m-d",time()))>$validDate2) throw new GeneralException("", "身份证已过期"); } return json_decode($resp->toJsonString(),true); break; case "BizLicenseOCR": $req = new BizLicenseOCRRequest(); $params = array( "ImageUrl" => empty($params["ImageUrl"])?"":$params["ImageUrl"], "ImageBase64" => empty($params["ImageBase64"])?"":$params["ImageBase64"], ); $req->fromJsonString(json_encode($params)); $resp = $client->BizLicenseOCR($req); txcloud_ocrErr($resp); return json_decode($resp->toJsonString(),true); break; default:throw new GeneralException("", " 不支持的catalog!"); } } catch(TencentCloudSDKException $e) { $err=array(); $err["errorCode"]=$e->getErrorCode(); $err["message"]=$e->getMessage(); $friendMsg="【".$err["errorCode"]."】".$err["message"]; $friendMsg="无法识别"; $err["requestId"]=$e->getRequestId(); $err["code"]=$e->getCode(); $err["file"]=$e->getFile(); $err["line"]=$e->getLine(); $err["trace"]=json_encode($e->getTrace()); $fullMsg=json_encode($err); throw new GeneralException("ocr_error",$friendMsg); } } function txcloud_ocrErr($resp){ if(!empty($resp->getRecognizeWarnCode())){ $msgs=$resp->getRecognizeWarnMsg(); $err=""; foreach($resp->getRecognizeWarnCode() as $index=>$code){ //$err.="【".$msgs[$index]." 错误码:{$code}】 "; $err.="【".$msgs[$index]."】 "; } throw new GeneralException("ocr_error",$err); } if(!empty($resp->getAdvancedInfo())){ $advancedInfo=json_decode($resp->getAdvancedInfo(),true); if(!empty($advancedInfo) && is_array($advancedInfo)){ $warnInfos=$advancedInfo["WarnInfos"]; if(!empty($warnInfos) && is_array($warnInfos)){ $err=""; foreach($warnInfos as $code){ switch($code){ case "-9100": $err.="【身份证有效日期不合法告警"; break; case "-9101": $err.="【身份证边框不完整告警"; break; case "-9102": $err.="【身份证复印件告警"; break; case "-9103": $err.="【身份证翻拍告警"; break; case "-9105": $err.="【身份证框内遮挡告警"; break; case "-9104": $err.="【临时身份证告警"; break; case "-9106": $err.="【身份证 PS 告警"; break; case "-9107": $err.="【身份证反光告警"; break; default: $err.="【未知错误"; break; } //$err.=" 错误码:{$code}】 "; $err.="】 "; } throw new GeneralException("ocr_error",$err); } } } } //*******/ use TencentCloud\Faceid\V20180301\FaceidClient; use TencentCloud\Faceid\V20180301\Models\IdCardVerificationRequest; function txcloud_idcardCheck($trueName,$idCard){ try { require_once WEB_PHY_ROOT."/base/composer/vendor/autoload.php"; $cred = new Credential(TXCLOUD_SecretId, TXCLOUD_SecretKey); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("faceid.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $client = new FaceidClient($cred, "ap-beijing", $clientProfile); $req = new IdCardVerificationRequest(); $params = array( "Name" => $trueName, "IdCard" => $idCard, ); $req->fromJsonString(json_encode($params)); $resp = $client->IdCardVerification($req); $Description = $resp->getDescription(); $RequestId = $resp->getRequestId(); $Result = $resp->getResult(); if($Result!="0") throw new GeneralException("idcardCheck_error"," ".$Description); return json_decode($resp->toJsonString(),true); } catch(TencentCloudSDKException $e) { $err=array(); $err["errorCode"]=$e->getErrorCode(); $err["message"]=$e->getMessage(); $friendMsg="【".$err["errorCode"]."】".$err["message"]; $friendMsg="无法识别"; $err["requestId"]=$e->getRequestId(); $err["code"]=$e->getCode(); $err["file"]=$e->getFile(); $err["line"]=$e->getLine(); $err["trace"]=json_encode($e->getTrace()); $fullMsg=json_encode($err); throw new GeneralException("idcardCheck_error",$friendMsg); } }