Παρέχεται παρακάτω ένα απλό παράδειγμα αποστολής μίας ειδοποίησης μέσω SMS. Είναι σε γλώσσα PHP και δεν κάνει depend σε κάποια βιβλιοθήκη ή PHP extension, αλλά υλοποιεί έναν απλό JSON-RPC 2.0 client σε μία function που μπορεί να χρησιμοποιηθεί αυτούσια.
(Σημείωση: ο κώδικας της παρακάτω function προέρχεται από το project JsonRpcPHP και είναι κάτω από την άδεια χρήσης GPL).
<?php
// ==================================================================
//
// Send an SMS Notification to a user's mobile
//
// ------------------------------------------------------------------
$key = 'SET_YOUR_API_KEY_HERE';
$url = 'https://ws.gunet.gr/ws/?service=sms&key='.$key;
try {
if(empty( jsonrpccall($url, 'send', array(
'number' => '6998118881',
'message' => 'Ο κωδικός σας έχει ενημερωθεί.'
)))) {
// Success; Message sent!
}
} catch (Exception $e) {
// Failure; message was not sent
echo $e->getMessage();
}
// ==================================================================
//
// Function Defintions Below
//
// ------------------------------------------------------------------
/**
* Performs a jsonRCP request and gets the results as an array
*
* @param string $url
* @param string $method
* @param array $params
* @return array
*/
function jsonrpccall($url, $method, $params) {
$currentId = 1;
// check
if (!is_scalar($method)) {
throw new Exception('Method name has no scalar value');
}
// check
if (is_array($params)) {
// no keys
$params = array_values($params);
} else {
throw new Exception('Params must be given as array');
}
// prepares the request
$request = array(
'jsonrpc' => "2.0",
'method' => $method,
'params' => $params,
'id' => $currentId
);
$request = json_encode($request);
// performs the HTTP POST
$opts = array ('http' => array (
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $request
));
$context = stream_context_create($opts);
if ($fp = fopen($url, 'r', false, $context)) {
$response = '';
while($row = fgets($fp)) {
$response.= trim($row)."\n";
}
$response = json_decode($response,true);
} else {
throw new Exception('Unable to connect to URL');
}
// final checks and return
// check
if ($response['id'] != $currentId) {
throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')');
}
if (!is_null($response['error'])) {
throw new Exception('Request error: '.$response['error']);
}
return $response['result'];
}