Code.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php namespace Msg\Lib\Type;
  2. use Dever;
  3. use Api\Lib\Account;
  4. class Code
  5. {
  6. private $config;
  7. # 发送验证码
  8. public function send($template, $account = [], $param = [], $project = 'api')
  9. {
  10. $data['template_id'] = $template['id'];
  11. $data['day'] = date('Ymd', DEVER_TIME);
  12. if (empty($param['code'])) {
  13. $this->config = Dever::db('msg/template_code')->find(['template_id' => $template['id']]);
  14. if (!$this->config) {
  15. Dever::error('验证码未配置');
  16. }
  17. $param['code'] = $this->createCode();
  18. }
  19. if ($template['content']) {
  20. $template['content'] = \Dever\Helper\Str::val($template['content'], $param);
  21. }
  22. $test = 1;
  23. foreach ($template['method'] as $k => $v) {
  24. $config = Dever::db('msg/account')->find(['method' => $v]);
  25. if ($config) {
  26. $handle = Dever::load('\\Msg\\Lib\\Method\\' . $config['method']);
  27. $data['account'] = $handle->init($template['id'], $config['id'], $account, $project);
  28. $this->valid($data);
  29. if ($config['test'] == 2) {
  30. $test = 2;
  31. $api = Dever::load(Account::class)->get($config['api_account_id'], $project);
  32. $data['record'] = $handle->send($api, $template['content'], $param);
  33. }
  34. $data['code'] = $param['code'];
  35. $data['status'] = 1;
  36. Dever::db('msg/code')->insert($data);
  37. # 这里以后加入计费机制
  38. }
  39. }
  40. $msg = '验证码发送成功';
  41. if ($test == 1) {
  42. $msg .= '::' . $param['code'];
  43. }
  44. return $msg;
  45. }
  46. # 检测并使用验证码
  47. public function check($template_id, $account, $code, $update = 1)
  48. {
  49. $info = Dever::db('msg/code')->find(['template_id' => $template_id, 'account' => $account], ['order' => 'cdate desc']);
  50. if ($info && $info['status'] == 1 && $code == $info['code']) {
  51. if ($update == 1) {
  52. Dever::db('msg/code')->update($info['id'], ['status' => 2]);
  53. }
  54. return true;
  55. }
  56. return false;
  57. }
  58. private function createCode()
  59. {
  60. $len = $this->config['length'] ? $this->config['length'] : 4;
  61. $type = $this->config['type'] ? $this->config['type'] : 1;
  62. return \Dever\Helper\Str::rand($len, $type - 1);
  63. }
  64. protected function valid($where)
  65. {
  66. $info = Dever::db('msg/code')->find($where);
  67. if ($info) {
  68. if (DEVER_TIME - $this->config['cdate'] < $this->config['interval']) {
  69. Dever::error('请不要在'.$this->config['interval'].'秒之内申请多次验证码,请您稍后再试');
  70. } elseif (Dever::db('msg/code')->count($where) >= $this->config['total']) {
  71. Dever::error('很抱歉,您已经申请获取验证码超过' . $this->config['total'] . '次,今天您已经无法获取验证码了,请您明天再来');
  72. }
  73. }
  74. }
  75. }