Client.php 2.13 KB
<?php

class YHMUtils_Sms_Client {
	
	/**
	 * 通过curl向SMS API发送数据
	 * @param string $project
	 * @param number $target	手机号,多个用   , 分隔
	 * @param array $message 	 如果为空,发送内容则为预设模板的内容
	 * @return array = array(
	 *                  'status' => bool	成功为true,失败为false
	 *                  'message' => '成功或者失败'
	 *                  )
	 */
	public static function Sms($project, $target, array $message=array(), $start_time=0, $end_time=0)
	{
		if (empty($project) || empty($target)) {
			$response = array(
					'status' => false,
					'message' => "项目或目标不能为空!"
			);
			return $response;
		}
	
		$string = json_encode($message);
		$data = array(
				'project' => $project,
				'target' => $target,
				'message' => $string,
				'start_time' => $start_time,
				'end_time' => $end_time
		);
		$token = self::makeToken($data);
		$data['token'] = $token;
		$api = Q_APPLICATION_ENV == 'release' ? 'api.open.yohobuy.com' : 'test.open.yohobuy.com';
	
		$data = http_build_query($data, '', '&');
		$url = 'http://' . $api . '/?method=Base.Sms.send&' . $data;
		$ch = curl_init();
	
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$jsonResult = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		$result = json_decode($jsonResult, true);
		if ($code != 200 || empty($result) || $result['code'] != 200) {
			$tip = empty($result['message']) ? '' : $result['message'];
			$response = array(
					'status' => false,
					'message' => "发送失败!{$tip}"
			);
			return $response;
		}
		return $response = array(
				'status' => true,
				'message' => "发送成功!"
		);
	}
	
	private static $key = 'sms-yohobuy';
	
	public static function makeToken(array $package)
	{
		$package['token'] = self::$key;
		ksort($package);
		reset($package);
		$packageList = array();
		foreach($package as $key => $val){
			$packageList[] = trim($key.'='.$val);
		}
		return strrev(strtolower(md5( implode('&',$packageList) )));
	}
	
}