二步验证 代码实现

2019-03-15 18:01:33   工作备份

  二步验证  

  1. <?php
  2. require_once "./vendor/autoload.php";
  3. error_reporting(E_ALL | E_STRICT);
  4. ini_set("display_errors", 1);
  5. class Authenticator
  6. {
  7. protected $googleClient;
  8. protected $secret;
  9. public function __construct()
  10. {
  11. $this->googleClient = new PHPGangsta_GoogleAuthenticator();
  12. }
  13. public function createSecret()
  14. {
  15. $secret = $this->googleClient->createSecret();
  16. return $secret;
  17. }
  18. public function createQr($url)
  19. {
  20. $secret = $this->createSecret();
  21. $this->InsertSecret(1, $secret);
  22. $qr = $this->googleClient->getQRCodeGoogleUrl($url, $secret);
  23. echo "秘钥:$secret" . PHP_EOL;
  24. return "<img src='$qr'/>";
  25. }
  26. public function InsertSecret($id, $secret)
  27. {
  28. //将服务器生成的secret入库与用户绑定
  29. }
  30. public function getSecret($id)
  31. {
  32. //将对应用户的secret提取出来并返回
  33. return 'GBYTMLVRNQKAKJVD';
  34. }
  35. public function verify($id, $verify)
  36. {
  37. $checkResult = $this->googleClient->verifyCode($this->getSecret(1), (string)$verify, 0);
  38. if ($checkResult) {
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. }
  45. $client = new Authenticator();
  46. echo $client->createQr("www.zhangshuxian.top");
  47. echo $client->verify(1, 436270) ? "通过" : "未通过";