Sms.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * hook钩子触发短信发送
  4. */
  5. namespace app\api\hook;
  6. //阿里云短信发送相关类 composer安装
  7. //composer require alibabacloud/sdk
  8. //use Swoft\Task\Bean\Annotation\Task;
  9. use AlibabaCloud\Client\AlibabaCloud;
  10. use AlibabaCloud\Client\Exception\ClientException;
  11. use AlibabaCloud\Client\Exception\ServerException;
  12. class Sms
  13. {
  14. //发送验证码
  15. //@sms 验证码发送记录数数据库实例
  16. //$sms->mobile 手机号码
  17. //['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]
  18. function smsSend($sms)
  19. {
  20. // return '11111';
  21. return $this->sendMsg($sms->mobile,['code'=>$sms->code],'code');
  22. }
  23. function smsCheck($sms)
  24. {
  25. // return $this->sendMsg($sms['mobile'],['code'=>$sms['code']],'code');
  26. if($this->sendMsg($sms['mobile'],['code'=>$sms['code']],'code')){
  27. $sms = \app\common\model\Sms::create(['event' => $sms['event'], 'mobile' => $sms['mobile'], 'code' => $sms['code'], 'ip' => '', 'createtime' => $sms['createtime']]);
  28. return true;
  29. }
  30. }
  31. //@mobile 手机号码
  32. //@param 短信发送参数
  33. //@template 短信发送模板编号key值
  34. private function sendMsg($mobile,$param,$template){
  35. $config = \config('alisms');
  36. // return json($config);
  37. if(empty($param)||!isset($config)||empty($config)){
  38. return false;
  39. }
  40. AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
  41. ->regionId($config['regionId'])
  42. ->asGlobalClient();
  43. $TemplateCode = isset($config['TemplateCode'][$template])?$config['TemplateCode'][$template]:$config['TemplateCode']['code'];
  44. try {
  45. $result = AlibabaCloud::rpcRequest()
  46. ->product('Dysmsapi')
  47. ->version('2017-05-25')
  48. ->action('SendSms')
  49. ->method('POST')
  50. ->options([
  51. 'query' => [
  52. 'PhoneNumbers' => $mobile,
  53. 'SignName' => $config['SignName'],
  54. 'TemplateCode' => $TemplateCode,
  55. 'TemplateParam' => json_encode($param)
  56. ],
  57. ])
  58. ->request();
  59. if($result->Code=="OK"){
  60. return $result;
  61. }else{
  62. return $result;
  63. }
  64. print_r($result->toArray());
  65. } catch (ClientException $e) {
  66. return $e;
  67. echo $e->getErrorMessage() . PHP_EOL;
  68. } catch (ServerException $e) {
  69. return $e;
  70. echo $e->getErrorMessage() . PHP_EOL;
  71. }
  72. }
  73. }