О сервисе Тарифы Требования Операторы Демо





C#

Скачать листинг

                                                                     
                                                                     
                                                                     
                                             
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;

public class SiteSMS
{
    private const string username = "username";

    private const string password = "password";

    private const string jsonurl = "http://api.avisosms.ru/sms/json/";

    public enum Action { get_balance, send_message, get_message_state }

    /// <summary>
    /// Sends MT SMS
    /// </summary>
    /// <param name="to">destination phone number</param>
    /// <param name="from">alphanumeric sender (up to 11 chars)</param>
    /// <param name="text">message (70 unicode chars, if more gateway will split text into message parts 
    ///  67 characters each)</param>
/// <param name="flash">flash sms - always false and is ignored in this implementation</param> /// <returns>unique message id</returns> public static string AvisoSMS(string to, string from, string text, bool flash) { var parameters = new Dictionary<string, string> { { "from", from }, { "to", to }, { "text", text } }; var request = JSONCommand(Action.send_message, parameters); var results = JSONRequest(jsonurl, request); var result = JSONResult(results); if (result == null || !result.ContainsKey("messageId")) { return string.Empty; } return result["messageId"]; } /// <summary> /// Check message status by message id (result of AvisoSMS function). /// Possible statuses are: /// Enqueued — temporary status /// Sending — temporary status /// Delivered_To_Gateway — temporary status /// Sent — temporary status /// Delivered_To_Recipient /// Error_Invalid_Destination_Address /// Error_Invalid_Source_Address /// Error_Incompatible_Destination /// Error_Rejected /// Error_Expired /// Unknown /// </summary> /// <param name="messageID">MT message id</param> /// <returns>message status</returns> public static string AvisoStatus(string messageID) { var parameters = new Dictionary<string, string> { { "messageID", messageID } }; var request = JSONCommand(Action.get_message_state, parameters); var results = JSONRequest(jsonurl, request); var result = JSONResult(results); if (result == null || !result.ContainsKey("messageState")) { return string.Empty; } return result["messageState"]; } /// <summary> /// Check balance of the account /// </summary> /// <returns>balance in RUR</returns> public static string AvisoBalance() { var request = JSONCommand(Action.get_balance, null); var results = JSONRequest(jsonurl, request); var result = JSONResult(results); if (result == null || !result.ContainsKey("balance")) { return string.Empty; } return result["balance"]; } /// <summary> /// Parse Action as JSON object for request /// </summary> /// <param name="action">action type - enum</param> /// <param name="parameters">optional value - additional parameters for the action</param> /// <returns>JSON formated string</returns> public static Dictionary<string, string> AvisoSMS(string to, string from, string text, string link, bool flash)

  {

        Dictionary<string, string> parameters = new Dictionary<string, string>();

        parameters.Add("from", from);

        parameters.Add("to", to);

        parameters.Add("text", text);

        string request = JSONCommand(Action.send_message, parameters);

        Utils.Write2Log("AvisoSMS request: " + request, "aviso");

        string results = Utils.MakeWebRequest(jsonurl, request, null);

        Utils.Write2Log("AvisoSMS response: " + results, "aviso");

        Dictionary<string, string> result = JSONResult(results);

        if (!Utils.exists(result))

            result = new Dictionary<string, string>();

        result.Add("raw", request);

        return result;

    }

    public static string JSONCommand(Action action, Dictionary<string, string> parameters)

    {

        string names_values = String.Empty;

        // format additional parameters

        switch (action)

        {

            case Action.send_message:

                if (parameters != null && parameters.ContainsKey("from") && parameters.ContainsKey("to") && parameters.ContainsKey("text"))

                    names_values = string.Format(", 'destination_address': '{0}', 'message': '{1}', 'source_address': '{2}', flash:'0'", parameters["to"], parameters["text"], parameters["to"]);

                break;

            case Action.get_message_state:

                if (parameters != null && parameters.ContainsKey("messageId"))

                    names_values = string.Format(", 'messageID': '{0}'", parameters["messageId"]);

                break;

        }

        // globaly required parameters

        return string.Format(@"{0}'username': '{1}', 'password': '{2}', 'request_type': '{3}'{4}{5}", "{", avisousername, avisopassword, action.ToString(), names_values, "}");

    }

    public static string MakeWebRequest(string url, string data, string type)

    {

        try

        {

            HttpWebRequest oHttpRequest = (HttpWebRequest)WebRequest.Create(url);

            oHttpRequest.Headers.Clear();

            oHttpRequest.KeepAlive = false;

            oHttpRequest.Method = "GET";

            if (!string.IsNullOrEmpty(data))

            {

                // Set values for the request back

                oHttpRequest.Method = "POST";

                oHttpRequest.ContentType = type ?? "application/x-www-form-urlencoded";

                byte[] dataarr = Encoding.UTF8.GetBytes(data);

                oHttpRequest.ContentLength = dataarr.Length;

                using (Stream stream = oHttpRequest.GetRequestStream())

                    for (int i = 0, lim = dataarr.Length; i < lim; i++)

                        stream.WriteByte(dataarr[i]);

            }

            HttpWebResponse oHttpResponse = (HttpWebResponse)oHttpRequest.GetResponse();

            //check status code

            if (oHttpResponse.StatusCode == HttpStatusCode.OK)

                data = new StreamReader(oHttpResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();

        }

        catch (Exception ex)

        {

            return String.Format("null {0} -> {1}", ex.Source, ex.Message);

        }

        return data ?? "null";

    }

Colored with dumpz.org

 

PHPPython,   Java,   Ruby on Rails,   Perl,   Delphi,   .NETC#,