Userauth.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. /**
  6. * 实名认证
  7. */
  8. class Userauth extends Api
  9. {
  10. // 无需登录的接口,*表示全部
  11. protected $noNeedLogin = ['test', 'test1'];
  12. // 无需鉴权的接口,*表示全部
  13. protected $noNeedRight = ['test2'];
  14. //实名认证信息
  15. public function idcard_confirm_info(){
  16. $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->order('id desc')->find();
  17. if (!$check) {
  18. $check = (object)[];
  19. }
  20. $this->success('success',$check);
  21. }
  22. //实名认证
  23. public function idcard_auth() {
  24. $info = Db::name('user_idconfirm')->where(['user_id' => $this->auth->id])->find();
  25. // if ($info && $info['status'] == 0) {
  26. // $this->error('您已经提交信息了,请进行人脸认证!');
  27. // }
  28. if ($info && $info['status'] == 1) {
  29. $this->error('您已通过审核!');
  30. }
  31. $nickname = input('nickname', '', 'trim'); // 姓名
  32. $idcard = input('idcard', '', 'trim'); // 身份证号
  33. if ($nickname === '') {
  34. $this->error('请输入姓名');
  35. }
  36. if (iconv_strlen($nickname, 'utf-8') > 50) {
  37. $this->error('请输入正确姓名');
  38. }
  39. if ($idcard === '') {
  40. $this->error('请输入身份证号');
  41. }
  42. if (iconv_strlen($idcard, 'utf-8') != 18) {
  43. $this->error('请输入正确身份证号');
  44. }
  45. $count = Db::name('user_idconfirm')->where(['idcard' => $idcard, 'user_id' => ['neq', $this->auth->id]])->count('id');
  46. if ($count) {
  47. $this->error('身份证号已存在');
  48. }
  49. $data = [];
  50. $data['truename'] = $nickname;
  51. $data['idcard'] = $idcard;
  52. //腾讯云身份证二要素认证
  53. $auth_restult = $this->userauth_tencent($idcard, $nickname);
  54. if ($auth_restult) {
  55. $data['status'] = 1; //通过
  56. $msg = '认证通过';
  57. } else {
  58. $data['status'] = 2; //不通过
  59. $msg = '认证不通过';
  60. }
  61. //开启事务
  62. Db::startTrans();
  63. if (!$info) { //未认证
  64. $data["user_id"] = $this->auth->id;
  65. $data["createtime"] = time();
  66. $res = Db::name('user_idconfirm')->insertGetId($data);
  67. } else { //认证被拒绝过
  68. $data['updatetime'] = time();
  69. $res = Db::name('user_idconfirm')->where(['id' => $info['id'], 'user_id' => $this->auth->id])->setField($data);
  70. }
  71. if (!$res) {
  72. Db::rollback();
  73. $this->error('认证失败');
  74. }
  75. $rt = Db::name('user')->where(['id' => $this->auth->id, 'idcard_status' => $this->auth->idcard_status])->setField('idcard_status', $data['status']);
  76. if ($rt === false) {
  77. Db::rollback();
  78. $this->error('认证失败');
  79. }
  80. if ($data['status'] == 1) {
  81. //完成实名认证 +20金币
  82. $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,4);
  83. if($task_rs === false){
  84. Db::rollback();
  85. $this->error('完成任务赠送奖励失败');
  86. }
  87. //系统消息
  88. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'实名认证','实名认证已经审核通过');
  89. } else {
  90. //系统消息
  91. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'实名认证','实名认证审核不通过');
  92. }
  93. Db::commit();
  94. $this->success($msg);
  95. }
  96. //腾讯云身份证二要素认证
  97. public function userauth_tencent($idcard = '', $nickname = '') {
  98. // require_once 'vendor/autoload.php';
  99. try {
  100. // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
  101. // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
  102. $config = config('tencent_im');
  103. $cred = new Credential($config['SecretId'], $config['SecretKey']);
  104. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  105. $httpProfile = new HttpProfile();
  106. $httpProfile->setEndpoint("faceid.tencentcloudapi.com");
  107. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  108. $clientProfile = new ClientProfile();
  109. $clientProfile->setHttpProfile($httpProfile);
  110. // 实例化要请求产品的client对象,clientProfile是可选的
  111. $client = new FaceidClient($cred, "", $clientProfile);
  112. // 实例化一个请求对象,每个接口都会对应一个request对象
  113. $req = new IdCardVerificationRequest();
  114. $params = array(
  115. "IdCard" => $idcard,
  116. "Name" => $nickname
  117. );
  118. $req->fromJsonString(json_encode($params));
  119. // 返回的resp是一个IdCardVerificationResponse的实例,与请求对象对应
  120. $resp = $client->IdCardVerification($req);
  121. // 输出json格式的字符串回包
  122. // print_r($resp->toJsonString());
  123. $result = json_decode($resp->toJsonString(), true);
  124. if (isset($result['Result']) && $result['Result'] == 0) {
  125. return 1; //通过
  126. } else {
  127. return 0;
  128. }
  129. }
  130. catch(TencentCloudSDKException $e) {
  131. // echo $e;
  132. return 0;
  133. }
  134. }
  135. //申请真人认证
  136. public function realauth() {
  137. if ($this->auth->real_status == 1) {
  138. $this->error('您已经真人认证过了~');
  139. }
  140. if ($this->auth->avatar == config('avatar_boy') || $this->auth->avatar == config('avatar_girl')) {
  141. $this->error('请先上传真人头像~');
  142. }
  143. //获取token
  144. $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';
  145. $token_result = file_get_contents($token_url);
  146. if (!$token_result) {
  147. $this->error('您的网络开小差啦1~');
  148. }
  149. $token_result = json_decode($token_result, true);
  150. if ($token_result['code'] != 0) {
  151. $this->error('您的网络开小差啦2~');
  152. }
  153. $token = $token_result['access_token'];
  154. //获取签名鉴权参数ticket
  155. $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';
  156. $ticket_result = file_get_contents($ticket_url);
  157. if (!$ticket_result) {
  158. $this->error('您的网络开小差啦3~');
  159. }
  160. $ticket_result = json_decode($ticket_result, true);
  161. if ($ticket_result['code'] != 0) {
  162. $this->error('您的网络开小差啦4~');
  163. }
  164. $ticket = $ticket_result['tickets'][0]['value'];
  165. //获取签名
  166. $sign_data = [
  167. 'wbappid' => config('tencent_yun')['secret_id'],
  168. 'userId' => (string)$this->auth->id,
  169. 'version' => '1.0.0',
  170. 'ticket' => $ticket,
  171. 'nonce' => Random::alnum(32)
  172. ];//p($sign_data);
  173. asort($sign_data); //p($sign_data);//排序
  174. $sign_string = join('', $sign_data);//p($sign_string);
  175. $sign = sha1($sign_string);//p($sign);
  176. //上传身份信息
  177. $orderNo = getMillisecond() . $this->auth->id . mt_rand(1, 1000); //商户请求的唯一标识
  178. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/server/getAdvFaceId?orderNo=' . $orderNo;
  179. $avatar = one_domain_image($this->auth->avatar);
  180. $avatar = str_replace('https', 'http', $avatar);
  181. $img = file_get_contents($avatar);
  182. $img = str_replace('data:image/jpg;base64', '', $img);
  183. $img = str_replace('\n', '', $img);
  184. $sourcePhotoStr = base64_encode($img);
  185. $data = [
  186. 'webankAppId' => config('tencent_yun')['secret_id'],
  187. 'orderNo' => $orderNo,
  188. 'userId' => (string)$this->auth->id,
  189. 'sourcePhotoStr' => $sourcePhotoStr,
  190. 'sourcePhotoType' => 2,
  191. 'version' => '1.0.0',
  192. 'sign' => $sign,
  193. 'nonce' => $sign_data['nonce']
  194. ];
  195. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  196. if (!$rs) {
  197. $this->error('您的网络开小差啦5~');
  198. }
  199. $rs = json_decode($rs, true);
  200. if (!$rs || $rs['code'] != 0) {
  201. $this->error('您的网络开小差啦6~');
  202. }
  203. $user_auth = [
  204. 'user_id' => $this->auth->id,
  205. 'certify_id' => $rs['result']['faceId'],
  206. 'out_trade_no' => $data['orderNo'],
  207. 'status' => 0,
  208. 'createtime' => time(),
  209. 'updatetime' => time()
  210. ];
  211. //开启事务
  212. Db::startTrans();
  213. //查询是否认证过
  214. $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  215. if ($info) {
  216. $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
  217. } else {
  218. $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
  219. }
  220. if (!$auth_rs) {
  221. Db::rollback();
  222. $this->error('您的网络开小差啦7~');
  223. }
  224. //修改用户表认证状态
  225. $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', 0);
  226. if ($user_rs === false) {
  227. Db::rollback();
  228. $this->error('您的网络开小差啦8~');
  229. }
  230. Db::commit();
  231. $return_data = [
  232. 'face_id' => $user_auth['certify_id'],
  233. 'order_no' => $user_auth['out_trade_no'],
  234. 'user_id' => (string)$this->auth->id,
  235. 'nonce' => $sign_data['nonce'],
  236. 'sign' => $sign
  237. ];
  238. $this->success('success', $return_data);
  239. }
  240. //查询真人认证结果
  241. public function getrealauthresult() {
  242. $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  243. if (!$user_auth) {
  244. $this->success('尚未认证');
  245. }
  246. if ($user_auth['status'] == 1) {
  247. $this->success('真人认证通过');
  248. }
  249. if (!$user_auth['certify_id']) {
  250. $this->success('请先进行真人认证');
  251. }
  252. //获取token
  253. $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';
  254. $token_result = file_get_contents($token_url);
  255. if (!$token_result) {
  256. $this->error('您的网络开小差啦1~');
  257. }
  258. $token_result = json_decode($token_result, true);
  259. if ($token_result['code'] != 0) {
  260. $this->error('您的网络开小差啦2~');
  261. }
  262. $token = $token_result['access_token'];
  263. //获取签名鉴权参数ticket
  264. $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';
  265. $ticket_result = file_get_contents($ticket_url);
  266. if (!$ticket_result) {
  267. $this->error('您的网络开小差啦3~');
  268. }
  269. $ticket_result = json_decode($ticket_result, true);
  270. if ($ticket_result['code'] != 0) {
  271. $this->error('您的网络开小差啦4~');
  272. }
  273. $ticket = $ticket_result['tickets'][0]['value'];
  274. //获取签名
  275. $sign_data = [
  276. 'wbappid' => config('tencent_yun')['secret_id'],
  277. 'orderNo' => $user_auth['out_trade_no'],
  278. 'version' => '1.0.0',
  279. 'ticket' => $ticket,
  280. 'nonce' => Random::alnum(32)
  281. ];//p($sign_data);
  282. asort($sign_data); //p($sign_data);//排序
  283. $sign_string = join('', $sign_data);//p($sign_string);
  284. $sign = sha1($sign_string);//p($sign);
  285. //人脸核身结果查询
  286. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
  287. $data = [
  288. 'appId' => config('tencent_yun')['secret_id'],
  289. 'version' => '1.0.0',
  290. 'nonce' => $sign_data['nonce'],
  291. 'orderNo' => $user_auth['out_trade_no'],
  292. 'sign' => $sign
  293. ];
  294. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  295. if (!$rs) {
  296. $this->error('您的网络开小差啦5~');
  297. }
  298. $rs = json_decode($rs, true);
  299. if (!$rs || $rs['code'] != 0) {
  300. $this->error($rs['msg']);
  301. }
  302. if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
  303. $edit_data['status'] = 1;
  304. $msg = '真人认证成功';
  305. } else {
  306. $edit_data['status'] = 2;
  307. $edit_data['certify_id'] = '';
  308. $edit_data['out_trade_no'] = '';
  309. $msg = '真人认证失败';
  310. }
  311. $edit_data['updatetime'] = time();
  312. //开启事务
  313. Db::startTrans();
  314. //修改认证信息
  315. $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
  316. if (!$result) {
  317. Db::rollback();
  318. $this->error('查询认证结果失败2');
  319. }
  320. //修改用户信息
  321. $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', $edit_data['status']);
  322. if (!$rs) {
  323. Db::rollback();
  324. $this->error('查询认证结果失败3');
  325. }
  326. if ($edit_data['status'] == 1) { //通过
  327. //tag任务赠送金币
  328. //真人认证奖励
  329. $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,20);
  330. if($task_rs === false){
  331. Db::rollback();
  332. $this->error('完成任务赠送奖励失败');
  333. }
  334. //系统消息
  335. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
  336. } else {
  337. //系统消息
  338. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
  339. }
  340. Db::commit();
  341. $this->success($msg);
  342. }
  343. //真人认证后修改头像前比对
  344. public function realavatar_auit() {
  345. if ($this->auth->real_status != 1) {
  346. $this->error('尚未通过真人认证');
  347. }
  348. $avatar = input('avatar', '', 'trim'); //头像地址
  349. if ($avatar === '') {
  350. $this->error('参数缺失');
  351. }
  352. $avatar = one_domain_image($avatar);
  353. $now_avatar = one_domain_image($this->auth->avatar);
  354. if ($avatar == $now_avatar) {
  355. $this->error('头像未改变');
  356. }
  357. //腾讯云人脸识别
  358. $result = $this->face_tencent($now_avatar, $avatar); //1通过 0拒绝
  359. $this->success('结果', $result);
  360. }
  361. //真人认证后修改头像
  362. public function editrealavatar() {
  363. if ($this->auth->real_status != 1) {
  364. $this->error('尚未通过真人认证');
  365. }
  366. $avatar = input('avatar', '', 'trim'); //头像地址
  367. if ($avatar === '') {
  368. $this->error('参数缺失');
  369. }
  370. $avatar = one_domain_image($avatar);
  371. $now_avatar = one_domain_image($this->auth->avatar);
  372. if ($avatar == $now_avatar) {
  373. $this->error('头像未改变');
  374. }
  375. //腾讯云人脸识别
  376. $auit_result = $this->face_tencent($now_avatar, $avatar); //1通过 0拒绝
  377. if ($auit_result != 1) {
  378. $this->success('提示', ['code' => 2]);
  379. }
  380. $data['avatar'] = $avatar;
  381. $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
  382. if (!$user_result) {
  383. $this->error('修改失败');
  384. }
  385. $this->success('修改成功');
  386. }
  387. //真人认证后修改头像并取消真人认证
  388. public function editrealavatarcancelauit() {
  389. if ($this->auth->real_status != 1) {
  390. $this->error('尚未通过真人认证');
  391. }
  392. $avatar = input('avatar', '', 'trim'); //头像地址
  393. if ($avatar === '') {
  394. $this->error('参数缺失');
  395. }
  396. $avatar = one_domain_image($avatar);
  397. $now_avatar = one_domain_image($this->auth->avatar);
  398. if ($avatar == $now_avatar) {
  399. $this->error('头像未改变');
  400. }
  401. $data['avatar'] = $avatar;
  402. $data['real_status'] = -1;
  403. //开启事务
  404. Db::startTrans();
  405. $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
  406. if (!$user_result) {
  407. Db::rollback();
  408. $this->error('修改失败');
  409. }
  410. $user_auth_result = Db::name('user_auth')->where(['user_id' => $this->auth->id])->delete();
  411. if (!$user_auth_result) {
  412. Db::rollback();
  413. $this->error('修改失败');
  414. }
  415. Db::commit();
  416. $this->success('修改成功');
  417. }
  418. //腾讯云人脸识别
  419. public function face_tencent($urla = '', $urlb = '') {
  420. // require_once 'vendor/autoload.php';
  421. try {
  422. // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
  423. // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
  424. $config = config('tencent_im');
  425. $cred = new Credential($config['SecretId'], $config['SecretKey']);
  426. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  427. $httpProfile = new HttpProfile();
  428. $httpProfile->setEndpoint("iai.tencentcloudapi.com");
  429. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  430. $clientProfile = new ClientProfile();
  431. $clientProfile->setHttpProfile($httpProfile);
  432. // 实例化要请求产品的client对象,clientProfile是可选的
  433. $client = new IaiClient($cred, "ap-beijing", $clientProfile);
  434. // 实例化一个请求对象,每个接口都会对应一个request对象
  435. $req = new CompareFaceRequest();
  436. $params = array(
  437. "UrlA" => $urla,
  438. "UrlB" => $urlb,
  439. "FaceModelVersion" => "3.0"
  440. );
  441. $req->fromJsonString(json_encode($params));
  442. // 返回的resp是一个CompareFaceResponse的实例,与请求对象对应
  443. $resp = $client->CompareFace($req);
  444. // 输出json格式的字符串回包
  445. // print_r($resp->toJsonString());
  446. $result = json_decode($resp->toJsonString(), true);
  447. //3.0版本误识率千分之一对应分数为40分,误识率万分之一对应分数为50分,误识率十万分之一对应分数为60分。 一般超过50分则可认定为同一人。
  448. if (isset($result['Score']) && $result['Score'] >= 60) {
  449. return 1; //通过
  450. } else {
  451. return 0;
  452. }
  453. }
  454. catch(TencentCloudSDKException $e) {
  455. // echo $e;
  456. return 0;
  457. }
  458. }
  459. }