Userauth.php 22 KB

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