Userauth.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Cache;
  6. use TencentCloud\Common\Credential;
  7. use TencentCloud\Common\Profile\ClientProfile;
  8. use TencentCloud\Common\Profile\HttpProfile;
  9. use TencentCloud\Common\Exception\TencentCloudSDKException;
  10. //use TencentCloud\Faceid\V20180301\FaceidClient;
  11. //use TencentCloud\Faceid\V20180301\Models\IdCardVerificationRequest;
  12. use TencentCloud\Iai\V20200303\IaiClient;
  13. use TencentCloud\Iai\V20200303\Models\CompareFaceRequest;
  14. use fast\Random;
  15. /**
  16. * 实名认证,真人认证相关
  17. */
  18. class Userauth extends Api
  19. {
  20. protected $noNeedLogin = [];
  21. protected $noNeedRight = '*';
  22. //实名认证信息
  23. public function idcard_info(){
  24. $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->order('id desc')->find();
  25. $this->success('success',$check);
  26. }
  27. //申请实名认证
  28. public function apply_idcard_confirm(){
  29. $realname = input('realname','');
  30. $idcard = input('idcard' ,'');
  31. if(empty($realname) || empty($idcard)){
  32. $this->error('实名认证信息必填');
  33. }
  34. if($this->auth->idcard_status == 1){
  35. $this->error('您已经完成实名认证');
  36. }
  37. if($this->auth->idcard_status == 0){
  38. $this->error('您已经提交实名认证,请等待审核');
  39. }
  40. Db::startTrans();
  41. $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->lock(true)->find();
  42. if(!empty($check)){
  43. if($check['status'] == 1){
  44. Db::rollback();
  45. $this->error('您已经完成实名认证');
  46. }
  47. if($check['status'] == 0){
  48. Db::rollback();
  49. $this->error('您已经提交实名认证,请等待审核');
  50. }
  51. }
  52. $count = Db::name('user_idconfirm')->where(['idcard' => $idcard, 'user_id' => ['neq', $this->auth->id]])->count('id');
  53. if ($count) {
  54. $this->error('该身份证号已被他人使用');
  55. }
  56. //限制每日请求次数
  57. $time = time();
  58. $today_end = strtotime(date('Y-m-d 23:59:59', $time));
  59. $cache_time = $today_end - $time; //缓存时间
  60. $time_count = Cache::get('userauth' . $this->auth->id);
  61. if (!$time_count) {
  62. Cache::set('userauth' . $this->auth->id, 1, $cache_time);
  63. } else {
  64. Cache::set('userauth' . $this->auth->id, $time_count + 1, $cache_time);
  65. if ($time_count > 5) {
  66. $this->error('今日实名次数已到上限,明天再来吧');
  67. }
  68. }
  69. //阿里云身份证二要素认证
  70. $auth_restult = $this->userauth_aliyun_two($idcard, $realname);
  71. if($auth_restult == false){
  72. $this->error('身份证信息与姓名不符');
  73. }
  74. $data = [
  75. 'user_id' => $this->auth->id,
  76. 'realname' => $realname,
  77. 'idcard' => $idcard,
  78. 'status' => 1, //不需要人工刚审核了,直接过审
  79. 'createtime' => time(),
  80. 'updatetime' => time(),
  81. ];
  82. //更新
  83. $update_rs = Db::name('user')->where('id',$this->auth->id)->update(['idcard_status'=>$data['status']]);
  84. if(!empty($check)){
  85. $rs = Db::name('user_idconfirm')->where('id',$check['id'])->update($data);
  86. }else{
  87. $rs = Db::name('user_idconfirm')->insertGetId($data);
  88. }
  89. if(!$rs || !$update_rs){
  90. Db::rollback();
  91. $this->error('认证失败');
  92. }
  93. Db::commit();
  94. $this->success('认证通过');
  95. }
  96. ///////////////////////////////////////////真人认证,来自知音////////////
  97. //申请真人认证
  98. public function realauth() {
  99. if ($this->auth->real_status == 1) {
  100. $this->error('您已经真人认证过了~');
  101. }
  102. if ($this->auth->avatar == config('avatar_boy') || $this->auth->avatar == config('avatar_girl')) {
  103. $this->error('请先上传真人头像~');
  104. }
  105. $check = Db::name('user_audit')->where('user_id',$this->auth->id)->where('type','avatar')->where('status',0)->find();
  106. if(!empty($check)){
  107. $this->error('您的头像还在审核中,审核完成在认证吧');
  108. }
  109. //获取token
  110. $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.config('tencent_yun')['secret_id'].'&secret='.config('tencent_yun')['secret_key'].'&grant_type=client_credential&version=1.0.0';
  111. $token_result = file_get_contents($token_url);
  112. if (!$token_result) {
  113. $this->error('您的网络开小差啦1~');
  114. }
  115. $token_result = json_decode($token_result, true);
  116. if ($token_result['code'] != 0) {
  117. $this->error('您的网络开小差啦2~');
  118. }
  119. $token = $token_result['access_token'];
  120. //获取签名鉴权参数ticket
  121. $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.config('tencent_yun')['secret_id'].'&access_token='.$token.'&type=SIGN&version=1.0.0';
  122. $ticket_result = file_get_contents($ticket_url);
  123. if (!$ticket_result) {
  124. $this->error('您的网络开小差啦3~');
  125. }
  126. $ticket_result = json_decode($ticket_result, true);
  127. if ($ticket_result['code'] != 0) {
  128. $this->error('您的网络开小差啦4~');
  129. }
  130. $ticket = $ticket_result['tickets'][0]['value'];
  131. //获取签名
  132. $sign_data = [
  133. 'wbappid' => config('tencent_yun')['secret_id'],
  134. 'userId' => (string)$this->auth->id,
  135. 'version' => '1.0.0',
  136. 'ticket' => $ticket,
  137. 'nonce' => Random::alnum(32)
  138. ];//p($sign_data);
  139. asort($sign_data); //p($sign_data);//排序
  140. $sign_string = join('', $sign_data);//p($sign_string);
  141. $sign = sha1($sign_string);//p($sign);
  142. //上传身份信息
  143. $orderNo = createUniqueNo('A',$this->auth->id); //商户请求的唯一标识
  144. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/server/getAdvFaceId?orderNo=' . $orderNo;
  145. $avatar = one_domain_image($this->auth->avatar);
  146. $avatar = str_replace('https', 'http', $avatar);
  147. $img = file_get_contents($avatar);
  148. $img = str_replace('data:image/jpg;base64', '', $img);
  149. $img = str_replace('\n', '', $img);
  150. $sourcePhotoStr = base64_encode($img);
  151. $data = [
  152. 'webankAppId' => config('tencent_yun')['secret_id'],
  153. 'orderNo' => $orderNo,
  154. 'userId' => (string)$this->auth->id,
  155. 'sourcePhotoStr' => $sourcePhotoStr,
  156. 'sourcePhotoType' => 2,
  157. 'version' => '1.0.0',
  158. 'sign' => $sign,
  159. 'nonce' => $sign_data['nonce']
  160. ];
  161. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  162. if (!$rs) {
  163. $this->error('您的网络开小差啦5~');
  164. }
  165. $rs = json_decode($rs, true);
  166. if (!$rs || $rs['code'] != 0) {
  167. $this->error('您的网络开小差啦6~');
  168. }
  169. $user_auth = [
  170. 'user_id' => $this->auth->id,
  171. 'certify_id' => $rs['result']['faceId'],
  172. 'out_trade_no' => $data['orderNo'],
  173. 'status' => 0,
  174. 'createtime' => time(),
  175. 'updatetime' => time()
  176. ];
  177. //开启事务
  178. Db::startTrans();
  179. //查询是否认证过
  180. $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  181. if ($info) {
  182. $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
  183. } else {
  184. $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
  185. }
  186. if (!$auth_rs) {
  187. Db::rollback();
  188. $this->error('您的网络开小差啦7~');
  189. }
  190. //修改用户表认证状态
  191. $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', 0);
  192. if ($user_rs === false) {
  193. Db::rollback();
  194. $this->error('您的网络开小差啦8~');
  195. }
  196. Db::commit();
  197. $return_data = [
  198. 'face_id' => $user_auth['certify_id'],
  199. 'order_no' => $user_auth['out_trade_no'],
  200. 'user_id' => (string)$this->auth->id,
  201. 'nonce' => $sign_data['nonce'],
  202. 'sign' => $sign
  203. ];
  204. $this->success('success', $return_data);
  205. }
  206. //查询真人认证结果
  207. public function getrealauthresult() {
  208. $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  209. if (!$user_auth) {
  210. $this->success('尚未认证');
  211. }
  212. if ($user_auth['status'] == 1) {
  213. $this->success('真人认证通过');
  214. }
  215. if (!$user_auth['certify_id']) {
  216. $this->success('请先进行真人认证');
  217. }
  218. //获取token
  219. $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.config('tencent_yun')['secret_id'].'&secret='.config('tencent_yun')['secret_key'].'&grant_type=client_credential&version=1.0.0';
  220. $token_result = file_get_contents($token_url);
  221. if (!$token_result) {
  222. $this->error('您的网络开小差啦1~');
  223. }
  224. $token_result = json_decode($token_result, true);
  225. if ($token_result['code'] != 0) {
  226. $this->error('您的网络开小差啦2~');
  227. }
  228. $token = $token_result['access_token'];
  229. //获取签名鉴权参数ticket
  230. $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.config('tencent_yun')['secret_id'].'&access_token='.$token.'&type=SIGN&version=1.0.0';
  231. $ticket_result = file_get_contents($ticket_url);
  232. if (!$ticket_result) {
  233. $this->error('您的网络开小差啦3~');
  234. }
  235. $ticket_result = json_decode($ticket_result, true);
  236. if ($ticket_result['code'] != 0) {
  237. $this->error('您的网络开小差啦4~');
  238. }
  239. $ticket = $ticket_result['tickets'][0]['value'];
  240. //获取签名
  241. $sign_data = [
  242. 'wbappid' => config('tencent_yun')['secret_id'],
  243. 'orderNo' => $user_auth['out_trade_no'],
  244. 'version' => '1.0.0',
  245. 'ticket' => $ticket,
  246. 'nonce' => Random::alnum(32)
  247. ];//p($sign_data);
  248. asort($sign_data); //p($sign_data);//排序
  249. $sign_string = join('', $sign_data);//p($sign_string);
  250. $sign = sha1($sign_string);//p($sign);
  251. //人脸核身结果查询
  252. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
  253. $data = [
  254. 'appId' => config('tencent_yun')['secret_id'],
  255. 'version' => '1.0.0',
  256. 'nonce' => $sign_data['nonce'],
  257. 'orderNo' => $user_auth['out_trade_no'],
  258. 'sign' => $sign
  259. ];
  260. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  261. if (!$rs) {
  262. $this->error('您的网络开小差啦5~');
  263. }
  264. $rs = json_decode($rs, true);
  265. if (!$rs || $rs['code'] != 0) {
  266. $this->error($rs['msg']);
  267. }
  268. if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
  269. $edit_data['status'] = 1;
  270. $msg = '真人认证成功';
  271. } else {
  272. $edit_data['status'] = 2;
  273. $edit_data['certify_id'] = '';
  274. $edit_data['out_trade_no'] = '';
  275. $msg = '真人认证失败';
  276. }
  277. $edit_data['updatetime'] = time();
  278. //开启事务
  279. Db::startTrans();
  280. //修改认证信息
  281. $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
  282. if (!$result) {
  283. Db::rollback();
  284. $this->error('查询认证结果失败2');
  285. }
  286. //修改用户信息
  287. $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', $edit_data['status']);
  288. if (!$rs) {
  289. Db::rollback();
  290. $this->error('查询认证结果失败3');
  291. }
  292. if ($edit_data['status'] == 1) { //通过
  293. //tag任务赠送金币
  294. //真人认证奖励
  295. $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,6);
  296. if($task_rs === false){
  297. Db::rollback();
  298. $this->error('完成任务赠送奖励失败');
  299. }
  300. //系统消息
  301. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
  302. } else {
  303. //系统消息
  304. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
  305. }
  306. Db::commit();
  307. $this->success($msg);
  308. }
  309. //真人认证后修改头像
  310. public function editrealavatar() {
  311. if ($this->auth->real_status != 1) {
  312. $this->error('尚未通过真人认证');
  313. }
  314. $avatar = input('avatar', '', 'trim'); //头像地址
  315. if ($avatar === '') {
  316. $this->error('参数缺失');
  317. }
  318. $avatar = one_domain_image($avatar);
  319. $now_avatar = one_domain_image($this->auth->avatar);
  320. if ($avatar == $now_avatar) {
  321. $this->error('头像未改变');
  322. }
  323. //腾讯云人脸识别
  324. $auit_result = $this->face_tencent($now_avatar, $avatar); //1通过 0拒绝
  325. if ($auit_result != 1) {
  326. $this->success('提示', ['code' => 2]);
  327. }
  328. $data['avatar'] = $avatar;
  329. $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
  330. if (!$user_result) {
  331. $this->error('修改失败');
  332. }
  333. $this->success('修改成功');
  334. }
  335. //真人认证后修改头像并取消真人认证
  336. public function editrealavatarcancelauit() {
  337. if ($this->auth->real_status != 1) {
  338. $this->error('尚未通过真人认证');
  339. }
  340. $avatar = input('avatar', '', 'trim'); //头像地址
  341. if ($avatar === '') {
  342. $this->error('参数缺失');
  343. }
  344. $avatar = one_domain_image($avatar);
  345. $now_avatar = one_domain_image($this->auth->avatar);
  346. if ($avatar == $now_avatar) {
  347. $this->error('头像未改变');
  348. }
  349. $data['avatar'] = $avatar;
  350. $data['real_status'] = -1;
  351. //开启事务
  352. Db::startTrans();
  353. $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
  354. if (!$user_result) {
  355. Db::rollback();
  356. $this->error('修改失败');
  357. }
  358. $user_auth_result = Db::name('user_auth')->where(['user_id' => $this->auth->id])->delete();
  359. if (!$user_auth_result) {
  360. Db::rollback();
  361. $this->error('修改失败');
  362. }
  363. Db::commit();
  364. $this->success('修改成功');
  365. }
  366. //腾讯云人脸识别
  367. public function face_tencent($urla = '', $urlb = '') {
  368. // require_once 'vendor/autoload.php';
  369. try {
  370. // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
  371. // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
  372. $config = config('tencent_realauth');
  373. $cred = new Credential($config['SecretId'], $config['SecretKey']);
  374. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  375. $httpProfile = new HttpProfile();
  376. $httpProfile->setEndpoint("iai.tencentcloudapi.com");
  377. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  378. $clientProfile = new ClientProfile();
  379. $clientProfile->setHttpProfile($httpProfile);
  380. // 实例化要请求产品的client对象,clientProfile是可选的
  381. $client = new IaiClient($cred, "ap-beijing", $clientProfile);
  382. // 实例化一个请求对象,每个接口都会对应一个request对象
  383. $req = new CompareFaceRequest();
  384. $params = array(
  385. "UrlA" => $urla,
  386. "UrlB" => $urlb,
  387. "FaceModelVersion" => "3.0"
  388. );
  389. $req->fromJsonString(json_encode($params));
  390. // 返回的resp是一个CompareFaceResponse的实例,与请求对象对应
  391. $resp = $client->CompareFace($req);
  392. // 输出json格式的字符串回包
  393. // print_r($resp->toJsonString());
  394. $result = json_decode($resp->toJsonString(), true);
  395. //3.0版本误识率千分之一对应分数为40分,误识率万分之一对应分数为50分,误识率十万分之一对应分数为60分。 一般超过50分则可认定为同一人。
  396. if (isset($result['Score']) && $result['Score'] >= 60) {
  397. return 1; //通过
  398. } else {
  399. return 0;
  400. }
  401. }
  402. catch(TencentCloudSDKException $e) {
  403. // echo $e;
  404. return 0;
  405. }
  406. }
  407. ////////////////////////////////////////////////////////////////////////////////////
  408. //产品链接:https://market.aliyun.com/products/57000002/cmapi026109.html#sku=yuncode20109000025
  409. //阿里云-数脉api
  410. //姓名+身份证号
  411. private function userauth_aliyun_two($cardNo = '',$realname = ''){
  412. if(!$cardNo || !$realname){
  413. return false;
  414. }
  415. $config = config('aliyun_auth_shumai_two');
  416. $host = "https://eid.shumaidata.com";
  417. $path = "/eid/check";
  418. $method = "POST";
  419. $appcode = $config['app_code'];
  420. $headers = array();
  421. array_push($headers, "Authorization:APPCODE " . $appcode);
  422. $querys = "idcard=".$cardNo."&name=".urlencode($realname);
  423. $bodys = '';
  424. $url = $host . $path . "?" . $querys;
  425. $curl = curl_init();
  426. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  427. curl_setopt($curl, CURLOPT_URL, $url);
  428. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  429. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  430. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  431. //设定返回信息中是否包含响应信息头,启用时会将头文件的信息作为数据流输出,true 表示输出信息头, false表示不输出信息头
  432. //如果需要将字符串转成json,请将 CURLOPT_HEADER 设置成 false
  433. curl_setopt($curl, CURLOPT_HEADER, false);
  434. if (1 == strpos("$".$host, "https://"))
  435. {
  436. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  437. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  438. }
  439. $returnRes = curl_exec($curl);
  440. //var_dump($returnRes);
  441. curl_close($curl);
  442. $result = json_decode($returnRes,true);
  443. //dump($result);
  444. if(is_array($result) && isset($result['code']) && $result['code'] == 0){
  445. if(isset($result['result']) && isset($result['result']['res'])){
  446. if($result['result']['res'] == 1){
  447. //实名过了
  448. return true;
  449. }
  450. }
  451. }
  452. return false;
  453. }
  454. //产品链接:https://market.aliyun.com/products/57000002/cmapi026100.html?spm=5176.730005.result.8.1dbc123e8ArY19&innerSource=search#sku=yuncode2010000006
  455. //阿里云-数脉api
  456. //姓名+手机号+身份证号
  457. private function userauth_aliyun_three($cardNo = '',$realname = '',$mobile = ''){
  458. if(!$cardNo || !$realname || !$mobile){
  459. return false;
  460. }
  461. $config = config('aliyun_auth_shumai');
  462. $host = "https://mobile3elements.shumaidata.com";
  463. $path = "/mobile/verify_real_name";
  464. $method = "POST";
  465. $appcode = $config['app_code'];
  466. $headers = array();
  467. array_push($headers, "Authorization:APPCODE " . $appcode);
  468. //根据API的要求,定义相对应的Content-Type
  469. array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
  470. $querys = "";
  471. $bodys = "idcard=".$cardNo."&mobile=".$mobile."&name=".urlencode($realname);
  472. $url = $host . $path;
  473. $curl = curl_init();
  474. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  475. curl_setopt($curl, CURLOPT_URL, $url);
  476. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  477. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  478. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  479. //设定返回信息中是否包含响应信息头,启用时会将头文件的信息作为数据流输出,true 表示输出信息头, false表示不输出信息头
  480. //如果需要将字符串转成json,请将 CURLOPT_HEADER 设置成 false
  481. curl_setopt($curl, CURLOPT_HEADER, false);
  482. if (1 == strpos("$".$host, "https://"))
  483. {
  484. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  485. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  486. }
  487. curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
  488. $returnRes = curl_exec($curl);
  489. curl_close($curl);
  490. $result = json_decode($returnRes,true);
  491. if(is_array($result) && isset($result['code']) && $result['code'] == 0){
  492. if(isset($result['result']) && isset($result['result']['res'])){
  493. if($result['result']['res'] == 1){
  494. //实名过了
  495. return true;
  496. }
  497. }
  498. }
  499. return false;
  500. }
  501. }