Отправка сообщений

* v1 — скоуп присваивается каждой CRM и сервису индивидуально, запросите свое персональное значение v1 и используйте в коде его, отправляя запросы.

Параметры
Пример успешного результата HTTP-код — 200.
{
  "delivery": {
    "sender_name": "PUSHSMS",
    "phone": "79681234567",
    "id": 26,
    "status_id": 2,
    "status_description": "Принято",
    "sum": "2.45",
    "total_sms": 1,
    "traffic_category": 0,
    "external_id": "132_id",
    "utm_mark": "Qwerty213",
    "dispatch_routing": ["sms"],
    "scheduled_at": "2021-12-12T21:30:00Z",
    "priority": "medium"
  },
  "callback_url": "https://pushsms.ru/callback_url",
  "meta": {
    "status": "success",
    "code": 200

}
Параметры ответа

Параметры ответа

Ошибка, HTTP-код — 422. JSON:
{
  "meta": {
    "status": "fail",
    "code": 422,
    "message": "error message",
    "error_id": 33,
    "errors": {"base": ["errors"]}
  }
}
Пример:
curl --location --request POST 'https://api.pushsms.ru/api/v1/delivery?text=textsms&phone=71233456789&scheduled_at=2021-12-12 21:30:00' \
--header 'Authorization: Bearer {your token}'
Примеры кода:
Ruby
NET:PHP
require 'uri'
require 'net/http'
require 'openssl'
require 'json'

url = URI('https://api.pushsms.ru/api/v1/delivery')

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # используйте OpenSSL::SSL::VERIFY_PEER в production среде

request = Net::HTTP::Post.new(url)
request['authorization'] = 'Bearer yourtoken123456'
request['content-type'] = 'application/json'
request.body = { text: 'hello world', phone: '71237654321' }.to_json

response = http.request(request)
puts response.read_body
PHP
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.pushsms.ru/api/v1/delivery",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"text\":\"hello world\",\"phone\":\"71237654321\"}",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer yourtoken123456",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
Node JS
var request = require("request");

var options = {
  method: "POST",
  url: "https://api.pushsms.ru/api/v1/delivery",
  headers: { authorization: "Bearer yourtoken123456", "content-type": "application/json" },
  body: { text: "hello world", phone: "71237654321" },
  json: true,
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});


import fetch from 'node-fetch';

const url = 'https://api.pushsms.ru/api/v1/delivery';
const body = { text: 'hello world', phone: '71237654321' };
const headers = {
  authorization: 'Bearer yourtoken123456',
  'content-type': 'application/json',
};

const response = await fetch(url, {
  method: 'post',
  body: JSON.stringify(body),
  headers: headers,
});
const data = await response.json();

console.log(data);
Python
import http.client

conn = http.client.HTTPSConnection("api.pushsms.ru")

payload = "{\"text\":\"hello world\",\"phone\":\"71237654321\"}"
headers = { 'authorization': "Bearer yourtoken123456",
            'content-type': 'application/json'
}
conn.request("POST", "/api/v1/delivery", payload, headers)

res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
import requests

url = "https://api.pushsms.ru/api/v1/delivery"

payload = "{\"text\":\"hello world\",\"phone\":\"71237654321\"}"
headers = {
  'authorization': 'Bearer yourtoken123456',
  'content-type': 'application/json'
}

response = requests.request("POST", url, data = payload, headers = headers)
print(response.text)
Java
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;

// .....

HttpResponse<JsonNode> response = Unirest.post("https://api.pushsms.ru/api/v1/delivery")
  .header("Content-Type", "application/json")
  .header("Authorization", "Bearer yourtoken123456")
  .body("{\"text\":\"hello world\",\"phone\":\"71237654321\"}")
  .asJson();

System.out.println(response.getBody());
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

// .....

String data = "{\"text\":\"hello world\",\"phone\":\"71237654321\"}";
MediaType jsonMediaType = MediaType.get("application/json; charset=utf-8");

RequestBody body = RequestBody.create(data, jsonMediaType);
String url = "https://api.pushsms.ru/api/v1/delivery";
String accessToken = "yourtoken123456";

Request request = new Request.Builder()
  .url(url)
  .post(body)
  .addHeader("authorization", "Bearer " + accessToken)
  .build();

OkHttpClient client = new OkHttpClient();

try (Response response = client.newCall(request).execute()) {
  System.out.println(response.body().string());
} catch (IOException e) {
  e.printStackTrace();
}
Java
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {
  url := "https://api.pushsms.ru/api/v1/delivery"
  payload := strings.NewReader("{\"text\":\"hello world\",\"phone\":\"71237654321\"}")

  req, _ := http.NewRequest("POST", url, payload)
  req.Header.Add("authorization", "Bearer yourtoken123456")
  req.Header.Add("content-type", "application/json")

  res, _ := http.DefaultClient.Do(req)
  defer res.Body.Close()

  body, _ := ioutil.ReadAll(res.Body)
  fmt.Println(string(body))
}
C##
using System;
using RestSharp;
using System.Threading;
using RestSharp.Authenticators.OAuth2;

// .....

var access_token = "yourtoken123456";

var client = new RestClient("https://api.pushsms.ru/api/v1/");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(access_token, "Bearer");

var request_params = new
{
  text = "hello world",
  phone = "71237654321"
};

var request = new RestRequest("delivery").AddJsonBody(request_params);

try
{
  var response = await client.PostAsync(request);
  Console.WriteLine(response.Content);
}
catch(Exception e) {
  Console.WriteLine("{0} Exception caught.", e);
Swift
import Foundation

let session = URLSession.shared
let url = URL(string: "https://api.pushsms.ru/api/v1/delivery")!
let headers = [
  "Authorization": "Bearer yourtoken123456",
  "Content-Type": "application/json"
]
let parameters = [
  "text": "hello world",
  "phone": "71237654321"
]

var request = URLRequest(
  url: url,
  cachePolicy: .reloadIgnoringLocalCacheData
)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])

let dataTask = session.dataTask(
  with: request as URLRequest,
  completionHandler: { data, _response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }

    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print(dataString)
    }
  }
)

dataTask.resume()
Kotlin
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.*
import kotlinx.serialization.Serializable

@Serializable
data class DeliveryParams(val text: String, val phone: String)

fun main() = runBlocking {
  val url = "https://api.pushsms.ru/api/v1/delivery"
  val token = "yourtoken123456"
  val parameters = DeliveryParams("hello world", "71237654321")

  val client = HttpClient(CIO) {
    install(ContentNegotiation) {
      json()
    }
  }

  val httpResponse = client.post(url) {
    contentType(ContentType.Application.Json)
    bearerAuth(token)
    setBody(parameters)
  }

  val stringBody: String = httpResponse.body()
  println(stringBody)
}
Elixir
params = %{text: "hello world", phone: "71237654321"}
url = "https://api.pushsms.ru/api/v1/delivery"
token = "yourtoken123456"
request_headers = [
  {"Content-Type", "application/json"},
  {"Authorization", "Bearer #{token}"}
]

case HTTPoison.post(url, Jason.encode!(params), request_headers) do
  {:ok, %HTTPoison.Response{status_code: 200, body: resp_body}} ->
    IO.inspect(Jason.decode!(resp_body))

  {:ok, %HTTPoison.Response{body: resp_body}} ->
    IO.puts("Request error: #{resp_body}")

  {:error, %HTTPoison.Error{reason: reason}} ->
    IO.puts("Connection error: #{reason}")
end
Clojure
(require '[clj-http.client :as client])

(defn generate-options [params-map]
  {:headers {:authorization "Bearer yourtoken123456"}
   :content-type :json
   :as :json
   :form-params params-map})

(defn create-delivery [params-map]
  (try
    (-> "https://api.pushsms.ru/api/v1/delivery"
        (client/post (generate-options params-map))
        (get :body))
    (catch Exception e {:error (ex-message e) :data (ex-data e)})))

(println (create-delivery {:text "hello world" :phone "71237654321"}))