diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..5446bcee --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: +- package-ecosystem: composer + directory: "/" + schedule: + interval: daily + time: "23:30" + open-pull-requests-limit: 10 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100755 index 00000000..ded9163a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to `Textlocal` will be documented in this file + + +## 2.4.0 - 2022-08-17 + +`public function getSenderId($notifiable)` + +method has changed from `public function getSenderId()`, so now the notifiable is passed as parameter +giving more control to the imeplementation to decide based on user/recipent in case want to use some alternate deciding factor + +## 0.0.1 - 2017-08-07 + +- initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100755 index 00000000..4da74e3f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..e65b3a7c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) Manash Jyoti Sonowal + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. diff --git a/README.md b/README.md index 746a917d..31a41247 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,174 @@ -# new-channels +This package allows to send SMS using Textlocal API using laravel notifications channel textlocal sms -Discuss about new channel proposals our share your finished channels in the [proposal issue](https://github.com/laravel-notification-channels/new-channels/issues/6). +Supports Laravel 5.5 upto 10.x -Take a look at our [FAQ](http://laravel-notification-channels.com/) to see our small list of rules, to provide top-notch notification channels. +[![Latest Stable Version](https://poser.pugx.org/msonowal/laravel-notification-channel-textlocal/v/stable)](https://packagist.org/packages/msonowal/laravel-notification-channel-textlocal) +[![License](https://poser.pugx.org/msonowal/laravel-notification-channel-textlocal/license)](https://packagist.org/packages/msonowal/laravel-notification-channel-textlocal) +[![Total Downloads](https://poser.pugx.org/msonowal/laravel-notification-channel-textlocal/downloads)](https://packagist.org/packages/msonowal/laravel-notification-channel-textlocal) + +This package makes it easy to send notifications using [textlocal](https://www.textlocal.in/) with Laravel 5.3.+ + + +To use version ^2.3.0 onwards will require PHP 8.0 + +for other PHP version use upto ^2.2.0 + +## Contents + +- [Installation](#installation) + - [Setting up the textlocal service](#setting-up-the-textlocal-service) +- [Usage](#usage) + - [Available Message methods](#available-message-methods) +- [Changelog](#changelog) +- [Testing](#testing) +- [Security](#security) +- [Contributing](#contributing) +- [Credits](#credits) +- [License](#license) + + +## Installation + +Create an account in textlocal then create an API key or hash(password). + +`composer require msonowal/laravel-notification-channel-textlocal` + +### Setting up the textlocal service + +default config `textlocal.php` update where desired + +Important Either specify a Key OR a Hash - don't enter both! + +``` +return [ + 'username' => env('TEXTLOCAL_USERNAME'), + 'password' => env('TEXTLOCAL_PASSWORD'), + 'hash' => env('TEXTLOCAL_HASH'), //optional if api_key is set + 'api_key' => env('TEXTLOCAL_API_KEY'), //optional if hash is set + 'sender' => env('TEXTLOCAL_SENDER'), + 'request_urls' => [ + 'IN' => 'https://api.textlocal.in/', + 'UK' => 'https://api.txtlocal.com/' + ], + 'country' => env('TEXTLOCAL_COUNTRY', 'IN'), + 'extra' => [ + // extra config define keys as desired for use within the textlocal client config + // if you want to use the custom client config for each notification or notifiable + // INotificationUsesTextlocalClientConfig + ]public function getSenderId($notifiable) +### Configuring .env +``` + TEXTLOCAL_USERNAME=Your email id or api key + TEXTLOCAL_HASH=get it from url '/docs/' under your API KEYS section + TEXTLOCAL_API_KEY get it from url '/docs/' under your API KEYS section + TEXTLOCAL_SENDER=Name of the Sender that will be displayed to the recipient (max 6 Characters). + TEXTLOCAL_COUNTRY=Your Two letter(ISO-3166-alpha-2) Country Code. It should be the Country of the TEXTLOCAL account. defaults to IN +``` + +### Publish Config +``` + php artisan vendor:publish --tag=textlocal +``` + +Currently, only textlocal of two country is supported IN(India) and UK(United Kingdom). + +## Usage + +Implement this method `routeNotificationForTextlocal()` in your notifiable class/model which will return array of mobile numbers. Please make sure the mobile number contains the dial code as well (e.g +91 for India). And lastly implement `toSms()` method in the notification class which will return the (string) sms or template that is defined in textlocal account that needs to be send. + + +## Usage + +You can use the channel in your `via()` method inside the notification: + +```php +use Illuminate\Notifications\Notification; +use NotificationChannels\Textlocal\TextlocalChannel; + +class TestOTPNotification extends Notification +{ + public function via($notifiable) + { + return [TextlocalChannel::class]; + } + + public function toSms($notifiable) + { + return 'Use 1234 as OTP for resetting your password.'; + } +} +``` + +In your notifiable model, make sure to include a `routeNotificationForTextlocal()` method, which returns a phone number or multiple numbers in array +or an array of phone numbers. + +```php +public function routeNotificationForTextlocal(): array +{ + return [$this->mobile_no]; +} +``` + +Annoynmous Notifable when say mobile no is not added to a notifiable model you can directly send to mobile no by using that + +```php +Notification::route('Textlocal', $mobileNo')->notify(new VerifyMobileNotification($otp)); +``` + +### Available Message methods + +And if you want to have a specific sender based on Notification, e.g. like you are sending promotional notification using one and another for transaction then you can just define this method in your notification class which will return your sender id for that notification only +``` +public function getSenderId($notifiable) +{ + return 'YOUR_SENDER_ID'; +} +``` + + +Unicode support +If you want to send the notification content to have unicode support. Define this method in your notification which will return boolean based on which the sms will set the unicode mode in textlocal API +``` +public function getUnicodeMode() +{ + return true; +} +``` + +A list of all available options + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. + +## Testing + +``` bash +$ composer test +``` + +## Security + +If you discover any security related issues, please email manash149@gmail.com instead of using the issue tracker. + +# Found any bugs or improvement open an issue or send me a PR + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Credits + +- [Manash Jyoti Sonowal](https://github.com/msonowal) +- [Mr Ejang](https://github.com/tomonsoejang) +- [Sinadh](https://github.com/tsainadh) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. + +## TODO +Need to convert to Guzzle Http as a Client in core +Add more countries +add tests diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..3921a676 --- /dev/null +++ b/composer.json @@ -0,0 +1,47 @@ +{ + "name": "msonowal/laravel-notification-channel-textlocal", + "description": "Textlocal Notifications Channel for Laravel", + "homepage": "https://github.com/laravel-notification-channels/textlocal", + "license": "MIT", + "authors": [ + { + "name": "Manash Jyoti Sonowal", + "email": "manash149@gmail.com", + "homepage": "https://github.com/msonowal", + "role": "Developer" + } + ], + "require": { + "php": ">=7.0", + "ext-json": "*", + "illuminate/notifications": "~5.5|~6.0|~7.0|~8.0|~9.0|~10.0|~11.0", + "illuminate/support": "~5.5|~6.0|~7.0|~8.0|~9.0|~10.0|~11.0" + }, + "require-dev": { + "mockery/mockery": "^0.9.5|^1.0", + "phpunit/phpunit": "~5|^8.0|^9.0|^10.0|~11.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\Textlocal\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\Textlocal\\Test\\": "tests" + } + }, + "extra": { + "laravel": { + "providers": [ + "NotificationChannels\\Textlocal\\TextlocalServiceProvider" + ] + } + }, + "scripts": { + "test": "vendor/bin/phpunit" + }, + "config": { + "sort-packages": true + } +} diff --git a/config/textlocal.php b/config/textlocal.php new file mode 100644 index 00000000..6dfa12a3 --- /dev/null +++ b/config/textlocal.php @@ -0,0 +1,26 @@ + env('TEXTLOCAL_USERNAME'), + 'password' => env('TEXTLOCAL_PASSWORD'), + 'hash' => env('TEXTLOCAL_HASH'), + 'api_key' => env('TEXTLOCAL_API_KEY'), + 'sender' => env('TEXTLOCAL_SENDER', 'DOCONL'), + 'request_urls' => [ + 'IN' => 'https://api.textlocal.in/', + 'UK' => 'https://api.txtlocal.com/', + ], + 'country' => env('TEXTLOCAL_COUNTRY', 'IN'), + /* + // a sample way to organize custom config when using mutliple on demand config + // uncomment this for that purpose or feel free to use your own implementations + 'UK' => [ + 'username' => env('TEXTLOCAL_USERNAME_UK'), + 'password' => env('TEXTLOCAL_PASSWORD_UK'), + 'hash' => env('TEXTLOCAL_HASH_UK'), + 'api_key' => env('TEXTLOCAL_API_KEY_UK'), + 'sender' => env('TEXTLOCAL_SENDER_UK', 'DOCONL'), + 'country' => env('TEXTLOCAL_COUNTRY_UK', 'UK'), + ], + */ +]; diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..7042c52b --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + tests + + + + + src/ + + + + + + + + + + diff --git a/scrutinizer.yml b/scrutinizer.yml new file mode 100644 index 00000000..6fad5be9 --- /dev/null +++ b/scrutinizer.yml @@ -0,0 +1,21 @@ +filter: + excluded_paths: [tests/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true + +tools: + external_code_coverage: true diff --git a/src/Contracts/INotificationUsesTextlocalClientConfig.php b/src/Contracts/INotificationUsesTextlocalClientConfig.php new file mode 100644 index 00000000..cebbb99d --- /dev/null +++ b/src/Contracts/INotificationUsesTextlocalClientConfig.php @@ -0,0 +1,20 @@ +getMessage() . ' message: ' . $message); + } +} diff --git a/src/Textlocal.php b/src/Textlocal.php new file mode 100644 index 00000000..0f5e11d7 --- /dev/null +++ b/src/Textlocal.php @@ -0,0 +1,818 @@ + + * + * @version 1.4-IN + * @string $request_url URL to make the request to + * @const REQUEST_TIMEOUT Timeout in seconds for the HTTP request + * @const REQUEST_HANDLER Handler to use when making the HTTP request (for future use) + */ +class Textlocal +{ + const REQUEST_TIMEOUT = 60; + const REQUEST_HANDLER = 'curl'; + + private string $request_url; + + private $errorReporting = false; + + public $errors = []; + public $warnings = []; + + public $lastRequest = []; + public $treatAsUnicode = 0; + + /** + * Instantiate the object. + * + * @param string|null $username + * @param string|null $hash + * @param string|null $apiKey + * @param string $country + */ + public function __construct(private $username, private $hash, private $apiKey, private string $country) + { + $this->request_url = config('textlocal.request_urls')[$country]; + } + + /** + * Private function to construct and send the request and handle the response. + * + * @param $command + * @param array $params + * + * @throws Exception + * + * @return array|mixed + * + * @todo Add additional request handlers - eg fopen, file_get_contacts + */ + private function _sendRequest($command, $params = []) + { + if ($this->apiKey && ! empty($this->apiKey)) { + $params['apiKey'] = $this->apiKey; + } else { + $params['hash'] = $this->hash; + } + // Create request string + $params['username'] = $this->username; + + $this->lastRequest = $params; + + if (self::REQUEST_HANDLER == 'curl') { + $rawResponse = $this->_sendRequestCurl($command, $params); + } else { + throw new Exception('Invalid request handler.'); + } + + $result = json_decode($rawResponse); + if (isset($result->errors)) { + if (count($result->errors) > 0) { + foreach ($result->errors as $error) { + switch ($error->code) { + default: + throw new Exception($error->message); + } + } + } + } + + return $result; + } + + /** + * Curl request handler. + * + * @param $command + * @param $params + * + * @throws Exception + * + * @return mixed + */ + private function _sendRequestCurl($command, $params) + { + $url = $this->request_url.$command.'/'; + + // Initialize handle + $ch = curl_init($url); + curl_setopt_array( + $ch, [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $params, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_TIMEOUT => self::REQUEST_TIMEOUT, + ] + ); + + $rawResponse = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error = curl_error($ch); + curl_close($ch); + + if ($rawResponse === false) { + throw new Exception('Failed to connect to the Textlocal service: '.$error); + } elseif ($httpCode != 200) { + throw new Exception('Bad response from the Textlocal service: HTTP code '.$httpCode); + } + + return $rawResponse; + } + + /** + * fopen() request handler. + * + * @param $command + * @param $params + * + * @throws Exception + */ + private function _sendRequestFopen($command, $params) + { + throw new Exception('Unsupported transfer method'); + } + + /** + * Get last request's parameters. + * + * @return array + */ + public function getLastRequest() + { + return $this->lastRequest; + } + + /** + * Send an SMS to one or more comma separated numbers. + * + * @param $numbers + * @param $message + * @param $sender + * @param null $sched + * @param bool $test + * @param null $receiptURL + * @param null $custom + * @param false $optouts + * @param false $simpleReplyService + * + * @throws Exception + * + * @return array|mixed + */ + public function sendSms($numbers, $message, $sender, $sched = null, bool $test = false, $receiptURL = null, $custom = null, $optouts = false, $simpleReplyService = false) + { + if (! is_array($numbers)) { + throw new Exception('Invalid $numbers format. Must be an array'); + } + if (empty($message)) { + throw new Exception('Empty message'); + } + if (empty($sender)) { + throw new Exception('Empty sender name'); + } + if (! is_null($sched) && ! is_numeric($sched)) { + throw new Exception('Invalid date format. Use numeric epoch format'); + } + + $params = [ + 'message' => rawurlencode($message), + 'numbers' => implode(',', $numbers), + 'sender' => rawurlencode($sender), + 'schedule_time' => $sched, + 'test' => $test, + 'receipt_url' => $receiptURL, + 'custom' => $custom, + 'optouts' => $optouts, + 'simple_reply' => $simpleReplyService, + 'unicode' => $this->treatAsUnicode, + ]; + + return $this->_sendRequest('send', $params); + } + + /** + * Send an SMS to a Group of contacts - group IDs can be retrieved from getGroups(). + * + * @param $groupId + * @param $message + * @param null $sender + * @param false $test + * @param null $receiptURL + * @param numm $custom + * @param false $optouts + * @param false $simpleReplyService + * + * @throws Exception + * + * @return array|mixed + */ + public function sendSmsGroup($groupId, $message, $sender = null, $sched = null, $test = false, $receiptURL = null, $custom = null, $optouts = false, $simpleReplyService = false) + { + if (! is_numeric($groupId)) { + throw new Exception('Invalid $groupId format. Must be a numeric group ID'); + } + if (empty($message)) { + throw new Exception('Empty message'); + } + if (empty($sender)) { + throw new Exception('Empty sender name'); + } + if (! is_null($sched) && ! is_numeric($sched)) { + throw new Exception('Invalid date format. Use numeric epoch format'); + } + + $params = [ + 'message' => rawurlencode($message), + 'group_id' => $groupId, + 'sender' => rawurlencode($sender), + 'schedule_time' => $sched, + 'test' => $test, + 'receipt_url' => $receiptURL, + 'custom' => $custom, + 'optouts' => $optouts, + 'simple_reply' => $simpleReplyService, + ]; + + return $this->_sendRequest('send', $params); + } + + /** + * Send an MMS to a one or more comma separated contacts. + * + * @param $numbers + * @param $fileSource - either an absolute or relative path, or http url to a file. + * @param $message + * @param null $sched + * @param false $test + * @param false $optouts + * + * @throws Exception + * + * @return array|mixed + */ + public function sendMms($numbers, $fileSource, $message, $sched = null, $test = false, $optouts = false) + { + if (! is_array($numbers)) { + throw new Exception('Invalid $numbers format. Must be an array'); + } + if (empty($message)) { + throw new Exception('Empty message'); + } + if (empty($fileSource)) { + throw new Exception('Empty file source'); + } + if (! is_null($sched) && ! is_numeric($sched)) { + throw new Exception('Invalid date format. Use numeric epoch format'); + } + + $params = [ + 'message' => rawurlencode($message), + 'numbers' => implode(',', $numbers), + 'schedule_time' => $sched, + 'test' => $test, + 'optouts' => $optouts, + ]; + + /* + * Local file. POST to service +*/ + if (is_readable($fileSource)) { + $params['file'] = '@'.$fileSource; + } else { + $params['url'] = $fileSource; + } + + return $this->_sendRequest('send_mms', $params); + } + + /** + * Send an MMS to a group - group IDs can be. + * + * @param $groupId + * @param $fileSource + * @param $message + * @param null $sched + * @param false $test + * @param false $optouts + * + * @throws Exception + * + * @return array|mixed + */ + public function sendMmsGroup($groupId, $fileSource, $message, $sched = null, $test = false, $optouts = false) + { + if (! is_numeric($groupId)) { + throw new Exception('Invalid $groupId format. Must be a numeric group ID'); + } + if (empty($message)) { + throw new Exception('Empty message'); + } + if (empty($fileSource)) { + throw new Exception('Empty file source'); + } + if (! is_null($sched) && ! is_numeric($sched)) { + throw new Exception('Invalid date format. Use numeric epoch format'); + } + + $params = [ + 'message' => rawurlencode($message), + 'group_id' => $groupId, + 'schedule_time' => $sched, + 'test' => $test, + 'optouts' => $optouts, + ]; + + /* + * Local file. POST to service +*/ + if (is_readable($fileSource)) { + $params['file'] = '@'.$fileSource; + } else { + $params['url'] = $fileSource; + } + + return $this->_sendRequest('send_mms', $params); + } + + /** + * Returns reseller customer's ID's. + * + * @return array + **/ + public function getUsers() + { + return $this->_sendRequest('get_users'); + } + + /** + * Transfer credits to a reseller's customer. + * + * @param $user - can be ID or Email + * @param $credits + * + * @throws Exception + * + * @return array|mixed + **/ + public function transferCredits($user, $credits) + { + if (! is_numeric($credits)) { + throw new Exception('Invalid credits format'); + } + if (! is_numeric($user)) { + throw new Exception('Invalid user'); + } + if (empty($user)) { + throw new Exception('No user specified'); + } + if (empty($credits)) { + throw new Exception('No credits specified'); + } + + if (is_int($user)) { + $params = [ + 'user_id' => $user, + 'credits' => $credits, + ]; + } else { + $params = [ + 'user_email' => rawurlencode($user), + 'credits' => $credits, + ]; + } + + return $this->_sendRequest('transfer_credits', $params); + } + + /**Get templates from an account **/ + + public function getTemplates() + { + return $this->_sendRequest('get_templates'); + } + + /** + * Check the availability of a keyword. + * + * @param $keyword + * return array|mixed + */ + public function checkKeyword($keyword) + { + $params = ['keyword' => $keyword]; + + return $this->_sendRequest('check_keyword', $params); + } + + /** + * Create a new contact group. + * + * @param $name + * + * @return array|mixed + */ + public function createGroup($name) + { + $params = ['name' => $name]; + + return $this->_sendRequest('create_group', $params); + } + + /** + * Get contacts from a group - Group IDs can be retrieved with the getGroups() function. + * + * @param $groupId + * @param $limit + * @param int $startPos + * + * @throws Exception + * + * @return array|mixed + */ + public function getContacts($groupId, $limit, $startPos = 0) + { + if (! is_numeric($groupId)) { + throw new Exception('Invalid $groupId format. Must be a numeric group ID'); + } + if (! is_numeric($startPos) || $startPos < 0) { + throw new Exception('Invalid $startPos format. Must be a numeric start position, 0 or above'); + } + if (! is_numeric($limit) || $limit < 1) { + throw new Exception('Invalid $limit format. Must be a numeric limit value, 1 or above'); + } + + $params = [ + 'group_id' => $groupId, + 'start' => $startPos, + 'limit' => $limit, + ]; + + return $this->_sendRequest('get_contacts', $params); + } + + /** + * Create one or more number-only contacts in a specific group, defaults to 'My Contacts'. + * + * @param $numbers + * @param string $groupid + * + * @return array|mixed + */ + public function createContacts($numbers, $groupid = '5') + { + $params = ['group_id' => $groupid]; + + if (is_array($numbers)) { + $params['numbers'] = implode(',', $numbers); + } else { + $params['numbers'] = $numbers; + } + + return $this->_sendRequest('create_contacts', $params); + } + + /** + * Create bulk contacts - with name and custom information from an array of: + * [first_name] [last_name] [number] [custom1] [custom2] [custom3]. + * + * @param array $contacts + * @param string $groupid + * + * @return array|mixed + */ + public function createContactsBulk($contacts, $groupid = '5') + { + // JSON & URL-encode array + $contacts = rawurlencode(json_encode($contacts)); + + $params = ['group_id' => $groupid, 'contacts' => $contacts]; + + return $this->_sendRequest('create_contacts_bulk', $params); + } + + /** + * Get a list of groups and group IDs. + * + * @return array|mixed + */ + public function getGroups() + { + return $this->_sendRequest('get_groups'); + } + + /** + * Get the status of a message based on the Message ID - this can be taken from sendSMS or from a history report. + * + * @param $messageid + * + * @return array|mixed + */ + public function getMessageStatus($messageid) + { + $params = ['message_id' => $messageid]; + + return $this->_sendRequest('status_message', $params); + } + + /** + * Get the status of a message based on the Batch ID - this can be taken from sendSMS or from a history report. + * + * @param $batchid + * + * @return array|mixed + */ + public function getBatchStatus($batchid) + { + $params = ['batch_id' => $batchid]; + + return $this->_sendRequest('status_batch', $params); + } + + /** + * Get sender names. + * + * @return array|mixed + */ + public function getSenderNames() + { + return $this->_sendRequest('get_sender_names'); + } + + /** + * Get inboxes available on the account. + * + * @return array|mixed + */ + public function getInboxes() + { + return $this->_sendRequest('get_inboxes'); + } + + /** + * Get Credit Balances. + * + * @return array + */ + public function getBalance() + { + $result = $this->_sendRequest('balance'); + + return ['sms' => $result->balance->sms, 'mms' => $result->balance->mms]; + } + + /** + * Get messages from an inbox - The ID can ge retrieved from getInboxes(). + * + * @param $inbox + * + * @return array|bool|mixed + */ + public function getMessages($inbox) + { + if (! isset($inbox)) { + return false; + } + $options = ['inbox_id' => $inbox]; + + return $this->_sendRequest('get_messages', $options); + } + + /** + * Cancel a scheduled message based on a message ID from getScheduledMessages(). + * + * @param $id + * + * @return array|bool|mixed + */ + public function cancelScheduledMessage($id) + { + if (! isset($id)) { + return false; + } + $options = ['sent_id' => $id]; + + return $this->_sendRequest('cancel_scheduled', $options); + } + + /** + * Get Scheduled Message information. + * + * @return array|mixed + */ + public function getScheduledMessages() + { + return $this->_sendRequest('get_scheduled'); + } + + /** + * Delete a contact based on telephone number from a group. + * + * @param $number + * @param int $groupid + * + * @return array|bool|mixed + */ + public function deleteContact($number, $groupid = 5) + { + if (! isset($number)) { + return false; + } + $options = ['number' => $number, 'group_id' => $groupid]; + + return $this->_sendRequest('delete_contact', $options); + } + + /** + * Delete a group - Be careful, we can not recover any data deleted by mistake. + * + * @param $groupid + * + * @return array|mixed + */ + public function deleteGroup($groupid) + { + $options = ['group_id' => $groupid]; + + return $this->_sendRequest('delete_group', $options); + } + + /** + * Get single SMS history (single numbers, comma seperated numbers when sending). + * + * @param $start + * @param $limit + * @param $min_time Unix timestamp + * @param $max_time Unix timestamp + * + * @return array|bool|mixed + */ + public function getSingleMessageHistory($start, $limit, $min_time, $max_time) + { + return $this->getHistory('get_history_single', $start, $limit, $min_time, $max_time); + } + + /** + * Get API SMS Message history. + * + * @param $start + * @param $limit + * @param $min_time Unix timestamp + * @param $max_time Unix timestamp + * + * @return array|bool|mixed + */ + public function getAPIMessageHistory($start, $limit, $min_time, $max_time) + { + return $this->getHistory('get_history_api', $start, $limit, $min_time, $max_time); + } + + /** + * Get Email to SMS History. + * + * @param $start + * @param $limit + * @param $min_time Unix timestamp + * @param $max_time Unix timestamp + * + * @return array|bool|mixed + */ + public function getEmailToSMSHistory($start, $limit, $min_time, $max_time) + { + return $this->getHistory('get_history_email', $start, $limit, $min_time, $max_time); + } + + /** + * Get group SMS history. + * + * @param $start + * @param $limit + * @param $min_time Unix timestamp + * @param $max_time Unix timestamp + * + * @return array|bool|mixed + */ + public function getGroupMessageHistory($start, $limit, $min_time, $max_time) + { + return $this->getHistory('get_history_group', $start, $limit, $min_time, $max_time); + } + + /** + * Generic function to provide validation and the request method for getting all types of history. + * + * @param $type + * @param $start + * @param $limit + * @param $min_time + * @param $max_time + * + * @return array|bool|mixed + */ + private function getHistory($type, $start, $limit, $min_time, $max_time) + { + if (! isset($start) || ! isset($limit) || ! isset($min_time) || ! isset($max_time)) { + return false; + } + $options = ['start' => $start, 'limit' => $limit, 'min_time' => $min_time, 'max_time' => $max_time]; + + return $this->_sendRequest($type, $options); + } + + /** + * Get a list of surveys. + * + * @return array|mixed + */ + public function getSurveys() + { + return $this->_sendRequest('get_surveys'); + } + + /** + * Get a deatils of a survey. + * + * @return array|mixed + */ + public function getSurveyDetails() + { + $options = ['survey_id' => $surveyid]; + + return $this->_sendRequest('get_survey_details'); + } + + /** + * Get a the results of a given survey. + * + * @return array|mixed + */ + public function getSurveyResults($surveyid, $start, $end) + { + $options = ['survey_id' => $surveyid, 'start_date' => $start, 'end_date' => $end]; + + return $this->_sendRequest('get_surveys', $options); + } + + /** + * Get all account optouts. + * + * @return array|mixed + */ + public function getOptouts($time = null) + { + return $this->_sendRequest('get_optouts'); + } + + /** + * Set unicode mode + * + * @param bool $mode + * @return \NotificationChannels\Textlocal\Textlocal + */ + public function setUnicodeMode(bool $mode) + { + $this->treatAsUnicode = (int) $mode; + return $this; + } +} + +class Contact +{ + public $number; + public $first_name; + public $last_name; + public $custom1; + public $custom2; + public $custom3; + + public $groupID; + + /** + * Structure of a contact object. + * + * @param $number + * @param string $firstname + * @param string $lastname + * @param string $custom1 + * @param string $custom2 + * @param string $custom3 + */ + public function __construct($number, $firstname = '', $lastname = '', $custom1 = '', $custom2 = '', $custom3 = '') + { + $this->number = $number; + $this->first_name = $firstname; + $this->last_name = $lastname; + $this->custom1 = $custom1; + $this->custom2 = $custom2; + $this->custom3 = $custom3; + } +} diff --git a/src/TextlocalChannel.php b/src/TextlocalChannel.php new file mode 100644 index 00000000..7d155a7f --- /dev/null +++ b/src/TextlocalChannel.php @@ -0,0 +1,110 @@ +sender = config('textlocal.sender'); + } + + /** + * Send the given notification. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * + * @throws \NotificationChannels\Textlocal\Exceptions\CouldNotSendNotification + */ + public function send($notifiable, Notification $notification) + { + // Get the mobile number/s from the model + if (! $numbers = $notifiable->routeNotificationFor('Textlocal')) { + return; + } + + if (empty($numbers)) { + return; + } + + if (!is_array($numbers)) { + $numbers = [$numbers]; + } + + // Get the message from the notification class + $message = (string) $notification->toSms($notifiable); + + if (empty($message)) { + return; + } + + // Get unicode parameter from notification class + $unicode = false; + if (method_exists($notification, 'getUnicodeMode')) { + $unicode = $notification->getUnicodeMode(); + } + + if (method_exists($notification, 'getSenderId')) { + $this->sender = $notification->getSenderId($notifiable); + } + + $client = $this->getClient($notifiable, $notification); + + try { + $response = $client + ->setUnicodeMode($unicode) + ->sendSms($numbers, $message, $this->sender); + + return $response; + } catch (\Exception $exception) { + throw CouldNotSendNotification::serviceRespondedWithAnError($exception, $message); + } + } + + public function getClient($notifiable, Notification $notification) + { + $client = $this->client; + + if ($notifiable instanceof IUsesTextlocalClientConfig) { + + if (! $notifiable->shouldUseCustomTextlocalConfig($notification)) { + return $client; + } + + [$username, $hash, $apiKey, $country] = $notifiable->getTextlocalClientConfig($notification); + + $client = new Textlocal($username, $hash, $apiKey, $country); + } + + if ($notification instanceof INotificationUsesTextlocalClientConfig) { + + if (! $notification->shouldUseCustomTextlocalConfig($notification)) { + return $client; + } + + [$username, $hash, $apiKey, $country] = $notification->getTextlocalClientConfig($notifiable); + + $client = new Textlocal($username, $hash, $apiKey, $country); + } + + return $client; + } +} diff --git a/src/TextlocalServiceProvider.php b/src/TextlocalServiceProvider.php new file mode 100644 index 00000000..ef02a7cc --- /dev/null +++ b/src/TextlocalServiceProvider.php @@ -0,0 +1,52 @@ +app->when(TextlocalChannel::class) + ->needs(Textlocal::class) + ->give( + function () { + $config = config('textlocal'); + + return new Textlocal( + $config['username'], + $config['hash'], + $config['api_key'], + $config['country'] + ); + } + ); + + $this->publishConfiguration(); + } + + /** + * Register the application services. + */ + public function register() + { + $config = __DIR__ . '/../config/textlocal.php'; + + $this->mergeConfigFrom($config, 'textlocal'); + } + + public function publishConfiguration() + { + $path = realpath(__DIR__.'/../config/textlocal.php'); + + $this->publishes([ + $path => config_path('textlocal.php') + ], 'textlocal'); + } +} diff --git a/styleci.yml b/styleci.yml new file mode 100644 index 00000000..0285f179 --- /dev/null +++ b/styleci.yml @@ -0,0 +1 @@ +preset: laravel diff --git a/tests/ExampleTest.php b/tests/ExampleTest.php new file mode 100644 index 00000000..b2cb7d5e --- /dev/null +++ b/tests/ExampleTest.php @@ -0,0 +1,12 @@ +assertTrue(true); + } +} diff --git a/travis.yml b/travis.yml new file mode 100644 index 00000000..1ca768d9 --- /dev/null +++ b/travis.yml @@ -0,0 +1,24 @@ +language: php + +php: + - 7.0 + - 7.1 + - 7.2 + - 7.3 + - 7.4 + +env: + matrix: + - COMPOSER_FLAGS="--prefer-lowest" + - COMPOSER_FLAGS="" + +before_script: + - travis_retry composer self-update + - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source + +script: + - phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover