From ad2e7ef5c28233011239bf1a98d9a9e6ef7e08c8 Mon Sep 17 00:00:00 2001 From: Shivam Agarwal Date: Fri, 12 Oct 2018 00:42:51 +0530 Subject: [PATCH] v3 update (#7) * Added Updates * Added Comments * Updated gitignore * Updated composer.json * Updated Sample Config * Added Headers in config * Updated Docs --- .gitignore | 2 + README.md | 33 +++- composer.json | 4 +- src/Exception/Exception.php | 7 + src/Exception/InvalidMethodException.php | 6 + src/Notifications/SmsApiChannel.php | 7 +- src/Notifications/SmsApiMessage.php | 22 ++- src/SmsApi.php | 235 ++++++++++++++--------- src/config/sms-api.php | 21 +- src/functions.php | 9 +- 10 files changed, 243 insertions(+), 103 deletions(-) create mode 100644 src/Exception/Exception.php create mode 100644 src/Exception/InvalidMethodException.php diff --git a/.gitignore b/.gitignore index c422267..b51f6fd 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ composer.phar # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file # composer.lock + +.idea diff --git a/README.md b/README.md index cff5233..82b27b2 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ Use can define multiple gateway configs like this:- ``` // Gateway Configuration 'gateway_name' => [ + 'method' => 'GET', //Choose Request Method (GET/POST) Default:GET 'url' => 'BaseUrl', //Base URL 'params' => [ 'send_to_param_name' => '', //Send to Parameter Name @@ -56,10 +57,36 @@ Use can define multiple gateway configs like this:- //More params can be added ], ], + 'headers' => [ + 'header1' => '', + 'header2' => '', + //More headers can be added + ], +// 'json' => true, // OPTIONAL: Use if you want the params to be sent in JSON format instead of query params (accepts true/false) +// 'wrapper' => 'wrapper_name', // OPTIONAL: Use only if you want the JSON request to be wrapped (accepts string) 'add_code' => true, //Include Country Code (true/false) ], ``` +#### Special Parameters in Gateway Config + +##### `json` Parameter +The `json` parameter accepts `true/false`. When `true`, it sends `params` as a JSON payload. It also takes care of `'Content-Type' => 'application/json'` header. + +##### `wrapper` Parameter +The `wrapper` is a special parameter which will be required only with some gateways. It wraps the JSON payload in the following structure: +``` +"wrapper_name": [ + { + "message": "Message", + "to": [ + "Receipient1", + "Receipient2" + ] + } + ] +``` + ## Usage ### Direct Use Use the `smsapi()` helper function or `SmsApi` facade to send the messages. @@ -73,6 +100,8 @@ Use the `smsapi()` helper function or `SmsApi` facade to send the messages. - Adding extra parameters `smsapi("TO", "Message", ["param1" => "val"]);` or `smsapi()->sendMessage("TO", "Message", ["param1" => "val"]);` +- Adding extra headers `smsapi("TO", "Message", ["param1" => "val"], ["header1" => "val"]);` or `smsapi()->sendMessage("TO", "Message", ["param1" => "val"], ["header1" => "val"]);` + - Using a different gateway `smsapi()->gateway('GATEWAY_NAME')->sendMessage("TO", "Message");` - Using a different country code `smsapi()->countryCode('COUNTRY_CODE')->sendMessage("TO", "Message");` @@ -84,6 +113,8 @@ Use the `smsapi()` helper function or `SmsApi` facade to send the messages. - Adding extra parameters `SmsApi::sendMessage("TO", "Message", ["param1" => "val"]);` +- Adding extra headers `SmsApi::sendMessage("TO", "Message", ["param1" => "val"], ["header1" => "val"]);` + - Using a different gateway `SmsApi::gateway('GATEWAY_NAME')->sendMessage("TO", "Message");` - Using a different country code `SmsApi::countryCode('COUNTRY_CODE')->sendMessage("TO", "Message");` @@ -140,7 +171,7 @@ class ExampleNotification extends Notification } } ``` -You can also use `->params(["param1" => "val"])` to add extra parameters to the request. +You can also use `->params(["param1" => "val"])` to add extra parameters to the request and `->headers(["header1" => "val"])` to add extra headers to the request. ## Support Feel free to post your issues in the issues section. diff --git a/composer.json b/composer.json index 3cbf673..2a1c86e 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "gr8shivam/laravel-sms-api", - "version":"2.0.4", + "version":"3.0.0", "description": "Laravel package to provide SMS API integration. Any SMS vendor that provides REST API can be used. SMS-API channel for Laravel notifications also included.", "license": "MIT", "keywords": [ @@ -16,7 +16,7 @@ { "name": "Shivam Agarwal", "email": "gr8shivam25@gmail.com", - "homepage": "https://www.shivam.ga", + "homepage": "https://github.com/gr8shivam", "role": "Developer" } ], diff --git a/src/Exception/Exception.php b/src/Exception/Exception.php new file mode 100644 index 0000000..52091d6 --- /dev/null +++ b/src/Exception/Exception.php @@ -0,0 +1,7 @@ +client->sendMessage($mobile,$message->content,$message->params); + $this->client->sendMessage($mobile,$message->content,$message->params,$message->headers); } } \ No newline at end of file diff --git a/src/Notifications/SmsApiMessage.php b/src/Notifications/SmsApiMessage.php index 517593e..9c0e868 100644 --- a/src/Notifications/SmsApiMessage.php +++ b/src/Notifications/SmsApiMessage.php @@ -17,6 +17,13 @@ class SmsApiMessage */ public $params; + /** + * Add Headers. + * + * @var array + */ + public $headers=[]; + /** * The message type. * @@ -29,10 +36,12 @@ class SmsApiMessage * * @param string $content * @param array $params + * @param array $headers */ - public function __construct($content = '', $params = null) { + public function __construct($content = '', $params = null, $headers=[]) { $this->content = $content; $this->params = $params; + $this->headers = $headers; } /** @@ -46,7 +55,6 @@ public function content($content) { return $this; } - /** * Set the message params. * @@ -59,6 +67,16 @@ public function params($params) return $this; } + /** + * @param $headers + * @return $this + */ + public function headers($headers) + { + $this->headers = $headers; + return $this; + } + /** * Set the message type. * diff --git a/src/SmsApi.php b/src/SmsApi.php index dcf3140..6ed593f 100644 --- a/src/SmsApi.php +++ b/src/SmsApi.php @@ -2,23 +2,27 @@ namespace Gr8Shivam\SmsApi; + use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Request; use Illuminate\Support\Facades\Log; use GuzzleHttp\Exception\RequestException; +use Gr8Shivam\SmsApi\Exception\InvalidMethodException; class SmsApi { + private static $client = null; private $config = array(); private $gateway; - private static $client=null; private $request = ''; private $response = ''; - private $country_code=null; + private $country_code = null; /** * SmsApi constructor. */ - public function __construct() { + public function __construct() + { $this->createClient(); } @@ -27,66 +31,164 @@ public function __construct() { * * @return $this */ - protected function createClient() { - if(!self::$client){ + protected function createClient() + { + if (!self::$client) { self::$client = new Client; } return $this; } /** - * Load Default Gateway + * Set custom gateway * + * @param string $gateway * @return $this */ - private function loadDefaultGateway() { - $default_acc = config('sms-api.default', null); - if ($default_acc) { - $this->gateway = $default_acc; - } + public function gateway($gateway = '') + { + $this->gateway = $gateway; return $this; } /** - * Load Credentials from the selected Gateway + * Set custom country code * + * @param string $country_code * @return $this */ - protected function loadCredentialsFromConfig() { - $gateway = $this->gateway; - $config_name = 'sms-api.'.$gateway; - $this->config = config($config_name); + public function countryCode($country_code = '') + { + $this->country_code = $country_code; return $this; } /** - * Get Client + * Send message * - * @return GuzzleHttp\Client + * @param $to + * @param $message + * @param array $extra_params + * @param array $extra_headers + * @return $this + * @throws InvalidMethodException */ - public function getClient() { - return self::$client; + public function sendMessage($to, $message, $extra_params = null, $extra_headers = []) + { + if ($this->gateway == '') { + $this->loadDefaultGateway(); + } + $this->loadCredentialsFromConfig(); + + $request_method = isset($this->config['method']) ? $this->config['method'] : 'GET'; + $url = $this->config['url']; + + $mobile = $this->config['add_code'] ? $this->addCountryCode($to) : $to; + if (is_array($mobile)) { + //Flatten Array only if JSON false + if (!(isset($this->config['json']) && $this->config['json'])) { + $mobile = $this->composeBulkMobile($mobile); + } + } + + $params = $this->config['params']['others']; + + $headers = isset($this->config['headers']) ? $this->config['headers'] : []; + + //Check wrapper for JSON Payload + $wrapper = isset($this->config['wrapper']) ? $this->config['wrapper'] : NULL; + + $send_to_param_name = $this->config['params']['send_to_param_name']; + $msg_param_name = $this->config['params']['msg_param_name']; + + if ($wrapper) { + $send_vars[$send_to_param_name] = $mobile; + $send_vars[$msg_param_name] = $message; + } else { + $params[$send_to_param_name] = $mobile; + $params[$msg_param_name] = $message; + } + + if ($extra_params) { + $params = array_merge($params, $extra_params); + } + + if($extra_headers){ + $headers = array_merge($headers, $extra_headers); + } + + try { + //Build Request + $request = new Request($request_method, $url); + if ($request_method == "GET") { + $promise = $this->getClient()->sendAsync( + $request, + [ + 'query' => $params, + 'headers' => $headers + ] + ); + } elseif ($request_method == "POST") { + $payload = $wrapper ? array_merge(array($wrapper => array($send_vars)), $params) : $params; + + if ((isset($this->config['json']) && $this->config['json'])) { + $promise = $this->getClient()->sendAsync( + $request, + [ + 'json' => $payload, + 'headers' => $headers + ] + ); + } else { + $promise = $this->getClient()->sendAsync( + $request, + [ + 'query' => $params, + 'headers' => $headers + ] + ); + } + } else { + throw new InvalidMethodException( + sprintf("Only GET and POST methods allowed.") + ); + } + + $this->response = $promise->wait()->getBody()->getContents(); + + } catch (RequestException $e) { + if ($e->hasResponse()) { + $this->response = $e->getResponseBodySummary($e->getResponse()); + } + } + Log::info('SMS Gateway Response: ' . $this->response); + return $this; } /** - * Set custom gateway + * Load Default Gateway * - * @param string $gateway * @return $this */ - public function gateway($gateway=''){ - $this->gateway = $gateway; + private function loadDefaultGateway() + { + $default_acc = config('sms-api.default', null); + if ($default_acc) { + $this->gateway = $default_acc; + } return $this; } /** - * Set custom country code + * Load Credentials from the selected Gateway * - * @param string $country_code * @return $this */ - public function countryCode($country_code=''){ - $this->country_code = $country_code; + protected function loadCredentialsFromConfig() + { + $gateway = $this->gateway; + $config_name = 'sms-api.' . $gateway; + $this->config = config($config_name); return $this; } @@ -96,15 +198,18 @@ public function countryCode($country_code=''){ * @param $mobile * @return array|string */ - private function addCountryCode($mobile) { - if(!$this->country_code){ - $this->country_code=config('sms-api.country_code', '91'); + private function addCountryCode($mobile) + { + if (!$this->country_code) { + $this->country_code = config('sms-api.country_code', '91'); } - if(is_array($mobile)){ - array_walk($mobile, function(&$value, $key) { $value = $this->country_code.$value; }); + if (is_array($mobile)) { + array_walk($mobile, function (&$value, $key) { + $value = $this->country_code . $value; + }); return $mobile; } - return $this->country_code.$mobile; + return $this->country_code . $mobile; } /** @@ -113,62 +218,19 @@ private function addCountryCode($mobile) { * @param $mobile * @return string */ - private function composeBulkMobile($mobile) { - return implode(',',$mobile); - } - - /** - * Generate Request URL - * - * @param $mobile - * @param $message - * @param array $extra_params - * @return string - */ - private function getUrl($mobile, $message, $extra_params=null) { - $params = $this->config['params']['others']; - $send_to_param_name = $this->config['params']['send_to_param_name']; - $msg_param_name = $this->config['params']['msg_param_name']; - $params[$send_to_param_name] = $mobile; - $params[$msg_param_name] = $message; - $url = $this->config['url']; - if($extra_params){ - $params = array_merge($params,$extra_params); - } - foreach($params as $key=>$val) { - $this->request.= $key."=".urlencode($val); - $this->request.= "&"; - } - $this->request = substr($this->request, 0, strlen($this->request)-1); - return $url.$this->request; + private function composeBulkMobile($mobile) + { + return implode(',', $mobile); } /** - * Send message + * Get Client * - * @param $to - * @param $message - * @param array $extra_params - * @return $this + * @return GuzzleHttp\Client */ - public function sendMessage($to, $message, $extra_params=null) { - if($this->gateway==''){ - $this->loadDefaultGateway(); - } - $this->loadCredentialsFromConfig(); - $mobile = $this->config['add_code']?$this->addCountryCode($to):$to; - if(is_array($mobile)){ - $mobile = $this->composeBulkMobile($mobile); - } - try { - $this->response = $this->getClient()->get($this->getUrl($mobile,$message,$extra_params))->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - $this->response = $e->getResponseBodySummary($e->getResponse()); - } - } - Log::info('SMS Gateway Response: '.$this->response); - return $this; + public function getClient() + { + return self::$client; } /** @@ -176,7 +238,8 @@ public function sendMessage($to, $message, $extra_params=null) { * * @return string */ - public function response(){ + public function response() + { return $this->response; } } \ No newline at end of file diff --git a/src/config/sms-api.php b/src/config/sms-api.php index e8fe6e1..ae01be6 100644 --- a/src/config/sms-api.php +++ b/src/config/sms-api.php @@ -3,10 +3,11 @@ return [ 'country_code' => '91', //Country code to be added - 'default' => env('SMS_API_DEFAULT_GATEWAY', 'msg91'), //Choose default gateway + 'default' => env('SMS_API_DEFAULT_GATEWAY', 'gateway_name'), //Choose default gateway // Gateway Configuration 'gateway_name' => [ + 'method' => 'GET', //Choose Request Method (GET/POST) Default:GET 'url' => 'BaseUrl', //Base URL 'params' => [ 'send_to_param_name' => '', //Send to Parameter Name @@ -18,6 +19,13 @@ //More params can be added ], ], + 'headers' => [ + 'header1' => '', + 'header2' => '', + //More headers can be added + ], +// 'json' => true, // OPTIONAL: Use if you want the params to be sent in JSON format instead of query params (accepts true/false) +// 'wrapper' => 'wrapper_name', // OPTIONAL: Use only if you want the JSON request to be wrapped (accepts wrapper name) 'add_code' => true, //Include Country Code (true/false) ], @@ -45,11 +53,12 @@ 'add_code' => true, //Include Country Code ], -// MSG91 + //MSG91 'msg91' => [ - 'url' => 'https://control.msg91.com/api/v2/sendsms?', + 'method' => 'POST', //Choose Request Method (GET/POST) + 'url' => 'https://control.msg91.com/api/v2/sendsms?', //Base URL 'params' => [ - 'send_to_param_name' => 'mobiles', //Send to Parameter Name + 'send_to_param_name' => 'to', //Send to Parameter Name 'msg_param_name' => 'message', //Message Parameter Name 'others' => [ 'authkey' => '', //Your auth key @@ -58,7 +67,9 @@ 'country' => '91', ], ], - 'add_code' => false, //Include Country Code + 'json' => true, // Use if you want the params to be sent in JSON format instead of query params + 'wrapper' => 'sms', //Optional, use only if you want the JSON request to be wrapped + 'add_code' => false, //Include Country Code (true/false) ] ]; \ No newline at end of file diff --git a/src/functions.php b/src/functions.php index f6f84bd..900ddb2 100644 --- a/src/functions.php +++ b/src/functions.php @@ -4,19 +4,20 @@ * Add helper function */ -if (! function_exists('smsapi')) { +if (!function_exists('smsapi')) { /** * @param string $to * @param string $message * @param array $extra_params + * @param array $headers * @return mixed */ - function smsapi($to = null, $message = null, $extra_params=null) + function smsapi($to = null, $message = null, $extra_params = null, $headers = []) { $smsapi = app('smsapi'); - if (! (is_null($to) || is_null($message))) { - return $smsapi->sendMessage($to,$message,$extra_params); + if (!(is_null($to) || is_null($message))) { + return $smsapi->sendMessage($to, $message, $extra_params, $headers); } return $smsapi; }