1要拼接接收的手机号和短信
public function sendcode() { $parpm = input(); $valist = $this->validate($parpm, [ 'phone' => 'require|regex:1[3-9]\d{9}' ]); if ($valist !== true) { $res = [ 'code' => 400, 'msg' => $valist ]; return Json($res); die; } $timer = cache('register_time_' . $parpm['phone']); if (time() - $timer < 60) { $rs = [ 'code' => '500', 'msg' => '发送太过频繁' ]; echo json_encode($rs); die; } $co = mt_rand(1000, 9999); $code = '%23code%23%3d' . $co; //发送短信验证 // $resule=sendmsg($parpm['phone'],$code); $resule = true; if ($resule === true) { cache('register_code_' . $parpm['phone'], $co, 180); cache('register_time_' . $parpm['phone'], time(), 180); $re = [ 'code' => 200, 'msg' => '短信发送成功', 'data' => "$code" ]; echo json_encode($re); die; } else { $re = [ 'code' => 400, 'msg' => $resule ]; echo json_encode($re); die; } }
2拼接要发送短信的要求
if(!function_exists('sendmsg')){ function sendmsg($phone,$code){ $gateway=config('msg.gateway'); $appkey=config('msg.appkey'); $tpl_id=config('msg.tpl_id'); $url=$gateway.'?mobile='.$phone.'&tpl_id='.$tpl_id.'&tpl_value='.$code.'&key='.$appkey; $res=curl_require($url,false,[],false); if(!$res){ return '请求失败'; } $arr=json_decode($res,true); if(isset($arr['code'])&&$arr['code']==10000){ return true; }else{ return false; } } }
3向第三方请求
if(!function_exists('curl_require')){ function curl_require($url,$post=true,$parpm=[],$https=false){ $ch=curl_init($url); if($post){ curl_setopt($ch,CURLOPT_PORT,true); curl_setopt($ch,CURLOPT_POSTFIELDS,$parpm); } if($https){ curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); } curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $res=curl_exec($ch); curl_close($ch); return $res; } }
下面是aliyun的发信deom
// 代码节选,详见dysms_php.zip\aliyun-dysms-php-sdk\api_demo/SmsDemo.php ... class SmsDemo { ... * 短信服务API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行此文件即可体验短信服务产品API功能(只需要将AK替换成开通了云通信-短信服务产品功能的AK即可) * 备注:Demo工程编码采用UTF-8 */ /** * 发送短信 * @return stdClass */ public static function sendSms() { // 初始化SendSmsRequest实例用于设置发送短信的参数 $request = new SendSmsRequest(); // 必填,设置短信接收号码 $request->setPhoneNumbers("12345678901"); // 必填,设置签名名称,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign $request->setSignName("短信签名"); // 必填,设置模板CODE,应严格按"模板CODE"填写,(如果发送国际/港澳台消息时,请使用国际/港澳台短信模版) 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template $request->setTemplateCode("SMS_0000001"); // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项 $request->setTemplateParam(json_encode(Array( // 短信模板中字段的值 "code"=>"12345", "product"=>"dsd" ))); // 可选,设置流水号 $request->setOutId("yourOutId"); // 选填,上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段) $request->setSmsUpExtendCode("1234567"); // 发起访问请求 $acsResponse = static::getAcsClient()->getAcsResponse($request); return $acsResponse; } // 调用示例: set_time_limit(0); header('Content-Type: text/plain; charset=utf-8'); $response = SmsDemo::sendSms(); echo "发送短信(sendSms)接口返回的结果:\n"; print_r($response);
完整版deom下载:https://help.aliyun.com/document_detail/55359.html?spm=a2c4g.11186623.4.2.796351cdoeTnoI