<?php
namespace app\service;
use app\model\SmsLog;
class Sms
{
public $error = '';
private $template = [
// 充值通过
'recharge_pass' => ['template'=>'尊敬的尾号${phone}用户,您于${datetime}充值${price}元已到账。','param_num'=>3],
// 充值驳回
'recharge_reject' => ['template'=>'尊敬的尾号${phone}用户,您于${datetime}充值${price}元申请被驳回,驳回原因为:${reject_reason}。若有疑问请与您的专属客服联系。','param_num'=>4],
// 提现通过
'cash_pass' => ['template'=>'尊敬的尾号${phone}用户,您于${datetime}申请提${price}元已成功,我们将在1-3个工作日内完成审核,请您耐心等待。','param_num'=>3],
// 提现驳回
'cash_reject' => ['template'=>'尊敬的尾号${phone}用户,您于${datetime}申请提${price}元被驳回,驳回原因为:${reject_reason}。若有疑问请与您的专属客服联系。','param_num'=>4],
// 发送短信验证码
'sms_code' => ['template'=>'您的验证码是${code}','param_num'=>2],
];
//发送短信
public function send($mobile,$template_key,$data = null)
{
if($template_key != 'sms_code'){
return true;
}
if(!$mobile){
$this->error = '手机号码有误';
return false;
}
if(!$template_key || !isset($this->template[$template_key])){
$this->error = '短信模板有误';
return false;
}
if(!isset($data['phone'])){
$data['phone'] = substr($mobile,-4);
}
if($this->template[$template_key]['param_num'] > 0 && $this->template[$template_key]['param_num'] != count($data)){
$this->error = '短信模板参数有误';
return false;
}
$template = $this->template[$template_key]['template'];
foreach ($data as $key=>$value){
$template = str_replace('${'.$key.'}',$value,$template);
}
$template = '【短信签名】'.$template;
$result = $this->sendSms($mobile,$template);
try{
$sms_data = [
'send_phone'=> $mobile,
'sms_sign' => $template_key,
'content' => $template,
'param' => $data
];
$data = [
'sms_type' => $template_key,
'create_time' => time(),
'sms_ip' => request()->ip(),
'sms_phone' => $mobile,
'sms_code' => '',
'sms_status' => $result['code'] == 0 ? 1 : 0,
'sms_return_code' => json_encode($result['data'],JSON_UNESCAPED_UNICODE),
'sms_content' => json_encode($sms_data,JSON_UNESCAPED_UNICODE)
];
SmsLog::writeSmsLog($data); // 写入数据
}catch (\Exception $e){
}
return true;
}
public function sendSms($mobile,$content)
{
try{
//todo:实现短信发送功能
$host = "";
$querys = [
'mobile'=>$mobile,
'content'=>$this->strToUtf8($content),
];
$url = $host.'?'.http_build_query($querys);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
$result = json_decode($result,true);
if($result && $result['status'] == 0 && $result['list'][0]['result'] == 0){
$sms_rs = [
'code' => 0,
'msg' => '发送成功',
'data' => $result
];
}else{
$sms_rs = [
'code' => 1,
'msg' => '发送失败',
'data' => $result
];
}
}catch (\Exception $e){
$sms_rs = [
'code' => 1,
'msg' => '发送失败,'.$e->getMessage(),
'data' => ''
];
}
return $sms_rs;
}
private function strToUtf8($str){
$encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
if($encode == 'UTF-8'){
return $str;
}else{
return mb_convert_encoding($str, 'UTF-8', $encode);
}
}
暂无评论