├── composer.json ├── exemplo ├── dispositivo │ ├── alterar_dispositivo.php │ └── cria_dispositivo.php └── notificacao │ ├── enviar_notificacao_por_device.php │ ├── enviar_notificacao_por_tag.php │ └── enviar_notificacao_todos.php ├── readme.md └── src ├── CURL.php ├── Device.php ├── Exceptions └── OneSignalException.php ├── Notification.php └── OneSignal.php /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "carloswgama/php-onesignal", 3 | "description": "Enviar Push Notification usando One Signal", 4 | "type": "library", 5 | "license": "MIT", 6 | "version": "1.0.0", 7 | "authors": [ 8 | { 9 | "name": "Carlos W. Gama", 10 | "email": "carloswgama@gmail.com" 11 | } 12 | ], 13 | "require": { 14 | "php": ">=5.3.0" 15 | }, 16 | "autoload" : { 17 | "psr-4": { 18 | "CWG\\OneSignal\\": "src/" 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /exemplo/dispositivo/alterar_dispositivo.php: -------------------------------------------------------------------------------- 1 | device->setLanguage('pt') 18 | ->setIdentifier('12312312313') 19 | ->setDevice(Device::ANDROID) 20 | ->addTag('matricula', '11') 21 | ->update($deviceID); 22 | 23 | 24 | print_r($retorno); -------------------------------------------------------------------------------- /exemplo/dispositivo/cria_dispositivo.php: -------------------------------------------------------------------------------- 1 | device->setLanguage('pt') 17 | ->setIdentifier('12312312313') 18 | ->setDevice(Device::ANDROID) 19 | ->addTag('matricula', '11111111') 20 | ->addTag('curso', '12312312') 21 | ->addTag('turma', '1111') 22 | ->create(); 23 | 24 | 25 | print_r($retorno); 26 | 27 | -------------------------------------------------------------------------------- /exemplo/notificacao/enviar_notificacao_por_device.php: -------------------------------------------------------------------------------- 1 | notification->setBody('Ola') 17 | ->setTitle('Titulo') 18 | ->addDevice($deviceID) 19 | ->send(); 20 | print_r($retorno); 21 | -------------------------------------------------------------------------------- /exemplo/notificacao/enviar_notificacao_por_tag.php: -------------------------------------------------------------------------------- 1 | notification->setBody('Ola') 16 | ->setTitle('Titulo') 17 | ->addTag('matricula', '11111111') 18 | ->send(); 19 | print_r($retorno); 20 | -------------------------------------------------------------------------------- /exemplo/notificacao/enviar_notificacao_todos.php: -------------------------------------------------------------------------------- 1 | notification->setBody('Ola') 17 | ->setTitle('Titulo') 18 | ->send(); 19 | print_r($retorno); 20 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # PHP - OneSignal 2 | Classe facilitar o uso do OneSignal para Push Notifications com PHP 3 | 4 | ## Obtendo a Chave do Servidor 5 | 6 | Primeiro será necessário criar a conta no 7 | [One Signal](https://onesignal.com) 8 | 9 | Após criar uma nova conta, crie um novo aplicativo, acesse o aplicativo, e escolha a opção App Settings. 10 | ![App Settings](http://carloswgama.com.br/onesignal/app_settings.jpg) 11 | 12 | Nela haverá a opção de baixar o ID do APP e a Key da REST API 13 | ![Keys](http://carloswgama.com.br/onesignal/keys_ids.jpg) 14 | 15 | 16 | ## Baixando o projeto 17 | 18 | Para usar esse projeto, basta baixar esse repositório em seu projeto e importar as classes em src/ ou usar o composer que é o mais indicado: 19 | 20 | ``` 21 | composer require carloswgama/php-onesignal:1.* 22 | ``` 23 | 24 | Caso seu projeto já possua um arquivo composer.json, você pode também adiciona-lo nas dependências require e rodar um composer install: 25 | ``` 26 | { 27 | "require": { 28 | "carloswgama/php-onesignal": "1.*" 29 | } 30 | } 31 | ``` 32 | 33 | ## Exemplos 34 | 35 | Abaixo segue alguns exemplos de como usar a classe 36 | 37 | 38 | ### Cadastrando um Dispositivo 39 | ``` php 40 | device->setLanguage('pt') 53 | ->setIdentifier('12312312313') 54 | ->setDevice(Device::ANDROID) 55 | ->addTag('matricula', '11111111') 56 | ->addTag('curso', '12312312') 57 | ->addTag('turma', '1111') 58 | ->create(); 59 | 60 | 61 | print_r($retorno); 62 | ``` 63 | 64 | ### Alterando Dispositivo 65 | 66 | ``` php 67 | device->setLanguage('pt') 81 | ->setIdentifier('12312312313') 82 | ->setDevice(Device::ANDROID) 83 | ->addTag('matricula', '11') 84 | ->update($deviceID); 85 | 86 | 87 | print_r($retorno); 88 | ``` 89 | 90 | ### Enviando notificação para todos dispositivos 91 | 92 | ``` php 93 | notification->setBody('Ola') 105 | ->setTitle('Titulo') 106 | ->send(); 107 | print_r($retorno); 108 | ``` 109 | 110 | ### Enviando notificação baseado em tags 111 | 112 | ``` php 113 | notification->setBody('Ola') 125 | ->setTitle('Titulo') 126 | ->addTag('categoria', 'esporte') 127 | ->addTag('categoria', 'natacao') 128 | ->send(); 129 | print_r($retorno); 130 | ``` 131 | 132 | ### Enviando notificação baseado no dispositivo 133 | ``` php 134 | notification->setBody('Ola') 146 | ->setTitle('Titulo') 147 | ->addDevice($deviceID) 148 | ->send(); 149 | ``` 150 | 151 | --- 152 | **Autor:** Carlos W. Gama *(carloswgama@gmail.com)* 153 | **Licença:** MIT 154 | 155 | Livre para usar, modificar como desejar e destribuir como quiser -------------------------------------------------------------------------------- /src/CURL.php: -------------------------------------------------------------------------------- 1 | key = $key; 58 | } 59 | /** 60 | * @access public 61 | * @param $url string 62 | * @param $dados array 63 | * @param $method GET|POST|PUT|DELETE 64 | * @return json 65 | */ 66 | protected function openCurl($url, $dados = array(), $method = 'GET') { 67 | 68 | if (is_array($dados)) $dados = json_encode($dados); 69 | //print_r($dados); 70 | $ch = curl_init(); 71 | curl_setopt($ch, CURLOPT_URL, $this->api.$url); 72 | curl_setopt($ch, CURLOPT_HTTPHEADER, [ 73 | 'Content-Type: application/json; charset=utf-8', 74 | 'Authorization: Basic '.$this->key] 75 | ); 76 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 77 | curl_setopt($ch, CURLOPT_HEADER, FALSE); 78 | curl_setopt($ch, CURLOPT_POSTFIELDS, $dados); 79 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 80 | 81 | switch($method) { 82 | case 'POST': 83 | curl_setopt($ch, CURLOPT_POST, TRUE); 84 | break; 85 | case 'PUT': 86 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 87 | break; 88 | case 'DELETE': 89 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); 90 | break; 91 | } 92 | curl_setopt($ch, CURLOPT_POST, TRUE); 93 | 94 | 95 | $response = curl_exec($ch); 96 | curl_close($ch); 97 | 98 | $retorno = json_decode($response, true); 99 | return $retorno; 100 | } 101 | 102 | /** 103 | * @access public 104 | * @param $url string 105 | * @return json 106 | */ 107 | public function get($url) { 108 | return $this->openCurl($url); 109 | } 110 | 111 | /** 112 | * @access public 113 | * @param $url string 114 | * @param $dados array() 115 | * @return json 116 | */ 117 | public function post($url, $dados = array()) { 118 | return $this->openCurl($url, $dados, "POST"); 119 | } 120 | 121 | /** 122 | * @access public 123 | * @param $url string 124 | * @param $dados array() 125 | * @return json 126 | */ 127 | public function put($url, $dados = array()) { 128 | return $this->openCurl($url, $dados, "PUT"); 129 | } 130 | 131 | /** 132 | * @access public 133 | * @param $url string 134 | * @param $dados array() 135 | * @return json 136 | */ 137 | public function delete($url, $dados = array()) { 138 | return $this->openCurl($url, $dados, "DELETE"); 139 | } 140 | } 141 | 142 | ?> -------------------------------------------------------------------------------- /src/Device.php: -------------------------------------------------------------------------------- 1 | 5 | * @category Library 6 | * @version 1.0.0 7 | * @license MIT 8 | * @link https://documentation.onesignal.com/v3.0/reference#add-a-device 9 | */ 10 | namespace CWG\OneSignal; 11 | 12 | use CWG\OOneSignal\Exception\OneSignalException; 13 | use CWG\OneSignal\Notification; 14 | 15 | class Device { 16 | 17 | // ENUMS // 18 | const IOS = 0; 19 | const ANDROID = 1; 20 | const AMAZON = 2; 21 | const WINDOWSPHONE = 3; 22 | const CHROMEAPP = 4; 23 | const CHROMEWEB = 5; 24 | const SAFARI = 7; 25 | const FIREFOX = 8; 26 | const MACOS = 9; 27 | 28 | /** 29 | * Objeto que irá enviar as requisições 30 | * @access private 31 | * @var CURL 32 | */ 33 | private $curl; 34 | 35 | /** 36 | * ID da API 37 | * @access private 38 | * @var string 39 | */ 40 | private $appID; 41 | 42 | private $campos = [ ]; 43 | 44 | public function __construct($appID) { 45 | $this->curl = CURL::getInstance(); 46 | $this->appID = $appID; 47 | } 48 | 49 | /** 50 | * Adiciona o UUID do dispotivo 51 | * @param $id string 52 | * @return Device 53 | */ 54 | public function setIdentifier($id) { 55 | $this->campos['identifier'] = $id; 56 | return $this; 57 | } 58 | 59 | /** 60 | * Informa o Idioma padrão 61 | * @param $lang string 62 | * @return Device 63 | */ 64 | public function setLanguage($lang) { 65 | $this->campos['language'] = $lang; 66 | return $this; 67 | } 68 | 69 | /** 70 | * Informa o tipo ed dispotivo 71 | * @param $type int IOS|ANDROID|WINDOWSPHONE 72 | * @return Device 73 | */ 74 | public function setDevice($type) { 75 | $this->campos['device_type'] = $type; 76 | return $this; 77 | } 78 | 79 | /** 80 | * Adiciona uma tag ao dispositivo 81 | * @param $name o nome da tag 82 | * @param $value o valor da tag 83 | * @return Device 84 | */ 85 | public function addTag($name, $value) { 86 | $this->campos['tags'][$name] = $value; 87 | return $this; 88 | } 89 | 90 | 91 | /** 92 | * Cria um novo dispositivo 93 | * @uses $api->device->addTag('info', 'teste')->create('69aeecc1-7b58-44d1-8000-7767de437adf'); 94 | * @param $campos array; 95 | */ 96 | public function create($campos = null) { 97 | if ($campos != null) $this->campos = $campos; 98 | 99 | $this->campos['app_id'] = $this->appID; 100 | 101 | if (empty($this->campos['identifier'])) throw new OneSignalException; 102 | if (empty($this->campos['language'])) $campos['language'] = 'pt'; 103 | if (empty($this->campos['device_type'])) $campos['device_type'] = SELF::ANDROID; 104 | 105 | return $this->curl->post('players', $this->campos); 106 | } 107 | 108 | /** 109 | * Atualiza uma dispositivo 110 | * @uses $api->device->addTag('info', 'teste')->update('69aeecc1-7b58-44d1-8000-7767de437adf'); 111 | * @param $deviceID string 112 | * @param $campos array; 113 | * @return array 114 | */ 115 | public function update($deviceID, $campos = null) { 116 | if ($campos != null) $this->campos = $campos; 117 | $this->campos['app_id'] = $this->appID; 118 | 119 | return $this->curl->put('players/' . $deviceID, $this->campos); 120 | } 121 | 122 | /** 123 | * Busca um dispositivo 124 | * @uses $api->device->getDevice('69aeecc1-7b58-44d1-8000-7767de437adf'); 125 | * @param $deviceID string 126 | * @return array 127 | */ 128 | public function getDevice($deviceID) { 129 | return $this->curl->put('players/' . $deviceID . '?app_id='. $this->appID); 130 | } 131 | 132 | /** 133 | * O ID da APP 134 | * @param $appID string 135 | */ 136 | private function setAppID($appID) { 137 | $this->appID = $appID; 138 | } 139 | 140 | } -------------------------------------------------------------------------------- /src/Exceptions/OneSignalException.php: -------------------------------------------------------------------------------- 1 | 5 | * @category Library 6 | * @version 1.0.0 7 | * @license MIT 8 | * @link https://documentation.onesignal.com/v3.0/reference#create-notification 9 | */ 10 | namespace CWG\OneSignal; 11 | 12 | use CWG\OOneSignal\Exception\OneSignalException; 13 | use CWG\OneSignal\Notification; 14 | 15 | class Notification { 16 | 17 | /** 18 | * Objeto que irá enviar as requisições 19 | * @access private 20 | * @var CURL 21 | */ 22 | private $curl; 23 | 24 | /** 25 | * ID da API 26 | * @access private 27 | * @var string 28 | */ 29 | private $appID; 30 | 31 | private $campos = [ ]; 32 | 33 | public function __construct($appID) { 34 | $this->curl = CURL::getInstance(); 35 | $this->appID = $appID; 36 | } 37 | 38 | /** 39 | * Seta o Segmento que irá receber a notificação 40 | * @param $segments array 41 | * @return Device 42 | */ 43 | public function setSegment($segments) { 44 | if (!is_array($segments)) $segments = [$segments]; 45 | $this->campos['included_segments'] = $segments; 46 | return $this; 47 | } 48 | 49 | /** 50 | * Adicionar um segmento que irá receber a notificação 51 | * @param $segment string 52 | * @return Device 53 | */ 54 | public function addSegment($segment) { 55 | $this->campos['included_segments'][] = $segment; 56 | return $this; 57 | } 58 | 59 | 60 | /** 61 | * Adicionar um dispositivo que irá receber a notificação 62 | * @param $segment string 63 | * @return Device 64 | */ 65 | public function addDevice($deviceID) { 66 | $this->campos['include_player_ids'][] = $deviceID; 67 | return $this; 68 | } 69 | 70 | 71 | /** 72 | * Adicionar uma tag que irá receber a notificação 73 | * @param $segment string 74 | * @return Device 75 | */ 76 | public function addTag($campo, $valor) { 77 | $tag = [ 78 | 'field' => 'tag', 79 | 'key' => $campo, 80 | 'relation' => '=', 81 | 'value' => $valor 82 | ]; 83 | 84 | if (isset($this->campos['filters']) && count($this->campos['filters']) > 0) 85 | $this->campos['filters'][] = ['operator' => 'OR']; 86 | $this->campos['filters'][] = $tag; 87 | 88 | return $this; 89 | } 90 | 91 | /** 92 | * Seta os conteúdos enviados para o servidor 93 | * @param $contents array com as informações 94 | * @param $lang no idioma informado 95 | * @param Notification 96 | */ 97 | public function setBody($contents, $lang = 'pt') { 98 | $this->campos['contents'][$lang] = $contents; 99 | if (!isset($this->campos['contents']['en'])) 100 | $this->campos['contents']['en'] = $contents; 101 | return $this; 102 | } 103 | 104 | /** 105 | * Seta um conteúdo adicional a ser recebido no destinatário 106 | * @param $data array com as informações 107 | * @return Notification 108 | */ 109 | public function setAdditionalData(array $data) { 110 | if($data && is_array($data)){ 111 | $this->campos['data'] = $data; 112 | } 113 | return $this; 114 | } 115 | 116 | /** 117 | * Seta o título do conteúdo 118 | * @param $contents array com as informações 119 | * @param $lang no idioma informado 120 | * @param Notification 121 | */ 122 | public function setTitle($title, $lang = 'pt') { 123 | $this->campos['headings'][$lang] = $title; 124 | if (!isset($this->campos['headings']['en'])) 125 | $this->campos['headings']['en'] = $title; 126 | return $this; 127 | } 128 | 129 | /** 130 | * Cria um novo dispositivo 131 | * @param $campos array; 132 | */ 133 | public function send($campos = null) { 134 | if ($campos != null) $this->campos = $campos; 135 | 136 | $this->campos['app_id'] = $this->appID; 137 | 138 | //Se não seleciona para quem enviar, então via para todos 139 | if (empty($this->campos['included_segments']) && empty($this->campos['filters']) && empty($this->campos['include_player_ids'])) 140 | $this->campos['included_segments'] = ['All']; 141 | 142 | return $this->curl->post('notifications', $this->campos); 143 | } 144 | 145 | /** 146 | * Deleta uma notificação 147 | * @param $campos array; 148 | */ 149 | public function cancel($deviceID) { 150 | return $this->curl->delete('notifications/' . $notificationID.'?app_id=' . $this->appID); 151 | } 152 | 153 | /** 154 | * O ID da APP 155 | * @param $appID string 156 | */ 157 | private function setAppID($appID) { 158 | $this->appID = $appID; 159 | } 160 | 161 | } -------------------------------------------------------------------------------- /src/OneSignal.php: -------------------------------------------------------------------------------- 1 | 5 | * @category Core 6 | * @version 1.0.0 7 | * @license MIT 8 | */ 9 | namespace CWG\OneSignal; 10 | 11 | use CWG\OneSignal\Notification; 12 | use CWG\OneSignal\Device; 13 | use CWG\OneSignal\CURL; 14 | 15 | class OneSignal { 16 | 17 | 18 | private $notification; 19 | private $device; 20 | 21 | public function __construct($appID, $authorizationID) { 22 | $this->notification = new Notification($appID); 23 | $this->device = new Device($appID); 24 | 25 | $curl = CURL::getInstance(); 26 | $curl->setAuthorization($authorizationID); 27 | } 28 | 29 | /** 30 | * O ID da APP 31 | * @param $appID string 32 | */ 33 | private function setAppID($appID) { 34 | $this->notification->setAppID($appID); 35 | $this->device->setAppID($appID); 36 | } 37 | 38 | /** 39 | * Usa um Getter para permitir recuperar os objetos de notificação e device 40 | */ 41 | public function __get($field) { 42 | if (isset($this->$field)) 43 | return $this->$field; 44 | } 45 | 46 | } --------------------------------------------------------------------------------