Sample Code
Sample PHP Code for sending single message
<?php
$request =""; //initialise the request variable $param[method]= "sendMessage";
$param[send_to] = "919xxxxxxxxx"; $param[msg] = "Hello"; $param[userid] = "xxxxxxxx"; $param[password] =
"xxxxxxxx"; $param[v] = "1.1";
$param[msg_type] = "TEXT"; //Can be "FLASH”/"UNICODE_TEXT"/”BINARY” $param[auth_scheme] = "PLAIN";
//Have to URL encode the values foreach($param as $key=>$val) {
$request.= $key."=".urlencode($val); //we have to urlencode the values $request.= "&";
//append the ampersand (&) sign after each parameter/value pair
}
$request = substr($request, 0, strlen($request)-1); //remove final (&) sign from the request
$url = "https://enterprise.smsgupshup.com/GatewayAPI/rest?".$request;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $curl_scraped_page = curl_exec($ch); curl_close($ch);
echo $curl_scraped_page;
?>
Sample JAVA Code for sending a single message
Import java.io.BufferedReader;
Import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date; public class GatewayAPITest {
public static void main(String[] args){ try {
Date mydate = new Date(System.currentTimeMillis());
String data = "";
data += "method=sendMessage";
data += "&userid=xxxxxxxx"; // your loginId data += "&password=" +
URLEncoder.encode("xxxxxx", "UTF-8"); // your password
data += "&msg=" + URLEncoder.encode("GUPSHUP
message" + mydate.toString(), "UTF-8");
data += "&send_to=" +
URLEncoder.encode("9xxxxxxxxx", "UTF-8"); // a valid 10 digit phone no.
data += "&v=1.1" ;
data += "&msg_type=TEXT"; // Can by "FLASH" or
"UNICODE_TEXT" or “BINARY”
data += "&auth_scheme=PLAIN";
URL url = new URL("https://enterprise.smsgupshup.com/GatewayAPI/rest?" + data);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer(); while ((line = rd.readLine()) != null){
buffer.append(line).append("\n");
}
System.out.println(buffer.toString());
rd.close();
conn.disconnect();
}
catch(Exception e){ e.printStackTrace();
}
}
}
Sample C# Code for sending a single message
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO; namespace GupshupAPI{
class Program{ static void Main(string[] args){ string result = ""; WebRequest request = null;
HttpWebResponse response = null; try{
String sendToPhoneNumber = "919xxxxxxxxx"; String userid = "xxxxxxxxx";
String passwd = "xxxxx"; String url =
"https://enterprise.smsgupshup.com/GatewayAPI/rest?method=sendMessage&send_to=" + sendToPhoneNumber +
"&msg=hello&userid=" + userid +"&password=" + passwd + "&v=1.1"&msg_type=TEXT&auth_scheme=PLAIN";
request = WebRequest.Create(url);
//in case u work behind proxy, uncomment the commented code and provide correct details
/*WebProxy proxy = new WebProxy("http://proxy:80/",true); proxy.Credentials = new
NetworkCredential("userId","password", "Domain"); request.Proxy = proxy;*/
// Send the 'HttpWebRequest' and wait for response. response = (HttpWebResponse)request.GetResponse(); Stream
stream = response.GetResponseStream();
Encoding ec = System.Text.Encoding.GetEncoding("utf-8"); StreamReader reader = new
System.IO.StreamReader(stream, ec);
result = reader.ReadToEnd(); Console.WriteLine(result);
reader.Close();
stream.Close();
}
catch (Exception exp){ Console.WriteLine(exp.ToString());
}
finally{
if(response != null) response.Close();
}
}
}
}
Sample Ruby Code
You can access the GupShup HTTP API by using the net/http standard Ruby library. But the plugin provided by SMS
GupShup is much easier than the standard one. The plugin is available at http://github.com/nileshtrivedi/gupshup.
Install the plugin as sudo gem sources – a http://gems.github.com sudo gem install nileshtrivedi-gupshup
To override some of the API parameters, pass an options hash as below:
gup.send_text_message("hello","919xxxxxxxxx", {:mask => "TESTING"}) require 'rubygems'
require 'gupshup'
gup = Gupshup::Enterprise.new("XXXXXX","your_password") gup.send_text_message("hello","919xxxxxxxxx")
gup.send_flash_message('sms message text',"919xxxxxxxxx")
gup.send_unicode_message("\xE0\xA4\x97\xE0\xA4\xAA\xE0\xA4\xB6\xE0\xA4\xAA","91 9xxxxxxxxx")
Sample HTML code for File Upload
<html>
<head></head>
<body>
<form name="xlsUploadForm" action="https://enterprise.smsgupshup.com/GatewayAPI/rest" method="post"
enctype="multipart/form-data"><input type="text" name="method" id="method" value="xlsUpload" /> <input type="text" name="userid" id="userid"
value=<login-id> /> <input type="text" name="password" id="password" value=<urlencodedpassword> />
<input type="text" name="v" id="version" value="1.1" /> <input type="text" name="auth_scheme" id="auth_scheme"
value=”PLAIN” />
<input type="file" name="xlsFile" /> <select name="filetype" >
<option value="xls">xls</option> <option value="csv">csv</option> <option value="zip">zip</option>
</select>
<input value="Send Message" type="submit" /> </form>
</body>
</html>
Sample Java code for File Upload
package com.webaroo.gatewayapi.v1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import com.mysql.jdbc.log.LogFactory;
public class TestClient1 {
public static void main(String[] args) throws HttpException, IOException {
try{
HttpClient client = new HttpClient(); PostMethod method = new
PostMethod("https://enterprise.smsgupshup.com/GatewayAPI/rest"); File f = new File("C:\\xlsUpload1.xls");
Part[] parts ={
new StringPart("method", "xlsUpload"), new StringPart("userid", "XXXXXXX"), new StringPart("password", "XXXXX"),
new StringPart("filetype", "xls"),
new StringPart("v", "1.1"),
new StringPart("auth_scheme", "PLAIN"), new FilePart(f.getName(), f)
};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
int statusCode = client.executeMethod(method); System.out.println(statusCode);
}
catch (Exception e){ e.printStackTrace();
}
}
}
Sample Ruby Code for File Upload
gup.bulk_file_upload("/home/myname/addressbook.csv")
Sample PHP Code for File Upload
<?php
/**
* Use a Gupshup Enterprise account to send messages.
* Supports setting time and mask for individual messages.
*
* @author Anshul <[email protected]>
*/
class EnterpriseSender{
public $id;
public $password;
/**
* Mask that would appear on receiver’s phone. For what can appear here,
* contact SMS GupShup Support as the mask needs to be set in the account
* before it can be used here.
* @var String
*/
public $mask;
private $_url = "https://enterprise.smsgupshup.com/GatewayAPI/rest"; private $_messages = array();
public function __construct($id, $password, $mask = NULL) {
$this->id = $id;
$this->password = $password;
$this->mask = $mask;
}
/**
*
* @param String $msisdn MSISDN of the recipient (will include 91)
* @param String $content Message content
* @param String $mask One of the mask as set in the enterprise account
* @param String $time In any acceptable format for PHP. Time Zone assumed to be
IST.
* @return Boolean */
public function addMsg($msisdn, $content, $mask = NULL, $time = "now"){ $message = new stdClass();
$message->msisdn = $msisdn; $message->content = $content;
$fileName = tempnam(sys_get_temp_dir(), 'EnterpriseUpload').'.csv'; $myFile = fopen($fileName, 'w');
fputs($myFile, '"'
.implode('","', array( 'PHONE', 'MESSAGE', 'MASKS', 'TIMESTAMPS'
))
.'"'
."\n"
$message->mask = $mask == NULL ? $this->mask : $mask;
$message->time = new DateTime($time, new DateTimeZone("Asia/Kolkata")); $this->_messages[] = $message;
return TRUE;
}
/**
* Sends the response using file upload API
* @return Boolean
*/
public function sendMsg(){ $rows = array();
foreach ($this->_messages as $message) { $rows[] = array(
$message->msisdn, $message->content, $message->mask, $message->time->format('Y-m-d H:i:s')
);
}
);
foreach ($rows as $row) {
fputcsv($myFile, $row, ',', '"');
}
fclose($myFile); $params = array();
$params['method'] = 'xlsUpload'; $params['userid'] = $this->id; $params['password'] = $this->password;
$params['filetype'] = 'csv'; $params['auth_scheme'] = 'PLAIN'; $params['v'] = '1.1';
$params['xlsFile'] = '@'.realpath($fileName);
$response = self::post($this->_url, $params, TRUE, CURL_HTTP_VERSION_1_0); unlink($fileName);
return preg_match('/^success/', $response);
}
public static function post($url, $params, $multipart = FALSE, $version= CURL_HTTP_VERSION_NONE){
if(function_exists('curl_init')){ $ch = curl_init();
$timeout = 60; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, $version); curl_setopt($ch, CURLOPT_POST, TRUE); if($multipart){
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); }else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
curl_setopt($ch,CURLOPT_TIMEOUT,$timeout); $data = curl_exec($ch);
if($data === FALSE){
throw new Exception(curl_errno($ch));
}
curl_close($ch); return $data;
}else{
return FALSE;
}
}
}
?>
Sample C# Code for sending a single message
var client = new RestClient("https://enterprise.smsgupshup.com/GatewayAPI/rest");
var request = new RestRequest(Method.POST);
request.AddParameter("application/x-www-form-urlencoded",
"method=sendMessage&send_to=919820XXXXXX&msg=This%20is%20sample%20test%20message%20from%20
GupShup&msg_type=TEXT&userid=XXXXXX&auth_scheme=PLAIN&password=XXXXX&format=JSON",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Sample PHP Code sending a single message (Post method)
<?php
$curl = curl_init();
$post_fields = array();
$post_fields["method"] = "sendMessage";
$post_fields["send_to"] = "919820XXXXXX";
$post_fields["msg"] = "This is sample test message from GupShup";
$post_fields["msg_type"] = "TEXT";
$post_fields["userid"] = "XXXXXX";$post_fields["password"] = "XXXXX";
$post_fields["auth_scheme"] = "PLAIN";
$post_fields["format"] = "JSON";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://enterprise.smsgupshup.com/GatewayAPI/rest",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $post_fields
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Sample Curl command for sending a single message
curl --request POST \
--url https://enterprise.smsgupshup.com/GatewayAPI/rest \
--data
'method=sendMessage&send_to=919820XXXXXX&msg=This%20is%20sample%20test%20message%20from%20G
upShup&msg_type=TEXT&userid=XXXXXX&auth_scheme=PLAIN&password=XXXXX&format=JSON'
Sample Ruby Code for sending a single message
require 'uri'
require 'net/http'
url = URI("https://enterprise.smsgupshup.com/GatewayAPI/rest")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request.body =
"method=sendMessage&send_to=919820XXXXXX&msg=This%20is%20sample%20test%20message%20from%20
GupShup&msg_type=TEXT&userid=XXXXXX&auth_scheme=PLAIN&password=XXXXX&format=JSON"
response = http.request(request)
puts response.read_body
Sample NodeJS Code for sending a single message
var request = require("request");
var options = { method: 'POST',
url: 'https://enterprise.smsgupshup.com/GatewayAPI/rest',
form:
{ method: 'sendMessage',
send_to: '919820XXXXXX',
msg: 'This is sample test message from GupShup',
msg_type: 'TEXT',
userid: 'XXXXXX',auth_scheme: 'PLAIN',
password: 'XXXXX',
format: 'JSON' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Sample Python Code for sending a single message
import requests
url = "https://enterprise.smsgupshup.com/GatewayAPI/rest"
payload =
"method=sendMessage&send_to=919820XXXXXX&msg=This%20is%20sample%20test%20message%20from%20
GupShup&msg_type=TEXT&userid=XXXXXX&auth_scheme=PLAIN&password=XXXXX&format=JSON"
response = requests.request("POST", url, data=payload)
print(response.text)
Updated over 2 years ago
What’s Next