Userauth.php 20 KB

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