Code.php 2.6 KB

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