| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- <?php
- namespace app\agent\service;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\ClientException;
- use GuzzleHttp\Exception\GuzzleException;
- use think\facade\Cache;
- use think\facade\Log;
- class SmsCode
- {
- private $config = [
- 'host' => 'http://47.92.32.85:7862/sms',
- 'account' => '800003',
- 'password' => '123456'
- ];
- /**
- * SmsCode constructor.
- * @param array $config
- */
- public function __construct($config = [])
- {
- if (!empty($config)){
- $this->config = $config;
- }
- }
- /**
- * 缓存手机码
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/7/10 14:15
- *
- * @param $mobile
- * @param $code
- */
- private function cacheCode($mobile, $code)
- {
- Cache::set($mobile, $code,5 * 60);
- }
- /**
- * 获取缓存码
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/7/10 14:15
- *
- * @param $mobile
- * @return mixed
- */
- private function getCode($mobile)
- {
- return Cache::get($mobile);
- }
- /**
- * 随意码 - 6
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/7/10 14:24
- *
- * @return int
- */
- private function randCode()
- {
- return rand(111111,999999);
- }
- /**
- * 验证
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/7/10 14:26
- *
- * @param string $mobile 手机号
- * @param string $code 验证码
- * @return bool
- */
- public function verify($mobile, $code)
- {
- if ($this->getCode($mobile) == $code){
- return true;
- }
- return false;
- }
- /**
- * 发送验证码
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/7/10 14:36
- *
- * @param $mobile
- * @return mixed|array|\Psr\Http\Message\ResponseInterface
- * @throws GuzzleException
- */
- public function send($mobile)
- {
- // rand code
- $code = $this->randCode();
- // cache code by number
- $this->cacheCode($mobile,$code);
- try {
- // http
- $client = new Client();
- $result = $client->request('POST', $this->config['host'], [
- 'query' => [
- 'action' => 'send',
- 'account' => $this->config['account'],
- 'password' => $this->config['password'],
- 'mobile' => $mobile,
- 'content' => sprintf('【人人接】欢迎您,您的验证码为:%s,请勿将验证码告知他人', $code),
- 'extno' => '',
- 'rt' => 'json'
- ]
- ]);
- // 返回处理
- $result = dejson($result->getBody());
- return ($result['status'] == 0) ? $result : false;
- }catch ( ClientException $e){
- Log::error('验证码发送失败:[' . $e->getMessage() . ']');
- return false;
- }
- }
- }
|