<?php namespace app\service; use fast\Random; use think\Exception; use think\Log; class SmsService extends BaseService { public $key = '';//您申请的接口调用Key public $template_id = '';//模板id public function send(string $mobile, string $event, string $ip) { $code = Random::numeric(config('captcha.length')); // 请求参数 $smsConf = array( 'key' => $this->key, //您申请的APPKEY 'mobile' => $mobile, //接受短信的用户手机号码 'tpl_id' => $this->template_id, //您申请的短信模板ID,根据实际情况修改 'tpl_value' => '#code#=' . $code //您设置的模板变量,根据实际情况修改 ); $content = self::sendCodeFunc('http://v.juhe.cn/sms/send', $smsConf, 1); //请求发送短信 $res = json_decode($content, true); $error_code = $res['error_code']; if ($error_code == 0) { // 发送成功 $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => time()]); }else{ Log::log('短信发送出错,手机号码:'.$mobile.',msg:'.$res['reason']); return false; } return true; } /** * 发起网络请求函数 * @param string $url 请求的URL * @param bool $params 请求的参数内容 * @param int $ispost 是否POST请求 * @return bool|string 返回内容 */ public static function sendCodeFunc($url, $params = false, $ispost = 0) { $httpInfo = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($ispost) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_URL, $url); } else { if ($params) { curl_setopt($ch, CURLOPT_URL, $url . '?' . $params); } else { curl_setopt($ch, CURLOPT_URL, $url); } } $response = curl_exec($ch); if ($response === FALSE) { return false; } $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpInfo = array_merge($httpInfo, curl_getinfo($ch)); curl_close($ch); return $response; } }
标签:ch,聚合,setopt,return,code,短信,curl,PHP,CURLOPT From: https://www.cnblogs.com/PLasir/p/17534597.html