Nada encontrado

SMS promocional – exemplos

Exemplos de utilização de Simple promotional. A Simple API recebe os destinatários numa única string separada por ponto e vírgula - os grupos da agenda de contactos, os administradores e os canais alternativos só estão disponíveis na Advanced API.

Vários destinatários

number é uma string de números de telefone separados por ponto e vírgula; todos recebem o mesmo texto.

POST /api/1.0/simple/promotional HTTP/1.1 Host: portal.bulkgate.com Content-Type: application/json { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Os saldos de primavera arrancam hoje, até 50 % de desconto." }

Remetente próprio e Unicode

gText envia a campanha a partir de um remetente de texto registado. Ative unicode sempre que o texto contiver caracteres fora do alfabeto de 7 bits - isso reduz a mensagem a 268 caracteres por parte.

POST /api/1.0/simple/promotional HTTP/1.1 Host: portal.bulkgate.com Content-Type: application/json { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Os saldos de primavera acabaram de arrancar.", "sender_id": "gText", "sender_id_value": "BulkGate", "unicode": true }

Números locais e campanha agendada

country permite indicar números sem o indicativo internacional. schedule aceita ISO 8601 ou unix timestamp.

POST /api/1.0/simple/promotional HTTP/1.1 Host: portal.bulkgate.com Content-Type: application/json { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "777777777;606606234", "country": "cz", "text": "Os saldos de primavera arrancam hoje, até 50 % de desconto.", "schedule": "2026-09-14T09:00:00+02:00" }

Proteção contra duplicados e etiqueta

same_text descarta uma mensagem com texto idêntico para um número que já a recebeu, same_number descarta qualquer outra mensagem para o mesmo número. tag etiqueta a campanha para posterior pesquisa.

POST /api/1.0/simple/promotional HTTP/1.1 Host: portal.bulkgate.com Content-Type: application/json { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Os saldos de primavera arrancam hoje, até 50 % de desconto.", "duplicates_check": "same_number", "tag": "spring-sale" }

A resposta está descrita na especificação.

Exemplos de código

Abaixo encontra exemplos de implementação da Simple API para enviar mensagens SMS promocionais com um ID do remetente de texto em diferentes linguagens de programação:

O significado de cada parâmetro está descrito na especificação; os pedidos simples encontram-se nos métodos de pedido.

PHP

php.net

$context = stream_context_create(['http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode([ 'application_id' => 451, 'application_token' => 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', 'number' => implode(';', [ '420777777777', '420606606234', '420601992992' ]), 'text' => 'Texto da mensagem', 'sender_id' => 'gText', 'sender_id_value' => 'BulkGate', ], JSON_THROW_ON_ERROR), 'timeout' => 30, 'ignore_errors' => true, ]]); $body = file_get_contents('https://portal.bulkgate.com/api/1.0/simple/promotional', false, $context); if ($body === false) { throw new RuntimeException('A API BulkGate não respondeu.'); } $response = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (isset($response['error'])) { throw new RuntimeException("BulkGate: {$response['error']} ({$response['type']})"); } foreach ($response['data']['response'] as $message) { echo $message['status'] === 'error' ? "{$message['number']}: {$message['error']}\n" : "{$message['number']}: {$message['status']} ({$message['sms_id']})\n"; } var_dump($response['data']['total']['status']);

PHP cURL

php.net/curl

$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => 'https://portal.bulkgate.com/api/1.0/simple/promotional', CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode([ 'application_id' => 451, 'application_token' => 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', 'number' => implode(';', [ '420777777777', '420606606234', '420601992992' ]), 'text' => 'Texto da mensagem', 'sender_id' => 'gText', 'sender_id_value' => 'BulkGate', ], JSON_THROW_ON_ERROR), ]); $body = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); if ($body === false) { throw new RuntimeException('BulkGate: ' . curl_error($curl)); } $response = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if ($status !== 200) { throw new RuntimeException("BulkGate: {$response['error']} ({$response['type']})"); } foreach($response['data']['response'] as $message) { echo $message['status'] === 'error' ? "{$message['number']}: {$message['error']}\n" : "{$message['number']}: {$message['status']} ({$message['sms_id']})\n"; } var_dump($response['data']['total']['status']);

PHP Guzzle

docs.guzzlephp.org

// composer require guzzlehttp/guzzle use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; $client = new Client(['timeout' => 30, 'http_errors' => false]); try { $result = $client->post('https://portal.bulkgate.com/api/1.0/simple/promotional', ['json' => [ 'application_id' => 451, 'application_token' => 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', 'number' => implode(';', [ '420777777777', '420606606234', '420601992992' ]), 'text' => 'Texto da mensagem', 'sender_id' => 'gText', 'sender_id_value' => 'BulkGate', ]]); } catch (GuzzleException $e) { throw new RuntimeException('BulkGate: ' . $e->getMessage(), previous: $e); } $response = json_decode((string) $result->getBody(), true, flags: JSON_THROW_ON_ERROR); // http_errors => false: o erro da API reconhece-se pelo código de estado, o corpo contém a sua descrição. if ($result->getStatusCode() !== 200) { throw new RuntimeException("BulkGate: {$response['error']} ({$response['type']})"); } foreach ($response['data']['response'] as $message) { echo $message['status'] === 'error' ? "{$message['number']}: {$message['error']}\n" : "{$message['number']}: {$message['status']} ({$message['sms_id']})\n"; } var_dump($response['data']['total']['status']);

Go

go.dev

package main import ( "fmt" "strings" "net/http" "io/ioutil" ) func main() { url := "https://portal.bulkgate.com/api/1.0/simple/promotional" payload := strings.NewReader("{\"application_id\": 451, \"application_token\": \"NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj\", \"number\": \"420777777777;420606606234;420601992992\", \"text\": \"Mensagem\", \"sender_id\": \"gText\", \"sender_id_value\": \"BulkGate\"}") req, _ := http.NewRequest("POST", url, payload) 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)) }

Python

python.org

# pip install requests import requests response = requests.post('https://portal.bulkgate.com/api/1.0/simple/promotional', json={ 'application_id': 451, 'application_token': 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', 'number': '420777777777;420606606234;420601992992', 'text': 'Mensagem', 'sender_id': 'gText', 'sender_id_value': 'BulkGate', }, timeout=30) data = response.json() # Uma resposta de erro tem a forma {type, code, error, detail} — consulte a tabela de tipos de erros. if 'error' in data: raise RuntimeError(f"BulkGate: {data['error']} ({data['type']})") # Um envio em massa devolve um resultado para cada número separadamente. for message in data['data']['response']: if message['status'] == 'error': print(message['number'], message['error']) else: print(message['number'], message['status'], message['sms_id']) print('Resumo:', data['data']['total']['status'])

Node.js

nodejs.org

// O Node.js 18+ tem fetch disponível globalmente. O top-level await requer ESM (.mjs ou "type": "module"). const response = await fetch('https://portal.bulkgate.com/api/1.0/simple/promotional', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ application_id: 451, application_token: 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', number: '420777777777;420606606234;420601992992', text: 'Mensagem', sender_id: 'gText', sender_id_value: 'BulkGate', }), }); const data = await response.json(); // Uma resposta de erro tem a forma {type, code, error, detail} — consulte a tabela de tipos de erros. if (!response.ok) { throw new Error(`BulkGate: ${data.error} (${data.type})`); } // Um envio em massa devolve um resultado para cada número separadamente. for (const message of data.data.response) { console.log(message.status === 'error' ? `${message.number}: ${message.error}` : `${message.number}: ${message.status} (${message.sms_id})`); } console.log('Resumo:', data.data.total.status);

Java

java.net.http.HttpClient

import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://portal.bulkgate.com/api/1.0/simple/promotional")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(""" { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Mensagem", "sender_id": "gText", "sender_id_value": "BulkGate" }""")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body());

Kotlin

kotlinlang.org

import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse val payload = """ { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Mensagem", "sender_id": "gText", "sender_id_value": "BulkGate" } """.trimIndent() val request = HttpRequest.newBuilder() .uri(URI.create("https://portal.bulkgate.com/api/1.0/simple/promotional")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(payload)) .build() val response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()) println("${response.statusCode()} ${response.body()}")

C# .NET

learn.microsoft.com

using System.Net.Http; using System.Text; var payload = """ { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Mensagem", "sender_id": "gText", "sender_id_value": "BulkGate" } """; using var client = new HttpClient(); var response = await client.PostAsync( "https://portal.bulkgate.com/api/1.0/simple/promotional", new StringContent(payload, Encoding.UTF8, "application/json")); Console.WriteLine($"{(int) response.StatusCode} {await response.Content.ReadAsStringAsync()}");

C++ libcurl

curl.se/libcurl

#include <curl/curl.h> #include <iostream> #include <string> static size_t collect(char *data, size_t size, size_t nmemb, std::string *out) { out->append(data, size * nmemb); return size * nmemb; } int main() { const std::string payload = R"json( { "application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Mensagem", "sender_id": "gText", "sender_id_value": "BulkGate" } )json"; CURL *curl = curl_easy_init(); if (curl == nullptr) { std::cerr << "curl_easy_init failed\n"; return 1; } curl_slist *headers = curl_slist_append(nullptr, "Content-Type: application/json"); std::string body; curl_easy_setopt(curl, CURLOPT_URL, "https://portal.bulkgate.com/api/1.0/simple/promotional"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, collect); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body); const CURLcode result = curl_easy_perform(curl); long status = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status); curl_slist_free_all(headers); curl_easy_cleanup(curl); if (result != CURLE_OK) { std::cerr << curl_easy_strerror(result) << "\n"; return 1; } std::cout << status << " " << body << "\n"; return 0; }

Ruby

ruby-lang.org

require 'json' require 'net/http' uri = URI('https://portal.bulkgate.com/api/1.0/simple/promotional') response = Net::HTTP.post(uri, { 'application_id' => 451, 'application_token' => 'NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj', 'number' => '420777777777;420606606234;420601992992', 'text' => 'Mensagem', 'sender_id' => 'gText', 'sender_id_value' => 'BulkGate' }.to_json, 'Content-Type' => 'application/json') puts "#{response.code} #{response.body}"

Bash cURL

curl.se

curl --request POST \ --url https://portal.bulkgate.com/api/1.0/simple/promotional \ --header 'Content-Type: application/json' \ --data '{"application_id": 451, "application_token": "NKN02TWE6NfBkfl-your-secret-token-Wf05GaqLIWLW4aBj", "number": "420777777777;420606606234;420601992992", "text": "Mensagem", "sender_id": "gText", "sender_id_value": "BulkGate"}'
Esta página foi útil?