Dmitry Yu Okunev лет назад: 8
Сommit
b264a99d55
4 измененных файлов с 239 добавлено и 0 удалено
  1. 3 0
      README.txt
  2. 63 0
      example.php
  3. 158 0
      lib/ssms_su.php
  4. 15 0
      sendsms.php

+ 3 - 0
README.txt

@@ -0,0 +1,3 @@
+Внимание!
+если Вы зарегистрированы на user.ssms.su, в своих скриптах необходимо обращатсья к API на домен api.ssms.su
+если Вы зарегистрированы на center.ssms.su, в своих скриптах необходимо обращатсья к API на домен api2.ssms.su

+ 63 - 0
example.php

@@ -0,0 +1,63 @@
+<?php
+ 
+require_once "lib/ssms_su.php";
+ 
+$email = "user@example.com";
+$password = "XxXXXXXXXXXXXXXXXX";
+$phone = "7xxxYYYyyzz";
+$phones = array("7xxxYYYyyzz", "7uuuWWWllkk");
+$dlr_url = "http://example.com/test.php?state=%d&phone=%p";
+$dlr_mask = 35;
+ 
+ 
+// Пример 1 - если необходимо отправить одно SMS сообщение, можно совместить
+// аутентификацию с отправкой сообщения.
+//--------------------------------------------------------------------
+ 
+// Отправляется SMS сообщение, указывается дополнительный параметр - имя
+// отправителя (полный список дополнительных параметров метода push_msg
+// можно найти в описании API, например, test=1 - режим отладки).
+ 
+var_dump(
+smsapi_push_msg_nologin($email, $password, $phone, "Hello world =)!", array("sender_name"=>"user"))
+);
+ 
+ 
+ 
+// Пример 2 - если необходимо отправить несколько сообщений, следует
+// аутентифицироваться один раз и после пользоваться Cookie с сессией.
+//--------------------------------------------------------------------
+$verb = function($ret) {
+    return is_null($ret)?"связи с API":$ret[0];
+};
+ 
+// Представляемся системе, получаем id сессии
+$ret = smsapi_login($email, $password);
+if(is_null($ret) || $ret[0] != 0){
+    die("Невозможно представиться системе: ошибка ".$verb($ret)."\n");
+}
+ 
+$cookie = $ret[1];
+ 
+// Отправляем сообщения, используя Cookie для аутентификации.
+// В качестве дополнительного параметра указывается шаблон URL для
+// оповещения о статусе сообщения и маска - фильтр статусов.
+// 35 = 0b100011, значит были запрошены статусы 1,2 и 32. При обновлении
+// статуса сообщения в нашей системе, если новый статус - один из
+// указанных, будет совершен HTTP запрос с URL, в котором %d заменён на
+// статус, а %p - на телефон.
+ 
+foreach($phones as $P){
+    $ret = smsapi_push_msg($cookie, $P, "Helo world! =)", array(
+    "dlr_url" =>$dlr_url,
+    "dlr_mask" => $dlr_mask
+    )
+    );
+    if(is_null($ret) || $ret[0] != 0){
+        die("Невозможно отправить сообщение: ошибка ".$verb($ret)."\n");
+    }
+}
+ 
+echo "OK\n";
+ 
+?>

+ 158 - 0
lib/ssms_su.php

@@ -0,0 +1,158 @@
+<?php
+
+/**
+ * Sends request to API
+ * @param $request - associative array to pass to API, "format" 
+ * key will be overridden
+ * @param $cookie - cookies string to be passed
+ * @return
+ * * NULL - communication to API failed
+ * * ($err_code, $data) if response was OK, $data is an associative
+ * array, $err_code is an error numeric code 
+ */
+
+function _smsapi_communicate($request, $cookie=NULL){
+	$request['format'] = "json";
+	$curl = curl_init();
+	curl_setopt($curl, CURLOPT_URL, "http://api2.ssms.su/");
+	curl_setopt($curl, CURLOPT_POST, True);
+	curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
+	curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
+	if(!is_null($cookie)){
+		curl_setopt($curl, CURLOPT_COOKIE, $cookie);
+	}
+	$data = curl_exec($curl);
+	curl_close($curl);
+	if($data === False){
+		return NULL;
+	}
+	$js = json_decode($data, $assoc=True);
+	if(!isset($js['response'])) return NULL;
+	$rs = &$js['response'];
+	if(!isset($rs['msg'])) return NULL;
+	$msg = &$rs['msg'];
+	if(!isset($msg['err_code'])) return NULL;
+	$ec = intval($msg['err_code']);
+	if(!isset($rs['data'])){ $data = NULL; }else{ $data = $rs['data']; }
+	return array($ec, $data);
+}
+
+
+/**
+ * Sends a message via ssms_su api, combining authenticating and sending
+ * message in one request.
+ * @param $email, $passwrod - login info
+ * @param $phone - recipient phone number in international format (like 7xxxyyyzzzz)
+ * @param $text - message text, ASCII or UTF-8.
+ * @param $params - additional parameters as key => value array, see API doc.
+ * @return 
+ * * NULL if API communication went a wrong way
+ * * array(>0) - if an error has occurred (see API error codes)
+ * * array(0, n_raw_sms, credits) - number of SMS parts in message and 
+ * price for a single part
+ */
+function smsapi_push_msg_nologin($email, $password, $phone, $text, $params = NULL){
+	$req = array(
+		"method" => "push_msg",
+		"api_v"=>"1.1",
+		"email"=>$email,
+		"password"=>$password,
+		"phone"=>$phone,
+		"text"=>$text);
+	if(!is_null($params)){
+		$req = array_merge($req, $params);
+	}
+	$resp = _smsapi_communicate($req);
+	if(is_null($resp)){
+		// Broken API request
+		return NULL;
+		return "";
+	}
+	$ec = $resp[0];
+	if($ec != 0){
+		return array($ec);
+		return "";
+	}
+	if(!isset($resp[1]['n_raw_sms']) OR !isset($resp[1]['credits'])){
+		return NULL; // No such fields in response while expected
+		return "";
+	}
+	$n_raw_sms = $resp[1]['n_raw_sms'];
+	$credits = $resp[1]['credits'];
+	return array(0, $n_raw_sms, $credits);
+	return "";
+}
+
+/**
+ * Logs in API, producing a session ID to be sent back in session 
+ * cookie.
+ * @param $email - user's email
+ * @param $password - user's password
+ * @return 
+ * * array(0,$cookie) - if OK, where $cookie is a string 
+ * "sid=${session_id}" to be passed to cURL
+ * * array(>0) - if API returned an error code (included)
+ * * NULL is API communication failed
+ */
+function smsapi_login($email, $password){
+	$req = array("method" => "login",
+		"format" => "json",
+		"email" => $email,
+		"password" => $password);
+	$ret=_smsapi_communicate($req);
+	if(is_null($ret)){
+		return NULL;
+	}
+	$ec = $ret[0];
+	if($ec != 0){
+		return array($ec);
+	}
+	if( ! isset($ret[1]['sid'])){
+		return NULL;
+	}
+	$usid = urlencode($ret[1]['sid']);
+	$cookie = "sid=$usid";
+	return array(0,$cookie);
+}
+
+
+/**
+ * Sends message via API, using previously obtained cookie to 
+ * authenticate.
+ * @param $cookie - string, returned by smsapi_login, "sid=..."
+ * @param $phone - target phone
+ * @param $text - message text, ASCII or UTF-8
+ * @param params - dictionary of optional parameters, see API 
+ * documentation of push_msg method
+ * @return 
+ * * NULL if communication to API failed
+ * * array(>0) if an error occured (see API error codes)
+ * * array(0, n_raw_sms, credits) - number of SMS parts in message and 
+ * price for a single part
+ */
+function smsapi_push_msg($cookie, $phone, $text, $params = NULL){
+	$req = array(
+		"method" => "push_msg",
+		"api_v"=>"1.1",
+		"phone"=>$phone,
+		"text"=>$text);
+	if(!is_null($params)){
+		$req = array_merge($req, $params);
+	}
+	$resp = _smsapi_communicate($req, $cookie);
+	if(is_null($resp)){
+		// Broken API request
+		return NULL;
+	}
+	$ec = $resp[0];
+	if($ec != 0){
+		return array($ec);
+	}
+	if(!isset($resp[1]['n_raw_sms']) OR !isset($resp[1]['credits'])){
+		return NULL; // No such fields in response while expected
+	}
+	$n_raw_sms = $resp[1]['n_raw_sms'];
+	$credits = $resp[1]['credits'];
+	return array(0, $n_raw_sms, $credits);
+}
+?>

+ 15 - 0
sendsms.php

@@ -0,0 +1,15 @@
+#!/usr/bin/php
+<?php
+require_once "lib/ssms_su.php";
+
+if (count($argv) < 6) {
+	print 'Not enough arguments, syntax: '.$argv[0].' login password destination message sender_name'."\n";
+	exit(7);
+}
+
+$rc = reset(smsapi_push_msg_nologin($argv[1], $argv[2], $argv[3], $argv[4], array("sender_name"=> $argv[5])));
+
+print $rc."\n";
+exit($rc);
+
+?>