短信发送 API

   利用了云信平台

controll:

<?php
/**
 * @name SmsController
 * @author pangee
 * @desc 短信处理功能
 */
class SmsController extends Yaf_Controller_Abstract {

	public function indexAction() {
	}
	public function sendAction() {
		$submit = $this->getRequest()->getQuery( "submit", "0" );
		if( $submit!="1" ) {
			echo json_encode( array("errno"=>-4001, "errmsg"=>"请通过正确渠道提交") );
			return FALSE;
		}

		// 获取参数
		$uid = $this->getRequest()->getPost( "uid", false );
		$contents = $this->getRequest()->getPost( "contents", false );
		if( !$uid || !$contents ) {
			echo json_encode( array("errno"=>-4002, "errmsg"=>"用户ID、邮件标题、邮件内容均不能为空。") );
			return FALSE;
		}

		// 调用Model, 发邮件
		$model = new SmsModel();
		if ( $model->send( intval($uid), trim($contents) ) ) {
			echo json_encode( array(
						"errno"=>0,
						"errmsg"=>"",
					));
		} else {
			echo json_encode( array(
						"errno"=>$model->errno,
						"errmsg"=>$model->errmsg,
					));
		}
		return TRUE;
	}
}

  model:

   利用了云信平台

<?php
/**
 * @name SmsModel
 * @desc 短信操作Model类,使用sms.cn服务,账号phpapi密码phpapi321
 * @author pangee
 */

class SmsModel {
	public $errno = 0;
	public $errmsg = "";
	private $_db;

    public function __construct() {
		$this->_db = new PDO("mysql:host=127.0.0.1;dbname=imooc;", "root", "");
    }   
    
	public function send( $uid, $contents ) {
		$query = $this->_db->prepare("select `mobile` from `user` where `id`= ? ");
		$query->execute( array(intval($uid)) );
		$ret = $query->fetchAll();
		if ( !$ret || count($ret)!=1 ) {
			$this->errno = -4003;
			$this->errmsg = "用户手机号信息查找失败";
			return false;
		}
		$userMobile = $ret[0]['mobile'];
		if( !$userMobile || !is_numeric($userMobile) || strlen($userMobile)!=11 ) {
			$this->errno = -4004;
			$this->errmsg = "用户手机号信息不符合标准,手机号为:".(!$userMobile?"空":$userMobile);
			return false;
		}

		$smsUid = "czc0927";
		$smsPwd = "czc092709";
		$sms = new ThirdParty_Sms( $smsUid, $smsPwd );

		$contentParam = array( 'code'=>rand(1000,9999) );
		$template = '100006';
		$result = $sms->send($userMobile, $contentParam, $template);
		if($result['stat']=='100') {
			/**
			 * 成功则记录,用于日后对账
			 */
			$query = $this->_db->prepare("insert into `sms_record` (`uid`,`contents`,`template`) VALUES ( ?, ?, ? )");
			$ret = $query->execute( array($uid, json_encode($contentParam), $template) );
			if( !$ret ){
				/**
				 * TODO 应该返回true还是false,有待商榷
				 */
				$this->errno = -4006;
				$this->errmsg = '消息发送成功,但发送记录失败。';
				return false;
			}
			return true;
		} else {
			$this->errno = -4005;
			$this->errmsg = '发送失败:'.$result['stat'].'('.$result['message'].')';
			return false;
		}
	}

}

  模板文件:

  

<?php
/**
 * 基于SMS.cn官方PHPsdk改写的SMS短信接口类
 */

class ThirdParty_Sms{
	/**
	* SMSAPI请求地址
	*/
	const API_URL = 'http://api.sms.cn/sms/';

	/**
	* 接口账号
	* 
	* @var string
	*/
	protected $uid;

	/**
	* 接口密码
	* 
	* @var string
	* @link http://sms.sms.cn/ 请到此处(短信设置->接口密码)获取
	*/
	protected $pwd;

	/**
	* sms api请求地址
	* @var string
	*/
	protected $apiURL;


	/**
	* 短信发送请求参数
	* @var string
	*/
	protected $smsParams;

	/**
	* 接口返回信息
	* @var string
	*/
    protected $resultMsg;

	/**
	* 接口返回信息格式
	* @var string
	*/
	protected $format;

	/**
	* 构造方法
	* 
	* @param string $uid 接口账号
	* @param string $pwd 接口密码
	*/
    public function __construct($uid = '', $pwd = '')
    {
		//用户和密码可直接写在类里
		$def_uid = '';
		$def_pwd = '';
        $this->uid	= $uid ?: $def_uid;
        $this->pwd	= $pwd ?: $def_pwd;
        $this->apiURL = self::API_URL;
		$this->format = 'json';
    }
	/**
	* SMS公共参数
	* @return array 
	*/
    protected function publicParams()
    {
        return array(
            'uid'		=> $this->uid,
            'pwd'		=> md5($this->pwd.$this->uid),
            'format'	=> $this->format,
        );
    }
	/**
	* 发送变量模板短信
	*
	* @param string $mobile 手机号码
	* @param string $content 短信内容参数
	* @param string $template 短信模板ID
	* @return array
	*/
	public function send($mobile, $contentParam,$template='') {
		//短信发送参数
		$this->smsParams = array(
			'ac'		=> 'send',
			'mobile'	=> $mobile,
			'content'	=> $this->array_to_json($contentParam),
			'template'	=> $template
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}

	/**
	* 发送全文模板短信
	*
	* @param string $mobile 手机号码
	* @param string $content 短信内容
	* @return array
	*/
	public function sendAll($mobile, $content) {
		//短信发送参数
		$this->smsParams = array(
			'ac'		=> 'send',
			'mobile'	=> $mobile,
			'content'	=> $content,
		);
		$this->resultMsg = $this->request();

		return $this->json_to_array($this->resultMsg, true);
	}

	/**
	* 取剩余短信条数
	*
	* @return array
	*/
	public function getNumber() {
		//参数
		$this->smsParams = array(
			'ac'		=> 'number',
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}


	/**
	* 获取发送状态
	*
	* @return array
	*/
	public function getStatus() {
		//参数
		$this->smsParams = array(
			'ac'		=> 'status',
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}
	/**
	* 接收上行短信(回复)
	*
	* @return array
	*/
	public function getReply() {
		//参数
		$this->smsParams = array(
			'ac'		=> 'reply',
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}
	/**
	* 取已发送总条数
	*
	* @return array
	*/
	public function getSendTotal() {
		//参数
		$this->smsParams = array(
			'ac'		=> 'number',
			'cmd'		=> 'send',
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}

	/**
	* 取发送记录
	*
	* @return array
	*/
	public function getQuery() {
		//参数
		$this->smsParams = array(
			'ac'		=> 'query',
		);
		$this->resultMsg = $this->request();
		return $this->json_to_array($this->resultMsg, true);
	}

	/**
	* 发送HTTP请求
	* @return string
	*/
	private function request()
	{
		$params = array_merge($this->publicParams(),$this->smsParams);
		if( function_exists('curl_init') )
		{
			return $this->curl_request($this->apiURL,$params);
		}
		else
		{
			return $this->file_get_request($this->apiURL,$params);
		}
	}
	/**
	* 通过CURL发送HTTP请求
	* @param string $url		 //请求URL
	* @param array $postFields //请求参数 
	* @return string
	*/
	private function curl_request($url,$postFields){
		$postFields = http_build_query($postFields);
		//echo $url.'?'.$postFields;
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields );
		$result = curl_exec ( $ch );
		curl_close ( $ch );
		return $result;
	}
	/**
	* 通过file_get_contents发送HTTP请求
	* @param string $url  //请求URL
	* @param array $postFields //请求参数 
	* @return string
	*/
	private function file_get_request($url,$postFields)
	{
		$post='';
		while (list($k,$v) = each($postFields)) 
		{
			$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
		}
		return file_get_contents($url.'?'.$post);
	}
	/**
	* 获取当前HTTP请返回信息
	* @return string
	*/
	public function getResult()
	{
		$this->resultMsg;
	}
	/**
	* 获取随机位数数字
	* @param  integer $len 长度
	* @return string       
	*/
	public function randNumber($len = 6)
	{
		$chars = str_repeat('0123456789', 10);
		$chars = str_shuffle($chars);
		$str   = substr($chars, 0, $len);
		return $str;
	}

	//把数组转json字符串
	function array_to_json($p)
	{
		return urldecode(json_encode($this->json_urlencode($p)));
	}
	//url转码
	function json_urlencode($p)
	{
		if( is_array($p) )
		{
			foreach( $p as $key => $value )$p[$key] = $this->json_urlencode($value);
		}
		else
		{
			$p = urlencode($p);
		}
		return $p;
	}

	//把json字符串转数组
	function json_to_array($p)
	{
		if( mb_detect_encoding($p,array('ASCII','UTF-8','GB2312','GBK')) != 'UTF-8' )
		{
			$p = iconv('GBK','UTF-8',$p);
		}
		return json_decode($p, true);
	}
}

?>

  

posted @ 2017-09-02 13:37  czcColud  阅读(254)  评论(0)    收藏  举报