├── .gitignore ├── examples ├── sendTextMessage.php ├── uploadFile.php ├── sendPictureByUpload.php ├── sendPictureByLink.php ├── uploadFile-sendFileByUrl.php ├── createGroupAndSendMessage.php ├── receiveNotification.php └── statusesExample.php ├── composer.json ├── src ├── tools │ ├── Marking.php │ ├── Queues.php │ ├── Webhooks.php │ ├── Journals.php │ ├── Receiving.php │ ├── Account.php │ ├── Statuses.php │ ├── Groups.php │ ├── ServiceMethods.php │ └── Sending.php └── GreenApiClient.php ├── LICENSE ├── README_RUS.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | /composer.lock 3 | /composer.phar 4 | /.idea 5 | /.history 6 | /.vscode 7 | -------------------------------------------------------------------------------- /examples/sendTextMessage.php: -------------------------------------------------------------------------------- 1 | sending->sendMessage('11001234567@c.us', 'Message text'); 12 | 13 | print_r( $result->data ); 14 | -------------------------------------------------------------------------------- /examples/uploadFile.php: -------------------------------------------------------------------------------- 1 | sending->uploadFile( 12 | 'C:\Games\PicFromDisk.png' 13 | ); 14 | 15 | print_r( $result->data ); 16 | -------------------------------------------------------------------------------- /examples/sendPictureByUpload.php: -------------------------------------------------------------------------------- 1 | sending->sendFileByUpload( 12 | '11001234567@c.us', 13 | 'C:\Games\PicFromDisk.png', 14 | 'PicFromDisk.jpg', 15 | 'Picture from disk' 16 | ); 17 | 18 | print_r( $result->data ); 19 | -------------------------------------------------------------------------------- /examples/sendPictureByLink.php: -------------------------------------------------------------------------------- 1 | sending->sendFileByUrl( 12 | '11001234567@c.us', 13 | 'https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 14 | 'googlelogo_color_272x92dp.png', 15 | 'Google logo' 16 | ); 17 | 18 | print_r( $result->data ); 19 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "green-api/whatsapp-api-client-php", 3 | "description": "Green-api.com REST API Client", 4 | "keywords": [ 5 | "green-api.com", 6 | "whatsapp", 7 | "rest", 8 | "private api", 9 | "api" 10 | ], 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "Green-api.com", 15 | "email": "support@green-api.com" 16 | } 17 | ], 18 | "require": { 19 | "ext-curl": "*", 20 | "php": ">=7.0", 21 | "ext-json": "*", 22 | "ext-fileinfo": "*" 23 | }, 24 | "autoload": { 25 | "psr-4": { 26 | "GreenApi\\RestApi\\": "src/" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /examples/uploadFile-sendFileByUrl.php: -------------------------------------------------------------------------------- 1 | sending->uploadFile( 12 | 'C:\Games\PicFromDisk.png' 13 | ); 14 | 15 | print_r( $result->data ); 16 | 17 | $result = $greenApi->sending->sendFileByUrl( 18 | '11001234567@c.us', 19 | $result->data->urlFile, 20 | 'googlelogo_color_272x92dp.png', 21 | 'Google logo' 22 | ); 23 | 24 | print_r( $result->data ); 25 | -------------------------------------------------------------------------------- /examples/createGroupAndSendMessage.php: -------------------------------------------------------------------------------- 1 | groups->createGroup('GroupName', $chatIds ); 16 | 17 | if ($resultCreate->code == 200) { 18 | print_r($resultCreate->data).PHP_EOL; 19 | $resultSend = $greenApi->sending->sendMessage($resultCreate->data->chatId, 'Message text'); 20 | if ($resultSend->code == 200) 21 | print_r( $resultSend->data ) . PHP_EOL; 22 | else 23 | print( $resultSend->error ) . PHP_EOL; 24 | } else 25 | print( $resultCreate->error ) . PHP_EOL; 26 | -------------------------------------------------------------------------------- /src/tools/Marking.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * The method returns the chat message history. 21 | * 22 | * @param string $chatId 23 | * @param string $idMessage 24 | * 25 | * @return stdClass 26 | * @link https://green-api.com/en/docs/api/marks/ReadChat/ 27 | */ 28 | public function readChat( string $chatId, string $idMessage ): stdClass { 29 | 30 | $requestBody = [ 31 | 'chatId' => $chatId, 32 | 'idMessage' => $idMessage, 33 | ]; 34 | 35 | return $this->greenApi->request( 'POST', 36 | '{{host}}/waInstance{{idInstance}}/ReadChat/{{apiTokenInstance}}', $requestBody ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Green API 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/tools/Queues.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * @return stdClass 21 | * @link https://green-api.com/en/docs/api/queues/ClearMessagesQueue/ 22 | */ 23 | public function clearMessagesQueue(): stdClass { 24 | 25 | return $this->greenApi->request( 'GET', 26 | '{{host}}/waInstance{{idInstance}}/ClearMessagesQueue/{{apiTokenInstance}}' ); 27 | } 28 | 29 | /** 30 | * The method is aimed for getting a list of messages in the queue to be sent. Messages sending rate is managed by 31 | * Messages sending delay parameter.' 32 | * 33 | * @return stdClass 34 | * @link https://green-api.com/en/docs/api/queues/ShowMessagesQueue/ 35 | */ 36 | public function showMessagesQueue(): stdClass { 37 | 38 | return $this->greenApi->request( 'GET', 39 | '{{host}}/waInstance{{idInstance}}/ShowMessagesQueue/{{apiTokenInstance}}' ); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/tools/Webhooks.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 18 | } 19 | 20 | public function startReceivingNotifications( $onEvent ) { 21 | $this->started = true; 22 | $this->job( $onEvent ); 23 | } 24 | 25 | public function stopReceivingNotifications() { 26 | $this->started = false; 27 | } 28 | 29 | public function job( $onEvent ) { 30 | print( 'Incoming notifications are being received.' ) . PHP_EOL; 31 | 32 | while ( $this->started ) { 33 | $resultReceive = $this->greenApi->receiving->receiveNotification(); 34 | if ( $resultReceive->code == 200 ) { 35 | if ( empty( $resultReceive->data ) ) { 36 | # There are no incoming notifications, 37 | # we send the request again 38 | continue; 39 | } 40 | $body = $resultReceive->data->body; 41 | $typeWebhook = $body->typeWebhook; 42 | $onEvent( $typeWebhook, $body ); 43 | $this->greenApi->receiving->deleteNotification( $resultReceive->data->receiptId ); 44 | continue; 45 | } 46 | sleep(1); 47 | } 48 | print( 'End receiving' ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /examples/receiveNotification.php: -------------------------------------------------------------------------------- 1 | webhooks->startReceivingNotifications(function($typeWebhook, $body) { 13 | if ($typeWebhook == 'incomingMessageReceived') { 14 | onIncomingMessageReceived($body); 15 | } elseif ($typeWebhook == 'incomingCall') { 16 | onIncomingCall($body); 17 | } elseif ($typeWebhook == 'outgoingAPIMessageReceived') { 18 | onOutgoingAPIMessageReceived($body); 19 | } elseif ($typeWebhook == 'outgoingMessageReceived') { 20 | onOutgoingMessageReceived($body); 21 | } elseif ($typeWebhook == 'outgoingMessageStatus') { 22 | onOutgoingMessageStatus($body); 23 | } elseif ($typeWebhook == 'stateInstanceChanged') { 24 | onStateInstanceChanged($body); 25 | } elseif ($typeWebhook == 'statusInstanceChanged') { 26 | onStatusInstanceChanged($body); 27 | } 28 | }); 29 | 30 | function onIncomingMessageReceived($body) { 31 | $idMessage = $body->idMessage; 32 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 33 | $senderData = $body->senderData; 34 | $messageData = $body->messageData; 35 | print($idMessage . ': At ' . $eventDate . ' Incoming from '. json_encode($senderData, JSON_UNESCAPED_UNICODE) . ' message = ' . json_encode($messageData, JSON_UNESCAPED_UNICODE)).PHP_EOL; 36 | } 37 | 38 | function onIncomingCall($body) { 39 | $idMessage = $body->idMessage; 40 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 41 | $fromWho = $body->from; 42 | print($idMessage . ': Call from ' . $fromWho . ' at ' . $eventDate).PHP_EOL; 43 | } 44 | 45 | function onOutgoingAPIMessageReceived($body) { 46 | $idMessage = $body->idMessage; 47 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 48 | $senderData = $body->senderData; 49 | $messageData = $body->messageData; 50 | print($idMessage . ': At ' . $eventDate . ' Incoming from '. json_encode($senderData, JSON_UNESCAPED_UNICODE) . ' message = ' . json_encode($messageData, JSON_UNESCAPED_UNICODE)).PHP_EOL; 51 | } 52 | 53 | function onOutgoingMessageReceived($body) { 54 | $idMessage = $body->idMessage; 55 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 56 | $senderData = $body->senderData; 57 | $messageData = $body->messageData; 58 | print($idMessage . ': At ' . $eventDate . ' Outgoing from '. json_encode($senderData, JSON_UNESCAPED_UNICODE) . ' message = ' . json_encode($messageData, JSON_UNESCAPED_UNICODE)).PHP_EOL; 59 | } 60 | 61 | function onOutgoingMessageStatus($body) { 62 | $idMessage = $body->idMessage; 63 | $status = $body->status; 64 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 65 | print($idMessage . ': At ' . $eventDate . ' status = ' . $status).PHP_EOL; 66 | } 67 | 68 | function onStateInstanceChanged($body) { 69 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 70 | $stateInstance = $body->stateInstance; 71 | print('At ' . $eventDate . ' state instance = ' . $stateInstance).PHP_EOL; 72 | } 73 | 74 | function onStatusInstanceChanged($body) { 75 | $eventDate = date('Y-m-d H:i:s', $body->timestamp); 76 | $statusInstance = $body->stateInstance; 77 | print('At ' . $eventDate . ' status instance = ' . $statusInstance).PHP_EOL; 78 | } 79 | -------------------------------------------------------------------------------- /src/tools/Journals.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 18 | } 19 | 20 | /** 21 | * The method returns the chat message history. 22 | * 23 | * @param string $chatId 24 | * @param int|null $count 25 | * 26 | * @return stdClass 27 | * 28 | * @link https://green-api.com/en/docs/api/journals/GetChatHistory/ 29 | */ 30 | public function getChatHistory(string $chatId, int $count = null): stdClass 31 | { 32 | $requestBody = [ 33 | 'chatId' => $chatId, 34 | ]; 35 | 36 | if ($count) { 37 | $requestBody['count'] = $count; 38 | } 39 | 40 | return $this->greenApi->request( 41 | 'POST', '{{host}}/waInstance{{idInstance}}/GetChatHistory/{{apiTokenInstance}}', $requestBody 42 | ); 43 | } 44 | 45 | /** 46 | * The method returns the chat message. 47 | * 48 | * @param string $chatId 49 | * @param string $idMessage 50 | * 51 | * @return stdClass 52 | * 53 | * @link https://green-api.com/en/docs/api/journals/GetMessage/ 54 | */ 55 | public function getMessage(string $chatId, string $idMessage): stdClass 56 | { 57 | $requestBody = [ 58 | 'chatId' => $chatId, 59 | 'idMessage' => $idMessage, 60 | ]; 61 | 62 | return $this->greenApi->request( 63 | 'POST', '{{host}}/waInstance{{idInstance}}/getMessage/{{apiTokenInstance}}', $requestBody 64 | ); 65 | } 66 | 67 | /** 68 | * The method returns the chat message history. 69 | * 70 | * @param int|null $minutes 71 | * 72 | * @return stdClass 73 | * 74 | * @link https://green-api.com/en/docs/api/journals/LastIncomingMessages/ 75 | */ 76 | public function lastIncomingMessages(int $minutes = null): stdClass 77 | { 78 | $requestBody = null; 79 | 80 | if ($minutes) { 81 | $requestBody['minutes'] = $minutes; 82 | } 83 | 84 | return $this->greenApi->request( 85 | 'GET', '{{host}}/waInstance{{idInstance}}/LastIncomingMessages/{{apiTokenInstance}}', $requestBody 86 | ); 87 | } 88 | 89 | /** 90 | * The method returns the last outgoing messages of the account. 91 | * Outgoing messages are stored on the server for 24 hours. 92 | * 93 | * @param int|null $minutes 94 | * 95 | * @return stdClass 96 | * 97 | * @link https://green-api.com/en/docs/api/journals/LastOutgoingMessages/ 98 | */ 99 | public function lastOutgoingMessages(int $minutes = null): stdClass 100 | { 101 | $requestBody = null; 102 | 103 | if ($minutes) { 104 | $requestBody['minutes'] = $minutes; 105 | } 106 | 107 | return $this->greenApi->request( 108 | 'GET', '{{host}}/waInstance{{idInstance}}/LastOutgoingMessages/{{apiTokenInstance}}', $requestBody 109 | ); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/tools/Receiving.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * The method is aimed for downloading incoming and outgoing files. Links to incoming files are transmitted 21 | * in Incoming messages, and you can also get them using LastIncomingMessages method. You can get links to outgoing 22 | * files using LastOutgoingMessages method.Files storage period and, accordingly, the capability to download 23 | * them is limited to 24 hours. 24 | * 25 | * @param string $chatId 26 | * @param string $idMessage 27 | * 28 | * @return stdClass 29 | */ 30 | public function downloadFile( string $chatId, string $idMessage ): stdClass { 31 | 32 | $requestBody = [ 33 | 'chatId' => $chatId, 34 | 'idMessage' => $idMessage, 35 | ]; 36 | 37 | return $this->greenApi->request( 'POST', 38 | '{{host}}/waInstance{{idInstance}}/DownloadFile/{{apiTokenInstance}}', $requestBody ); 39 | } 40 | 41 | /** 42 | * The method is aimed for receiving one incoming notification from the notifications queue. ReceiveNotification 43 | * method waits for a notification receipt for 20 sec. The method call ends with an empty response if a timeout is 44 | * reached. If a notification comes to the queue within 20 seconds, the method call is completed, and the method 45 | * returns the received notification.After receiving and processing an incoming notification, you need to delete the 46 | * notification from the queue. This requires you to run DeleteNotification method. After calling DeleteNotification 47 | * method, the notification will be considered received and processed and will be permanently deleted from the queue. 48 | * Therefore, the next call of ReceiveNotification method will return the next notification from the queue in the 49 | * order in which notifications come to the queue.Incoming notifications are stored in the queue for 24 hours. 50 | * Notifications are sent from the queue in FIFO order 51 | * 52 | * @return stdClass 53 | * @link https://green-api.com/en/docs/api/receiving/technology-http-api/ReceiveNotification/ 54 | */ 55 | public function receiveNotification(): stdClass { 56 | 57 | return $this->greenApi->request( 'GET', 58 | '{{host}}/waInstance{{idInstance}}/ReceiveNotification/{{apiTokenInstance}}' ); 59 | } 60 | 61 | /** 62 | * The method is aimed for deleting an incoming notification from the notification queue. To specify what notification 63 | * to delete, use receiptId parameter. After receiving and processing an incoming notification, you need to delete 64 | * the notification from the queue. This requires you to run this method. After calling the method, the notification 65 | * will be considered received and processed and will be permanently deleted from the queue. Therefore, the next call 66 | * of ReceiveNotification method will return the next notification from the queue in the order in which notifications 67 | * come to the queue.Incoming notifications are stored in the queue for 24 hours.Notifications are sent from the 68 | * queue in FIFO order 69 | * 70 | * @param string $receiptId 71 | * 72 | * @return stdClass 73 | */ 74 | public function deleteNotification( string $receiptId ): stdClass { 75 | 76 | return $this->greenApi->request( 'DELETE', 77 | '{{host}}/waInstance{{idInstance}}/DeleteNotification/{{apiTokenInstance}}/' . $receiptId ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /examples/statusesExample.php: -------------------------------------------------------------------------------- 1 | statuses->sendTextStatus( 14 | "Hello from Green-API!", // message 15 | "#FF0000", // background color (red) 16 | "SERIF", // font 17 | ["70000001234@c.us"] // participants 18 | ); 19 | print_r("Text Status Result:\n"); 20 | print_r("Status Code: " . $textStatusResult->code . "\n"); 21 | print_r($textStatusResult->data); 22 | echo "\n\n"; 23 | sleep(1); // 1 second delay 24 | 25 | // Example 2: Send a voice status 26 | $voiceStatusResult = $greenApi->statuses->sendVoiceStatus( 27 | "https://example.com/voice.mp3", // URL to voice file 28 | "voice_message.mp3", // file name 29 | "#00FF00", // background color (green) 30 | ["70000001234@c.us"] // participants 31 | ); 32 | print_r("Voice Status Result:\n"); 33 | print_r("Status Code: " . $voiceStatusResult->code . "\n"); 34 | print_r($voiceStatusResult->data); 35 | echo "\n\n"; 36 | sleep(1); // 1 second delay 37 | 38 | // Example 3: Send a media status (photo or video) 39 | $mediaStatusResult = $greenApi->statuses->sendMediaStatus( 40 | "https://example.com/image.jpg", // URL to media file 41 | "sunset.jpg", // file name 42 | "Beautiful sunset!", // caption 43 | ["70000001234@c.us"] // participants 44 | ); 45 | print_r("Media Status Result:\n"); 46 | print_r("Status Code: " . $mediaStatusResult->code . "\n"); 47 | print_r($mediaStatusResult->data); 48 | echo "\n\n"; 49 | sleep(1); // 1 second delay 50 | 51 | // Example 4: Get incoming statuses (last 24 hours by default) 52 | $incomingStatuses = $greenApi->statuses->getIncomingStatuses(); 53 | print_r("Incoming Statuses (24h):\n"); 54 | print_r("Status Code: " . $incomingStatuses->code . "\n"); 55 | 56 | print_r($incomingStatuses->data); 57 | echo "\n\n"; 58 | sleep(1); // 1 second delay 59 | 60 | // Example 5: Get incoming statuses for specific time period (60 minutes) 61 | $incomingStatuses60min = $greenApi->statuses->getIncomingStatuses(60); 62 | print_r("Incoming Statuses (60 minutes):\n"); 63 | print_r("Status Code: " . $incomingStatuses60min->code . "\n"); 64 | print_r($incomingStatuses60min->data); 65 | echo "\n\n"; 66 | sleep(1); // 1 second delay 67 | 68 | // Example 6: Get outgoing statuses (last 24 hours by default) 69 | $outgoingStatuses = $greenApi->statuses->getOutgoingStatuses(); 70 | print_r("Outgoing Statuses (24h):\n"); 71 | print_r("Status Code: " . $outgoingStatuses->code . "\n"); 72 | print_r($outgoingStatuses->data); 73 | echo "\n\n"; 74 | sleep(1); // 1 second delay 75 | 76 | // Example 7: Get outgoing statuses for specific time period (120 minutes) 77 | $outgoingStatuses120min = $greenApi->statuses->getOutgoingStatuses(120); 78 | print_r("Outgoing Statuses (120 minutes):\n"); 79 | print_r("Status Code: " . $outgoingStatuses120min->code . "\n"); 80 | print_r($outgoingStatuses120min->data); 81 | echo "\n\n"; 82 | sleep(1); // 1 second delay 83 | 84 | // Example 8: Get status statistics for a specific message 85 | // Note: Replace with an actual message ID from your status 86 | $statusStatistics = $greenApi->statuses->getStatusStatistic("3EB0C767D097B7C7C81"); 87 | print_r("Status Statistics:\n"); 88 | print_r("Status Code: " . $statusStatistics->code . "\n"); 89 | print_r($statusStatistics->data); 90 | echo "\n\n"; 91 | -------------------------------------------------------------------------------- /src/tools/Account.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 16 | } 17 | 18 | /** 19 | * The method is aimed for getting the current account settings. 20 | * 21 | * @return stdClass 22 | * @link https://green-api.com/en/docs/api/account/GetSettings/ 23 | */ 24 | public function getSettings(): stdClass { 25 | return $this->greenApi->request('GET', 26 | '{{host}}/waInstance{{idInstance}}/GetSettings/{{apiTokenInstance}}'); 27 | } 28 | 29 | /** 30 | * The method is aimed for setting account settings. 31 | * 32 | * @param array $requestBody 33 | * 34 | * @return stdClass 35 | * @link https://green-api.com/en/docs/api/account/SetSettings/ 36 | */ 37 | public function setSettings(array $requestBody): stdClass { 38 | return $this->greenApi->request('POST', 39 | '{{host}}/waInstance{{idInstance}}/SetSettings/{{apiTokenInstance}}', $requestBody); 40 | } 41 | 42 | /** 43 | * The method is aimed for getting the account state. 44 | * 45 | * @return stdClass 46 | * @link https://green-api.com/en/docs/api/account/GetStateInstance/ 47 | */ 48 | public function getStateInstance(): stdClass { 49 | return $this->greenApi->request('GET', 50 | '{{host}}/waInstance{{idInstance}}/GetStateInstance/{{apiTokenInstance}}'); 51 | } 52 | 53 | /** 54 | * The method is aimed for rebooting an account. 55 | * 56 | * @return stdClass 57 | * @link https://green-api.com/en/docs/api/account/Reboot/ 58 | */ 59 | public function reboot(): stdClass { 60 | return $this->greenApi->request('GET', 61 | '{{host}}/waInstance{{idInstance}}/Reboot/{{apiTokenInstance}}'); 62 | } 63 | 64 | /** 65 | * The method is aimed for logging out an account. 66 | * 67 | * @return stdClass 68 | * @link https://green-api.com/en/docs/api/account/Logout/ 69 | */ 70 | public function logout(): stdClass { 71 | return $this->greenApi->request('GET', 72 | '{{host}}/waInstance{{idInstance}}/Logout/{{apiTokenInstance}}'); 73 | } 74 | 75 | /** 76 | * The method is aimed for getting QR code. To authorize your account, you have to scan a QR code from 77 | * application WhatsApp Business on your phone. You can also get a QR code and authorize your account in your profile. 78 | * 79 | * @return stdClass 80 | * @link https://green-api.com/en/docs/api/account/QR/ 81 | */ 82 | public function qr(): stdClass { 83 | return $this->greenApi->request('GET', 84 | '{{host}}/waInstance{{idInstance}}/qr/{{apiTokenInstance}}'); 85 | } 86 | 87 | /** 88 | * The method is intended to authorize an instance by phone number. 89 | * 90 | * @param int $phoneNumber 91 | * 92 | * @return stdClass 93 | * @link https://green-api.com/en/docs/api/account/GetAuthorizationCode/ 94 | */ 95 | public function getAuthorizationCode( int $phoneNumber ): stdClass { 96 | $requestBody = [ 97 | 'phoneNumber' => $phoneNumber, 98 | ]; 99 | 100 | return $this->greenApi->request( 'POST', 101 | '{{host}}/waInstance{{idInstance}}/getAuthorizationCode/{{apiTokenInstance}}', $requestBody ); 102 | } 103 | 104 | /** 105 | * The method is aimed for setting an account picture. 106 | * 107 | * @param string $path 108 | * 109 | * @return stdClass 110 | * @link https://green-api.com/en/docs/api/account/SetProfilePicture/ 111 | */ 112 | public function setProfilePicture(string $path): stdClass { 113 | $requestBody = [ 114 | 'file' => curl_file_create($path), 115 | ]; 116 | $requestBody['file']->mime = 'image/jpeg'; 117 | 118 | return $this->greenApi->request('POST', 119 | '{{host}}/waInstance{{idInstance}}/SetProfilePicture/{{apiTokenInstance}}', $requestBody, true); 120 | } 121 | 122 | /** 123 | * The method is aimed for getting the current WhatsApp account settings. 124 | * 125 | * @return stdClass 126 | * @link https://green-api.com/en/docs/api/account/GetWaSettings/ 127 | */ 128 | public function getWaSettings(): stdClass { 129 | return $this->greenApi->request('GET', 130 | '{{host}}/waInstance{{idInstance}}/getWaSettings/{{apiTokenInstance}}'); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/tools/Statuses.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 16 | } 17 | 18 | /** 19 | * The method is aimed for sending a text status. 20 | * 21 | * @param string $message 22 | * @param string $backgroundColor 23 | * @param string $font 24 | * @param array $participants 25 | * 26 | * @return stdClass 27 | * @link https://green-api.com/en/docs/api/statuses/SendTextStatus/ 28 | */ 29 | public function sendTextStatus( string $message, string $backgroundColor, string $font, array $participants ): stdClass { 30 | 31 | $requestBody = [ 32 | 'message' => $message, 33 | 'backgroundColor' => $backgroundColor, 34 | 'font' => $font, 35 | 'participants' => $participants, 36 | ]; 37 | 38 | return $this->greenApi->request( 'POST', 39 | '{{host}}/waInstance{{idInstance}}/sendTextStatus/{{apiTokenInstance}}', $requestBody ); 40 | } 41 | 42 | /** 43 | * The method is aimed for sending a voice status. 44 | * 45 | * @param string $urlFile 46 | * @param string $fileName 47 | * @param string $backgroundColor 48 | * @param array $participants 49 | * 50 | * @return stdClass 51 | * @link https://green-api.com/en/docs/api/statuses/SendVoiceStatus/ 52 | */ 53 | public function sendVoiceStatus( string $urlFile, string $fileName, string $backgroundColor, array $participants ): stdClass { 54 | 55 | $requestBody = [ 56 | 'urlFile' => $urlFile, 57 | 'fileName' => $fileName, 58 | 'backgroundColor' => $backgroundColor, 59 | 'participants' => $participants, 60 | ]; 61 | 62 | return $this->greenApi->request( 'POST', 63 | '{{host}}/waInstance{{idInstance}}/sendVoiceStatus/{{apiTokenInstance}}', $requestBody ); 64 | } 65 | 66 | /** 67 | * The method is aimed for sending a pictures or video status. 68 | * 69 | * @param string $urlFile 70 | * @param string $fileName 71 | * @param string $caption 72 | * @param array $participants 73 | * 74 | * @return stdClass 75 | * @link https://green-api.com/en/docs/api/statuses/SendMediaStatus/ 76 | */ 77 | public function sendMediaStatus( string $urlFile, string $fileName, string $caption, array $participants ): stdClass { 78 | 79 | $requestBody = [ 80 | 'urlFile' => $urlFile, 81 | 'fileName' => $fileName, 82 | 'caption' => $caption, 83 | 'participants' => $participants, 84 | ]; 85 | 86 | return $this->greenApi->request( 'POST', 87 | '{{host}}/waInstance{{idInstance}}/sendMediaStatus/{{apiTokenInstance}}', $requestBody ); 88 | } 89 | 90 | /** 91 | * The method returns the incoming status messages of the instance. In the default mode the incoming status messages for 24 hours are returned. 92 | * 93 | * @param int|null $minutes 94 | * 95 | * @return stdClass 96 | * @link https://green-api.com/en/docs/api/statuses/GetIncomingStatuses/ 97 | */ 98 | public function getIncomingStatuses( int $minutes = null ): stdClass { 99 | 100 | $requestBody = null; 101 | 102 | if ($minutes) { 103 | $requestBody['minutes'] = $minutes; 104 | } 105 | 106 | return $this->greenApi->request( 107 | 'GET', '{{host}}/waInstance{{idInstance}}/getIncomingStatuses/{{apiTokenInstance}}', $requestBody 108 | ); 109 | } 110 | 111 | /** 112 | * The method returns the outgoing statuses of the account. In the default mode the outgoing status messages for 24 hours are returned. 113 | * 114 | * @param int|null $minutes 115 | * 116 | * @return stdClass 117 | * @link https://green-api.com/en/docs/api/statuses/GetOutgoingStatuses/ 118 | */ 119 | public function getOutgoingStatuses( int $minutes = null ): stdClass { 120 | 121 | $requestBody = null; 122 | 123 | if ($minutes) { 124 | $requestBody['minutes'] = $minutes; 125 | } 126 | 127 | return $this->greenApi->request( 128 | 'GET', '{{host}}/waInstance{{idInstance}}/getOutgoingStatuses/{{apiTokenInstance}}', $requestBody 129 | ); 130 | } 131 | 132 | /** 133 | * The method returns an array of recipients marked sent/delivered/read for a given status 134 | * 135 | * @param string $idMessage 136 | * 137 | * @return stdClass 138 | * @link https://green-api.com/en/docs/api/statuses/GetStatusStatistic/ 139 | */ 140 | public function getStatusStatistic(string $idMessage): stdClass { 141 | return $this->greenApi->request( 142 | 'GET', 143 | '{{host}}/waInstance{{idInstance}}/getStatusStatistic/{{apiTokenInstance}}', 144 | ['idMessage' => $idMessage] // This will be added as query parameters 145 | ); 146 | } 147 | } -------------------------------------------------------------------------------- /src/tools/Groups.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * The method adds a participant to a group chat. 21 | * 22 | * @param string $groupId 23 | * @param string $participantChatId 24 | * 25 | * @return stdClass 26 | * @link https://green-api.com/en/docs/api/groups/AddGroupParticipant/ 27 | */ 28 | public function addGroupParticipant( string $groupId, string $participantChatId ): stdClass { 29 | 30 | $requestBody = [ 31 | 'groupId' => $groupId, 32 | 'participantChatId' => $participantChatId, 33 | ]; 34 | 35 | return $this->greenApi->request( 'POST', 36 | '{{host}}/waInstance{{idInstance}}/AddGroupParticipant/{{apiTokenInstance}}', $requestBody ); 37 | } 38 | 39 | /** 40 | * The method is aimed for creating a group chat. 41 | * 42 | * @param string $groupName 43 | * @param array $chatIds 44 | * 45 | * @return stdClass 46 | * @link https://green-api.com/en/docs/api/groups/CreateGroup/ 47 | */ 48 | public function createGroup( string $groupName, array $chatIds ): stdClass { 49 | 50 | $requestBody = [ 51 | 'groupName' => $groupName, 52 | 'chatIds' => $chatIds, 53 | ]; 54 | 55 | return $this->greenApi->request( 'POST', 56 | '{{host}}/waInstance{{idInstance}}/CreateGroup/{{apiTokenInstance}}', $requestBody ); 57 | } 58 | 59 | /** 60 | * The method gets group chat data. 61 | * 62 | * @param string $groupId 63 | * 64 | * @return stdClass 65 | * @link https://green-api.com/en/docs/api/groups/GetGroupData/ 66 | */ 67 | public function getGroupData( string $groupId ): stdClass { 68 | 69 | $requestBody = [ 70 | 'groupId' => $groupId, 71 | ]; 72 | 73 | return $this->greenApi->request( 'POST', 74 | '{{host}}/waInstance{{idInstance}}/GetGroupData/{{apiTokenInstance}}', $requestBody ); 75 | } 76 | 77 | /** 78 | * The method makes the current account user leave the group chat. 79 | * 80 | * @param string $groupId 81 | * 82 | * @return stdClass 83 | * @link https://green-api.com/en/docs/api/groups/LeaveGroup/ 84 | */ 85 | public function leaveGroup( string $groupId ): stdClass { 86 | 87 | $requestBody = [ 88 | 'groupId' => $groupId, 89 | ]; 90 | 91 | return $this->greenApi->request( 'POST', 92 | '{{host}}/waInstance{{idInstance}}/LeaveGroup/{{apiTokenInstance}}', $requestBody ); 93 | } 94 | 95 | /** 96 | * The method removes a participant from group chat administration rights. 97 | * 98 | * @param string $groupId 99 | * @param string $participantChatId 100 | * 101 | * @return stdClass 102 | * @link https://green-api.com/en/docs/api/groups/RemoveAdmin/ 103 | */ 104 | public function removeAdmin( string $groupId, string $participantChatId ): stdClass { 105 | 106 | $requestBody = [ 107 | 'groupId' => $groupId, 108 | 'participantChatId' => $participantChatId, 109 | ]; 110 | 111 | return $this->greenApi->request( 'POST', 112 | '{{host}}/waInstance{{idInstance}}/RemoveAdmin/{{apiTokenInstance}}', $requestBody ); 113 | } 114 | 115 | /** 116 | * The method removes a participant from a group chat. 117 | * 118 | * @param string $groupId 119 | * @param string $participantChatId 120 | * 121 | * @return stdClass 122 | * @link https://green-api.com/en/docs/api/groups/RemoveGroupParticipant/ 123 | */ 124 | public function removeGroupParticipant( string $groupId, string $participantChatId ): stdClass { 125 | 126 | $requestBody = [ 127 | 'groupId' => $groupId, 128 | 'participantChatId' => $participantChatId, 129 | ]; 130 | 131 | return $this->greenApi->request( 'POST', 132 | '{{host}}/waInstance{{idInstance}}/RemoveGroupParticipant/{{apiTokenInstance}}', $requestBody ); 133 | } 134 | 135 | /** 136 | * The method sets a group chat participant as an administrator. 137 | * 138 | * @param string $groupId 139 | * @param string $participantChatId 140 | * 141 | * @return stdClass 142 | * @link https://green-api.com/en/docs/api/groups/SetGroupAdmin/ 143 | */ 144 | public function setGroupAdmin( string $groupId, string $participantChatId ): stdClass { 145 | 146 | $requestBody = [ 147 | 'groupId' => $groupId, 148 | 'participantChatId' => $participantChatId, 149 | ]; 150 | 151 | return $this->greenApi->request( 'POST', 152 | '{{host}}/waInstance{{idInstance}}/SetGroupAdmin/{{apiTokenInstance}}', $requestBody ); 153 | } 154 | 155 | /** 156 | * The method sets a group picture. 157 | * 158 | * @param string $groupId 159 | * @param string $path 160 | * 161 | * @return stdClass 162 | * @link https://green-api.com/en/docs/api/groups/SetGroupPicture/ 163 | */ 164 | public function setGroupPicture( string $groupId, string $path ): stdClass { 165 | 166 | $requestBody = [ 167 | 'groupId' => $groupId, 168 | 'file' => curl_file_create( $path ), 169 | ]; 170 | $requestBody['file']->mime = 'image/jpeg'; 171 | 172 | return $this->greenApi->request( 'POST', 173 | '{{host}}/waInstance{{idInstance}}/SetGroupPicture/{{apiTokenInstance}}', $requestBody, true ); 174 | } 175 | 176 | /** 177 | * The method changes a group chat name. 178 | * 179 | * @param string $groupId 180 | * @param string $groupName 181 | * 182 | * @return stdClass 183 | * @link https://green-api.com/en/docs/api/groups/UpdateGroupName/ 184 | */ 185 | public function updateGroupName( string $groupId, string $groupName ): stdClass { 186 | 187 | $requestBody = [ 188 | 'groupId' => $groupId, 189 | 'groupName' => $groupName, 190 | ]; 191 | 192 | return $this->greenApi->request( 'POST', 193 | '{{host}}/waInstance{{idInstance}}/UpdateGroupName/{{apiTokenInstance}}', $requestBody ); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/tools/ServiceMethods.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * The method checks WhatsApp account availability on a phone number. 21 | * 22 | * @param int $phoneNumber 23 | * 24 | * @return stdClass 25 | * @link https://green-api.com/en/docs/api/service/CheckWhatsapp/ 26 | */ 27 | public function checkWhatsapp( int $phoneNumber ): stdClass { 28 | 29 | $requestBody = [ 30 | 'phoneNumber' => $phoneNumber, 31 | ]; 32 | 33 | return $this->greenApi->request( 'POST', 34 | '{{host}}/waInstance{{idInstance}}/CheckWhatsapp/{{apiTokenInstance}}', $requestBody ); 35 | } 36 | 37 | /** 38 | * The method returns a user or a group chat avatar. 39 | * 40 | * @param string $chatId 41 | * 42 | * @return stdClass 43 | * @link https://green-api.com/en/docs/api/service/GetAvatar/ 44 | */ 45 | public function getAvatar( string $chatId ): stdClass { 46 | 47 | $requestBody = [ 48 | 'chatId' => $chatId, 49 | ]; 50 | 51 | return $this->greenApi->request( 'POST', 52 | '{{host}}/waInstance{{idInstance}}/GetAvatar/{{apiTokenInstance}}', $requestBody ); 53 | } 54 | 55 | /** 56 | * The method is aimed for getting information on a contact. 57 | * 58 | * @param string $chatId 59 | * 60 | * @return stdClass 61 | * @link https://green-api.com/en/docs/api/service/GetContactInfo/ 62 | */ 63 | public function getContactInfo( string $chatId ): stdClass { 64 | 65 | $requestBody = [ 66 | 'chatId' => $chatId, 67 | ]; 68 | 69 | return $this->greenApi->request( 'POST', 70 | '{{host}}/waInstance{{idInstance}}/GetContactInfo/{{apiTokenInstance}}', $requestBody ); 71 | } 72 | 73 | /** 74 | * The method is aimed for getting a list of the current account contacts. Send contacts of all recipients 75 | * whom the account connected with. Parameter "contact name" "name" takes on a value based on the 76 | * below criteria: If the account is recorded in the phonebook, then we get the name from the book; 77 | * If the account is not recorded in the phonebook, then we get the name from WhatsApp account; 78 | * If the account is not recorded in the phone book and WhatsApp account name is not assigned, then we get an empty 79 | * field. 80 | * 81 | * @return stdClass 82 | * @link https://green-api.com/en/docs/api/service/GetContacts/ 83 | */ 84 | public function getContacts(): stdClass { 85 | 86 | return $this->greenApi->request( 'GET', 87 | '{{host}}/waInstance{{idInstance}}/GetContacts/{{apiTokenInstance}}' ); 88 | } 89 | 90 | 91 | /** 92 | * The method archives a chat. You can archive chats that have at least one incoming message. 93 | * 94 | * @param string $chatId 95 | * 96 | * @return stdClass 97 | * @link https://green-api.com/en/docs/api/service/ArchiveChat/ 98 | */ 99 | public function archiveChat( string $chatId ): stdClass { 100 | 101 | $requestBody = [ 102 | 'chatId' => $chatId, 103 | ]; 104 | 105 | return $this->greenApi->request( 'POST', 106 | '{{host}}/waInstance{{idInstance}}/ArchiveChat/{{apiTokenInstance}}', $requestBody ); 107 | } 108 | 109 | 110 | /** 111 | * The method deletes a message from a chat. 112 | * 113 | * @param string $chatId 114 | * @param string $idMessage 115 | * 116 | * @return stdClass 117 | * @link https://green-api.com/en/docs/api/service/DeleteMessage/ 118 | */ 119 | public function deleteMessage( string $chatId, string $idMessage, bool $onlySenderDelete = false ): stdClass { 120 | 121 | $requestBody = [ 122 | 'chatId' => $chatId, 123 | 'idMessage' => $idMessage, 124 | 'onlySenderDelete' => $onlySenderDelete, 125 | ]; 126 | 127 | return $this->greenApi->request( 'POST', 128 | '{{host}}/waInstance{{idInstance}}/DeleteMessage/{{apiTokenInstance}}', $requestBody ); 129 | } 130 | 131 | /** 132 | * The method edits a message in a chat. 133 | * 134 | * @param string $chatId 135 | * @param string $idMessage 136 | * @param string $message 137 | * 138 | * @return stdClass 139 | * @link https://green-api.com/en/docs/api/service/EditMessage/ 140 | */ 141 | public function editMessage( string $chatId, string $idMessage, string $message ): stdClass { 142 | 143 | $requestBody = [ 144 | 'chatId' => $chatId, 145 | 'idMessage' => $idMessage, 146 | 'message' => $message, 147 | ]; 148 | 149 | return $this->greenApi->request( 'POST', 150 | '{{host}}/waInstance{{idInstance}}/EditMessage/{{apiTokenInstance}}', $requestBody ); 151 | } 152 | 153 | /** 154 | * The method unarchives a chat. 155 | * 156 | * @param string $chatId 157 | * 158 | * @return stdClass 159 | * @link https://green-api.com/en/docs/api/service/unarchiveChat/ 160 | */ 161 | public function unarchiveChat( string $chatId ): stdClass { 162 | 163 | $requestBody = [ 164 | 'chatId' => $chatId, 165 | ]; 166 | 167 | return $this->greenApi->request( 'POST', 168 | '{{host}}/waInstance{{idInstance}}/UnarchiveChat/{{apiTokenInstance}}', $requestBody ); 169 | } 170 | 171 | /** 172 | * The method is aimed for changing settings of disappearing messages in chats. The standard settings of the 173 | * application are used: 0 (off), 86400 (24 hours), 604800 (7 days), 7776000 (90 days). 174 | * 175 | * @param string $chatId 176 | * @param int $ephemeralExpiration 177 | * 178 | * @return stdClass 179 | * @link https://green-api.com/en/docs/api/service/SetDisappearingChat/ 180 | */ 181 | public function setDisappearingChat( string $chatId, int $ephemeralExpiration ): stdClass { 182 | 183 | $requestBody = [ 184 | 'chatId' => $chatId, 185 | 'ephemeralExpiration' => $ephemeralExpiration, 186 | ]; 187 | 188 | return $this->greenApi->request( 'POST', 189 | '{{host}}/waInstance{{idInstance}}/SetDisappearingChat/{{apiTokenInstance}}', $requestBody ); 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /src/GreenApiClient.php: -------------------------------------------------------------------------------- 1 | idInstance = $idInstance; 74 | $this->apiTokenInstance = $apiTokenInstance; 75 | $this->host = $host; 76 | $this->media = $media; 77 | 78 | $this->account = new Account( $this ); 79 | $this->groups = new Groups( $this ); 80 | $this->journals = new Journals( $this ); 81 | $this->marking = new Marking( $this ); 82 | $this->queues = new Queues( $this ); 83 | $this->receiving = new Receiving( $this ); 84 | $this->sending = new Sending( $this ); 85 | $this->serviceMethods = new ServiceMethods( $this ); 86 | $this->webhooks = new Webhooks( $this ); 87 | $this->statuses = new Statuses( $this ); 88 | } 89 | 90 | /** 91 | * @param string $method 92 | * @param string $url 93 | * @param array|null $payload 94 | * @param bool $is_files 95 | * @param string|null $mime_type 96 | * @param string|null $path 97 | * 98 | * @return stdClass 99 | */ 100 | public function request( string $method, string $url, array $payload = null, bool $is_files = false, 101 | string $mime_type = null, string $path = null 102 | ): stdClass { 103 | $url = str_replace( '{{host}}', $this->host, $url ); 104 | $url = str_replace( '{{media}}', $this->media, $url ); 105 | $url = str_replace( '{{idInstance}}', $this->idInstance, $url ); 106 | $url = str_replace( '{{apiTokenInstance}}', $this->apiTokenInstance, $url ); 107 | 108 | $method = strtoupper( $method ); 109 | $curl = curl_init(); 110 | 111 | $payloadData = null; 112 | $headers = null; 113 | 114 | if ( $payload ) { 115 | if ( ! $is_files ) { 116 | $headers = array( 'Content-Type: application/json; charset=utf-8' ); 117 | curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers ); 118 | $payloadData = json_encode( $payload, JSON_UNESCAPED_UNICODE ); 119 | } else { 120 | if ( $mime_type ) { 121 | $headers = array( 'Content-Type: ' . $mime_type ); 122 | curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers ); 123 | } 124 | $payloadData = $payload; 125 | } 126 | } 127 | 128 | switch ( $method ) { 129 | case 'POST': 130 | if ( ! $headers && ! $is_files ) { 131 | curl_setopt( $curl, CURLOPT_POST, count( $payload ) ); 132 | } elseif ( $is_files ) { 133 | curl_setopt( $curl, CURLOPT_POST, count( $payloadData ) ); 134 | } 135 | curl_setopt( $curl, CURLOPT_POSTFIELDS, $payloadData ); 136 | break; 137 | case 'PUT': 138 | curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'PUT' ); 139 | curl_setopt( $curl, CURLOPT_POSTFIELDS, $payloadData ); 140 | break; 141 | case 'DELETE': 142 | curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'DELETE' ); 143 | curl_setopt( $curl, CURLOPT_POSTFIELDS, $payloadData ); 144 | break; 145 | case 'POST_BINARY': 146 | $mime_type = mime_content_type( $path ); 147 | $headers = array( 148 | 'Content-Type: ' . $mime_type , 149 | 'GA-Filename: ' . basename($path) 150 | ); 151 | $filesize = filesize($path); 152 | $stream = fopen($path, 'r'); 153 | curl_setopt( $curl, CURLOPT_PUT, true ); 154 | curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST' ); 155 | curl_setopt( $curl, CURLOPT_INFILE, $stream ); 156 | curl_setopt( $curl, CURLOPT_INFILESIZE, $filesize ); 157 | curl_setopt( $curl, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 ); 158 | curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers ); 159 | break; 160 | default: 161 | if ( ! empty( $payload ) ) { 162 | $url .= '?' . http_build_query( $payload ); 163 | } 164 | } 165 | 166 | curl_setopt( $curl, CURLOPT_URL, $url ); 167 | curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false ); 168 | curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, false ); 169 | curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true ); 170 | curl_setopt( $curl, CURLOPT_HEADER, true ); 171 | curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 30 ); 172 | curl_setopt( $curl, CURLOPT_TIMEOUT, 30 ); 173 | 174 | $response = curl_exec( $curl ); 175 | $header_size = curl_getinfo( $curl, CURLINFO_HEADER_SIZE ); 176 | $headerCode = curl_getinfo( $curl, CURLINFO_HTTP_CODE ); 177 | $responseBody = substr( $response, $header_size ); 178 | $curlErrors = curl_error( $curl ); 179 | 180 | curl_close( $curl ); 181 | 182 | if ( $responseBody === 'null' ) { 183 | $responseBodyJson = null; 184 | } else { 185 | $responseBodyJson = json_decode( $responseBody ); 186 | } 187 | 188 | $result = new stdClass(); 189 | 190 | if ( !empty( $curlErrors ) ) { 191 | $result->code = 0; 192 | $result->error = $curlErrors; 193 | return $result; 194 | } 195 | 196 | $result->code = $headerCode; 197 | 198 | if ( json_last_error() === JSON_ERROR_NONE ) { 199 | if ( $headerCode === 200 ) { 200 | $result->data = $responseBodyJson; 201 | $result->error = null; 202 | } else { 203 | $result->data = null; 204 | $result->error = $responseBodyJson; 205 | } 206 | } else { 207 | $result->data = null; 208 | $result->error = $responseBody; 209 | } 210 | 211 | return $result; 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/tools/Sending.php: -------------------------------------------------------------------------------- 1 | greenApi = $greenApi; 17 | } 18 | 19 | /** 20 | * The method is aimed for sending a button message to a personal or a group chat. The message will be added to 21 | * the send queue. Checking whatsapp authorization on the phone (i.e. availability in linked devices) is not 22 | * performed. The message will be kept for 24 hours in the queue and will be sent immediately after phone 23 | * authorization. The rate at which messages are sent from the queue is managed by Message sending delay parameter. 24 | * 25 | * @param string $chatId 26 | * @param string $message 27 | * @param string $footer 28 | * @param array $buttons 29 | * @param string|null $quotedMessageId 30 | * @param bool $archiveChat 31 | * 32 | * @return stdClass 33 | * @link https://green-api.com/en/docs/api/sending/SendButtons/ 34 | */ 35 | public function sendButtons( 36 | string $chatId, string $message, string $footer, array $buttons, 37 | string $quotedMessageId = null, bool $archiveChat = false 38 | ): stdClass { 39 | 40 | $requestBody = [ 41 | 'chatId' => $chatId, 42 | 'message' => $message, 43 | 'footer' => $footer, 44 | 'buttons' => $buttons, 45 | ]; 46 | 47 | if ( $quotedMessageId ) { 48 | $requestBody['quotedMessageId'] = $quotedMessageId; 49 | } 50 | 51 | if ( $archiveChat ) { 52 | $requestBody['archiveChat'] = $archiveChat; 53 | } 54 | 55 | return $this->greenApi->request( 'POST', 56 | '{{host}}/waInstance{{idInstance}}/sendButtons/{{apiTokenInstance}}', $requestBody ); 57 | } 58 | 59 | /** 60 | * The method is aimed for sending a contact message. Contact visit card is created and sent to a chat. The message 61 | * will be added to the send queue. Linked device not required when sending. Messages will be kept for 24 hours 62 | * in the queue until account will be authorized The rate at which messages are sent from the queue is managed 63 | * by Message sending delay parameter. 64 | * 65 | * @param string $chatId 66 | * @param array $contact 67 | * @param string|null $quotedMessageId 68 | * 69 | * @return stdClass 70 | * @link https://green-api.com/en/docs/api/sending/SendContact/ 71 | */ 72 | public function sendContact( string $chatId, array $contact, string $quotedMessageId = null ): stdClass { 73 | 74 | $requestBody = [ 75 | 'chatId' => $chatId, 76 | 'contact' => $contact 77 | ]; 78 | 79 | if ( $quotedMessageId ) { 80 | $requestBody['quotedMessageId'] = $quotedMessageId; 81 | } 82 | 83 | return $this->greenApi->request( 'POST', 84 | '{{host}}/waInstance{{idInstance}}/SendContact/{{apiTokenInstance}}', $requestBody ); 85 | } 86 | 87 | /** 88 | * The method is aimed for sending a file uploaded by form (form-data). The message will be added to the send queue. 89 | * The rate at which messages are sent from the queue is managed by Message sending delay parameter. Video, audio 90 | * and image files available for viewing and listening to are sent as in native-mode WhatsApp. Documents are sent 91 | * in the same way as in native-mode WhatsApp. Outgoing file type and send method is determined by the file extension. 92 | * Description is only added to images and video.The maximum size of outgoing files is 37 MB. 93 | * 94 | * @param string $chatId 95 | * @param string $path 96 | * @param string|null $fileName 97 | * @param string|null $caption 98 | * @param string|null $quotedMessageId 99 | * 100 | * @return stdClass 101 | * @link https://green-api.com/en/docs/api/sending/SendFileByUpload/ 102 | */ 103 | public function sendFileByUpload( 104 | string $chatId, string $path, string $fileName = null, string $caption = null, string $quotedMessageId = null 105 | ): stdClass { 106 | 107 | if ( ! $fileName ) { 108 | $fileName = basename( $path ); 109 | } 110 | 111 | $requestBody = [ 112 | 'chatId' => $chatId, 113 | 'fileName' => $fileName, 114 | 'file' => curl_file_create( $path ), 115 | ]; 116 | $requestBody['file']->mime = mime_content_type( $path ); 117 | 118 | if ( $caption ) { 119 | $requestBody['caption'] = $caption; 120 | } 121 | if ( $quotedMessageId ) { 122 | $requestBody['quotedMessageId'] = $quotedMessageId; 123 | } 124 | 125 | return $this->greenApi->request( 'POST', 126 | '{{media}}/waInstance{{idInstance}}/SendFileByUpload/{{apiTokenInstance}}', $requestBody, true ); 127 | } 128 | 129 | 130 | /** 131 | * The method is aimed for sending a file uploaded by Url The message will be added to the send queue. The rate at 132 | * which messages are sent from the queue is managed by Message sending delay parameter.Video, audio and image files 133 | * available for viewing and listening to are sent as in native-mode WhatsApp. Documents are sent in the same way 134 | * as in native-mode WhatsApp. Outgoing file type and send method is determined by the file extension. Description is 135 | * only added to images and video.The maximum size of outgoing files is 37 MB. 136 | * 137 | * @param string $chatId 138 | * @param string $urlFile 139 | * @param string|null $fileName 140 | * @param string|null $caption 141 | * @param string|null $quotedMessageId 142 | * @param bool $archiveChat 143 | * 144 | * @return stdClass 145 | * @link https://green-api.com/en/docs/api/sending/SendFileByUrl/ 146 | */ 147 | public function sendFileByUrl( 148 | string $chatId, string $urlFile, string $fileName = null, string $caption = null, string $quotedMessageId = null, 149 | bool $archiveChat = false 150 | ): stdClass { 151 | 152 | if ( ! $fileName ) { 153 | $fileName = basename( $urlFile ); 154 | } 155 | 156 | $requestBody = [ 157 | 'chatId' => $chatId, 158 | 'urlFile' => $urlFile, 159 | 'fileName' => $fileName, 160 | ]; 161 | 162 | if ( $caption ) { 163 | $requestBody['caption'] = $caption; 164 | } 165 | 166 | if ( $quotedMessageId ) { 167 | $requestBody['quotedMessageId'] = $quotedMessageId; 168 | } 169 | 170 | if ( $archiveChat ) { 171 | $requestBody['archiveChat'] = $archiveChat; 172 | } 173 | 174 | return $this->greenApi->request( 'POST', 175 | '{{host}}/waInstance{{idInstance}}/SendFileByUrl/{{apiTokenInstance}}', $requestBody ); 176 | } 177 | 178 | /** 179 | * The method is aimed for sending a message with a link, by which an image preview, title and description will be 180 | * added. Linked device not required when sending. Messages will be kept for 24 hours in the queue until account will 181 | * be authorized Image, title and description are obtained from Open Graph page template being linked to. The message 182 | * will be added to the send queue. The rate at which messages are sent from the queue is managed by Messages sending 183 | * delay parameter. 184 | * 185 | * @param string $chatId 186 | * @param string $urlLink 187 | * @param string|null $quotedMessageId 188 | * 189 | * @return stdClass 190 | * @link https://green-api.com/en/docs/api/sending/SendLink/ 191 | */ 192 | public function sendLink( string $chatId, string $urlLink, string $quotedMessageId = null ): stdClass { 193 | 194 | $requestBody = [ 195 | 'chatId' => $chatId, 196 | 'urlLink' => $urlLink 197 | ]; 198 | 199 | if ( $quotedMessageId ) { 200 | $requestBody['quotedMessageId'] = $quotedMessageId; 201 | } 202 | 203 | return $this->greenApi->request( 'POST', 204 | '{{host}}/waInstance{{idInstance}}/SendLink/{{apiTokenInstance}}', $requestBody ); 205 | } 206 | 207 | 208 | /** 209 | * The method is aimed for sending a message with a select button from a list of values to a personal or a group chat. 210 | * The message will be added to the send queue. Checking whatsapp authorization on the phone (i.e. availability in 211 | * linked devices) is not performed. The message will be kept for 24 hours in the queue and will be sent immediately 212 | * after phone authorization. The rate at which messages are sent from the queue is managed by Message sending delay 213 | * parameter. 214 | * 215 | * @param string $chatId 216 | * @param string $message 217 | * @param array $sections 218 | * @param string|null $title 219 | * @param string|null $footer 220 | * @param string|null $buttonText 221 | * @param string|null $quotedMessageId 222 | * @param bool $archiveChat 223 | * 224 | * @return stdClass 225 | * @link https://green-api.com/en/docs/api/sending/SendListMessage/ 226 | */ 227 | public function sendListMessage( 228 | string $chatId, string $message, array $sections, string $title = null, string $footer = null, 229 | string $buttonText = null, string $quotedMessageId = null, bool $archiveChat = false 230 | ): stdClass { 231 | 232 | $requestBody = [ 233 | 'chatId' => $chatId, 234 | 'message' => $message, 235 | 'sections' => $sections, 236 | ]; 237 | 238 | if ( $title ) { 239 | $requestBody['title'] = $title; 240 | } 241 | if ( $footer ) { 242 | $requestBody['footer'] = $footer; 243 | } 244 | if ( $buttonText ) { 245 | $requestBody['buttonText'] = $buttonText; 246 | } 247 | if ( $quotedMessageId ) { 248 | $requestBody['quotedMessageId'] = $quotedMessageId; 249 | } 250 | if ( $archiveChat ) { 251 | $requestBody['archiveChat'] = $archiveChat; 252 | } 253 | 254 | return $this->greenApi->request( 'POST', 255 | '{{host}}/waInstance{{idInstance}}/SendListMessage/{{apiTokenInstance}}', $requestBody ); 256 | } 257 | 258 | /** 259 | * The method is aimed for sending location message. The message will be added to the send queue. Linked device not 260 | * required when sending. Messages will be kept for 24 hours in the queue until account will be authorized. 261 | * The rate at which messages are sent from the queue is managed by Message sending delay parameter. 262 | * 263 | * @param string $chatId 264 | * @param float $latitude 265 | * @param float $longitude 266 | * @param string|null $nameLocation 267 | * @param string|null $address 268 | * @param string|null $quotedMessageId 269 | * 270 | * @return stdClass 271 | * @link https://green-api.com/en/docs/api/sending/SendLocation/ 272 | */ 273 | public function sendLocation( 274 | string $chatId, float $latitude, float $longitude, string $nameLocation = null, string $address = null, 275 | string $quotedMessageId = null 276 | ): stdClass { 277 | 278 | $requestBody = [ 279 | 'chatId' => $chatId, 280 | 'latitude' => $latitude, 281 | 'longitude' => $longitude, 282 | ]; 283 | 284 | if ( $nameLocation ) { 285 | $requestBody['nameLocation'] = $nameLocation; 286 | } 287 | if ( $address ) { 288 | $requestBody['address'] = $address; 289 | } 290 | if ( $quotedMessageId ) { 291 | $requestBody['quotedMessageId'] = $quotedMessageId; 292 | } 293 | 294 | return $this->greenApi->request( 'POST', 295 | '{{host}}/waInstance{{idInstance}}/SendLocation/{{apiTokenInstance}}', $requestBody ); 296 | } 297 | 298 | 299 | /** 300 | * The method is aimed for sending a text message to a personal or a group chat. The message will be added to 301 | * the send queue. Linked device not required when sending. Messages will be kept for 24 hours in the queue until 302 | * account will be authorized The rate at which messages are sent from the queue is managed by Message sending 303 | * delay parameter. 304 | * 305 | * @param string $chatId 306 | * @param string $message 307 | * @param string|null $quotedMessageId 308 | * @param bool $archiveChat 309 | * 310 | * @return stdClass 311 | * @link https://green-api.com/en/docs/api/sending/SendMessage/ 312 | */ 313 | public function sendMessage( 314 | string $chatId, string $message, string $quotedMessageId = null, bool $archiveChat = false 315 | ): stdClass { 316 | 317 | $requestBody = [ 318 | 'chatId' => $chatId, 319 | 'message' => $message, 320 | ]; 321 | 322 | if ( $quotedMessageId ) { 323 | $requestBody['quotedMessageId'] = $quotedMessageId; 324 | } 325 | 326 | if ( $archiveChat ) { 327 | $requestBody['archiveChat'] = $archiveChat; 328 | } 329 | 330 | return $this->greenApi->request( 'POST', 331 | '{{host}}/waInstance{{idInstance}}/SendMessage/{{apiTokenInstance}}', $requestBody ); 332 | } 333 | 334 | 335 | /** 336 | * The method is aimed for sending a message with template list interactive buttons to a personal or a group chat. 337 | * The message will be added to the send queue. Checking whatsapp authorization on the phone (i.e. availability in 338 | * linked devices) is not performed. The message will be kept for 24 hours in the queue and will be sent immediately 339 | * after phone authorization. The rate at which messages are sent from the queue is managed by Message sending delay 340 | * parameter. 341 | * 342 | * @param string $chatId 343 | * @param string $message 344 | * @param array $templateButtons 345 | * @param string|null $footer 346 | * @param string|null $quotedMessageId 347 | * @param bool $archiveChat 348 | * 349 | * @return stdClass 350 | * @link https://green-api.com/en/docs/api/sending/SendTemplateButtons/ 351 | */ 352 | public function sendTemplateButtons( 353 | string $chatId, string $message, array $templateButtons, string $footer = null, 354 | string $quotedMessageId = null, bool $archiveChat = false 355 | ): stdClass { 356 | 357 | $requestBody = [ 358 | 'chatId' => $chatId, 359 | 'message' => $message, 360 | 'templateButtons' => $templateButtons, 361 | ]; 362 | 363 | if ( $footer ) { 364 | $requestBody['footer'] = $footer; 365 | } 366 | if ( $quotedMessageId ) { 367 | $requestBody['quotedMessageId'] = $quotedMessageId; 368 | } 369 | if ( $archiveChat ) { 370 | $requestBody['archiveChat'] = $archiveChat; 371 | } 372 | 373 | return $this->greenApi->request( 'POST', 374 | '{{host}}/waInstance{{idInstance}}/SendTemplateButtons/{{apiTokenInstance}}', $requestBody ); 375 | } 376 | 377 | /** 378 | * The method is intended for forwarding messages to a personal or group chat. The forwarded messages will be added 379 | * to the send queue. Checking whatsapp authorization on the phone (i.e. availability in linked devices) is not performed. 380 | * The message will be kept for 24 hours in the queue and will be sent immediately after phone authorization. 381 | * The rate at which messages are sent from the queue is managed by Message sending delay parameter. 382 | * 383 | * @param string $chatId 384 | * @param string $chatIdFrom 385 | * @param array $messages 386 | * 387 | * @return stdClass 388 | * @link https://green-api.com/en/docs/api/sending/ForwardMessages/ 389 | */ 390 | public function forwardMessages( string $chatId, string $chatIdFrom, array $messages ): stdClass { 391 | 392 | $requestBody = [ 393 | 'chatId' => $chatId, 394 | 'chatIdFrom' => $chatIdFrom, 395 | 'messages' => $messages 396 | ]; 397 | 398 | return $this->greenApi->request( 'POST', 399 | '{{host}}/waInstance{{idInstance}}/ForwardMessages/{{apiTokenInstance}}', $requestBody ); 400 | } 401 | 402 | /** 403 | * The method is aimed for upload binary file. 404 | * 405 | * @param string $path 406 | * 407 | * @return stdClass 408 | * @link https://green-api.com/en/docs/api/sending/UploadFile/ 409 | */ 410 | public function uploadFile( 411 | string $path): stdClass { 412 | 413 | return $this->greenApi->request( 'POST_BINARY', 414 | '{{media}}/waInstance{{idInstance}}/UploadFile/{{apiTokenInstance}}', null, false, null, $path ); 415 | } 416 | } 417 | -------------------------------------------------------------------------------- /README_RUS.md: -------------------------------------------------------------------------------- 1 | # whatsapp-api-client-php 2 | [![Total Downloads](https://poser.pugx.org/green-api/whatsapp-api-client-php/downloads?format=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 3 | [![Downloads per month](https://img.shields.io/packagist/dm/green-api/whatsapp-api-client-php.svg?style=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 4 | [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg?style=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 5 | 6 | PHP библиотека для интеграции с мессенджером WhatsApp через API сервиса [green-api.com](https://green-api.com/). Чтобы воспользоваться библиотекой, нужно получить регистрационный токен и id аккаунта в [личном кабинете](https://console.green-api.com). Есть бесплатный тариф аккаунта разработчика. 7 | 8 | ## API 9 | 10 | Документация к REST API находится по [ссылке](https://green-api.com/docs/api/). Библиотека является оберткой к REST API, поэтому документация по ссылке выше применима и к самой библиотеке. 11 | 12 | ## Установка 13 | Через [Composer](https://getcomposer.org): 14 | 15 | ```bash 16 | composer require green-api/whatsapp-api-client-php 17 | ``` 18 | 19 | ## Import 20 | 21 | ``` 22 | require './vendor/autoload.php'; 23 | ``` 24 | ## Авторизация 25 | 26 | Чтобы отправить сообщение или выполнить другой метод Green-API, аккаунт WhatsApp в приложении телефона должен быть в авторизованном состоянии. Для авторизации аккаунта перейдите в [личный кабинет](https://console.green-api.com) и сканируйте QR-код с использованием приложения WhatsApp. 27 | 28 | ## Запуск index.php 29 | 30 | ``` 31 | php -S localhost:8080 32 | ``` 33 | 34 | ## Примеры 35 | 36 | ### Как инициализировать объект 37 | 38 | ``` 39 | $greenApi = new GreenApiClient( ID_INSTANCE, API_TOKEN_INSTANCE ); 40 | ``` 41 | 42 | ### Отправка текстового сообщения на номер WhatsApp 43 | 44 | ``` 45 | $result = $greenApi->sending->sendMessage('11001234567@g.us', 'Message text'); 46 | ``` 47 | 48 | Ссылка на пример: [sendTextMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendTextMessage.php) 49 | 50 | Обратите внимание, что ключи можно получать из переменных среды: 51 | ``` 52 | sending->sendFileByUrl( 63 | '11001234567@c.us', 'https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 64 | 'googlelogo_color_272x92dp.png', 'Google logo'); 65 | ``` 66 | 67 | Ссылка на пример: [sendPictureByLink.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByLink.php) 68 | 69 | ### Отправка картинки загрузкой с диска 70 | 71 | ``` 72 | result = greenAPI.sending.sendFileByUpload('120363025955348359@g.us', 73 | 'C:\Games\PicFromDisk.png', 74 | 'PicFromDisk.png', 'Picture from disk') 75 | ``` 76 | 77 | Ссылка на пример: [sendPictureByUpload.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByUpload.php) 78 | 79 | ### Создание группы и отправка сообщения в эту группу 80 | 81 | ``` 82 | $chatIds = [ 83 | '11001234567@c.us' 84 | ]; 85 | $resultCreate = $greenApi->groups->createGroup('GroupName', $chatIds ); 86 | 87 | if ($resultCreate->code == 200) 88 | $resultSend = $greenApi->sending->sendMessage($resultCreate->data->chatId, 89 | 'Message text'); 90 | ``` 91 | 92 | ВАЖНО: Если попытаться создать группу с несуществующим номером WhatsApp 93 | может заблокировать номер отправителя. Номер в примере не существует. 94 | 95 | Ссылка на пример: [createGroupAndSendMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/createGroupAndSendMessage.php) 96 | 97 | ### Получение входящих сообщений через HTTP API 98 | 99 | Общая концепция получения данных в Green API описана [здесь](https://green-api.com/docs/api/receiving/) 100 | Для старта получения сообщений через HTTP API требуется выполнить метод библиотеки: 101 | 102 | ``` 103 | greenAPI.webhooks.startReceivingNotifications(onEvent) 104 | ``` 105 | 106 | onEvent - ваш метод, который должен содержать параметры: 107 | Параметр | Описание 108 | ----- | ----- 109 | typeWebhook | тип полученного сообщения (строка) 110 | body | тело сообщения (json) 111 | 112 | Типы и форматы тел сообщений [здесь](https://green-api.com/docs/api/receiving/notifications-format/) 113 | 114 | Этот метод будет вызываться при получении входящего сообщения. Далее обрабатываете сообщения согласно бизнес-логике вашей системы. 115 | 116 | ## Список примеров 117 | 118 | | Описание | Модуль | 119 | |------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------| 120 | | Пример отправки текста | [sendTextMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendTextMessage.php) | 121 | | Пример отправки картинки по URL | [sendPictureByLink.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByLink.php) | 122 | | Пример отправки картинки загрузкой с диска | [sendPictureByUpload.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByUpload.php) | 123 | | Пример создание группы и отправка сообщения в группу | [createGroupAndSendMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/createGroupAndSendMessage.php) | 124 | | Пример получения входящих уведомлений | [receiveNotification.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/receiveNotification.php) | 125 | 126 | ## Полный список методов библиотеки 127 | 128 | | Метод API | Описание | Documentation link | 129 | |----------------------------------------|---------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| 130 | | `account.getSettings` | Метод предназначен для получения текущих настроек аккаунта | [GetSettings](https://green-api.com/docs/api/account/GetSettings/) | 131 | | `account.setSettings` | Метод предназначен для установки настроек аккаунта | [SetSettings](https://green-api.com/docs/api/account/SetSettings/) | 132 | | `account.getStateInstance` | Метод предназначен для получения состояния аккаунта | [GetStateInstance](https://green-api.com/docs/api/account/GetStateInstance/) | 133 | | `account.getStatusInstance` | Метод предназначен для получения состояния сокета соединения инстанса аккаунта с WhatsApp | [GetStatusInstance](https://green-api.com/docs/api/account/GetStatusInstance/) | 134 | | `account.reboot` | Метод предназначен для перезапуска аккаунта | [Reboot](https://green-api.com/docs/api/account/Reboot/) | 135 | | `account.logout` | Метод предназначен для разлогинивания аккаунта | [Logout](https://green-api.com/docs/api/account/Logout/) | 136 | | `account.qr` | Метод предназначен для получения QR-кода | [QR](https://green-api.com/docs/api/account/QR/) | 137 | | `account.setProfilePicture` | Метод предназначен для установки аватара аккаунта | [SetProfilePicture](https://green-api.com/docs/api/account/SetProfilePicture/) | 138 | | `account.getAuthorizationCode` | Метод предназначен для авторизации инстанса по номеру телефона | [GetAuthorizationCode](https://green-api.com/docs/api/account/GetAuthorizationCode/) | 139 | | `groups.createGroup` | Метод предназначен для создания группового чата | [CreateGroup](https://green-api.com/docs/api/groups/CreateGroup/) | 140 | | `groups.updateGroupName` | Метод изменяет наименование группового чата | [UpdateGroupName](https://green-api.com/docs/api/groups/UpdateGroupName/) | 141 | | `groups.getGroupData` | Метод получает данные группового чата | [GetGroupData](https://green-api.com/docs/api/groups/GetGroupData/) | 142 | | `groups.addGroupParticipant` | Метод добавляет участника в групповой чат | [AddGroupParticipant](https://green-api.com/docs/api/groups/AddGroupParticipant/) | 143 | | `groups.removeGroupParticipant` | Метод удаляет участника из группового чата | [RemoveGroupParticipant](https://green-api.com/docs/api/groups/RemoveGroupParticipant/) | 144 | | `groups.setGroupAdmin` | Метод назначает участника группового чата администратором | [SetGroupAdmin](https://green-api.com/docs/api/groups/SetGroupAdmin/) | 145 | | `groups.removeAdmin` | Метод лишает участника прав администрирования группового чата | [RemoveAdmin](https://green-api.com/docs/api/groups/RemoveAdmin/) | 146 | | `groups.setGroupPicture` | Метод устанавливает аватар группы | [SetGroupPicture](https://green-api.com/docs/api/groups/SetGroupPicture/) | 147 | | `groups.leaveGroup` | Метод производит выход пользователя текущего аккаунта из группового чата | [LeaveGroup](https://green-api.com/docs/api/groups/LeaveGroup/) | 148 | | `journals.getChatHistory` | Метод возвращает историю сообщений чата | [GetChatHistory](https://green-api.com/docs/api/journals/GetChatHistory/) | 149 | | `journals.lastIncomingMessages` | Метод возвращает крайние входящие сообщения аккаунта | [LastIncomingMessages](https://green-api.com/docs/api/journals/LastIncomingMessages/) | 150 | | `journals.lastOutgoingMessages` | Метод возвращает крайние отправленные сообщения аккаунта | [LastOutgoingMessages](https://green-api.com/docs/api/journals/LastOutgoingMessages/) | 151 | | `queues.showMessagesQueue` | Метод предназначен для получения списка сообщений, находящихся в очереди на отправку | [ShowMessagesQueue](https://green-api.com/docs/api/queues/ShowMessagesQueue/) | 152 | | `queues.clearMessagesQueue` | Метод предназначен для очистки очереди сообщений на отправку | [ClearMessagesQueue](https://green-api.com/docs/api/queues/ClearMessagesQueue/) | 153 | | `marking.readChat` | Метод предназначен для отметки сообщений в чате прочитанными | [ReadChat](https://green-api.com/docs/api/marks/ReadChat/) | 154 | | `receiving.receiveNotification` | Метод предназначен для получения одного входящего уведомления из очереди уведомлений | [ReceiveNotification](https://green-api.com/docs/api/receiving/technology-http-api/ReceiveNotification/) | 155 | | `receiving.deleteNotification` | Метод предназначен для удаления входящего уведомления из очереди уведомлений | [DeleteNotification](https://green-api.com/docs/api/receiving/technology-http-api/DeleteNotification/) | 156 | | `receiving.downloadFile` | Метод предназначен для скачивания принятых и отправленных файлов | [DownloadFile](https://green-api.com/docs/api/receiving/files/DownloadFile/) | 157 | | `sending.sendMessage` | Метод предназначен для отправки текстового сообщения в личный или групповой чат | [SendMessage](https://green-api.com/docs/api/sending/SendMessage/) | 158 | | `sending.sendButtons` | Метод предназначен для отправки сообщения с кнопками в личный или групповой чат | [SendButtons](https://green-api.com/docs/api/sending/SendButtons/) | 159 | | `sending.sendTemplateButtons` | Метод предназначен для отправки сообщения с интерактивными кнопками из перечня шаблонов в личный или групповой чат | [SendTemplateButtons](https://green-api.com/docs/api/sending/SendTemplateButtons/) | 160 | | `sending.sendListMessage` | Метод предназначен для отправки сообщения с кнопкой выбора из списка значений в личный или групповой чат | [SendListMessage](https://green-api.com/docs/api/sending/SendListMessage/) | 161 | | `sending.sendFileByUpload` | Метод предназначен для отправки файла, загружаемого через форму (form-data) | [SendFileByUpload](https://green-api.com/docs/api/sending/SendFileByUpload/) | 162 | | `sending.sendFileByUrl` | Метод предназначен для отправки файла, загружаемого по ссылке | [SendFileByUrl](https://green-api.com/docs/api/sending/SendFileByUrl/) | 163 | | `sending.sendLocation` | Метод предназначен для отправки сообщения геолокации | [SendLocation](https://green-api.com/docs/api/sending/SendLocation/) | 164 | | `sending.sendContact` | Метод предназначен для отправки сообщения с контактом | [SendContact](https://green-api.com/docs/api/sending/SendContact/) | 165 | | `sending.sendLink` | Метод предназначен для отправки сообщения со ссылкой, по которой будут добавлены превью изображения, заголовок и описание | [SendLink](https://green-api.com/docs/api/sending/SendLink/) | 166 | | `sending.forwardMessages` | Метод предназначен для пересылки сообщений в личный или групповой чат | [ForwardMessages](https://green-api.com/docs/api/sending/ForwardMessages/) | 167 | | `serviceMethods.checkWhatsapp` | Метод проверяет наличие аккаунта WhatsApp на номере телефона | [CheckWhatsapp](https://green-api.com/docs/api/service/CheckWhatsapp/) | 168 | | `serviceMethods.getAvatar` | Метод возвращает аватар корреспондента или группового чата | [GetAvatar](https://green-api.com/docs/api/service/GetAvatar/) | 169 | | `serviceMethods.getContacts` | Метод предназначен для получения списка контактов текущего аккаунта | [GetContacts](https://green-api.com/docs/api/service/GetContacts/) | 170 | | `serviceMethods.getContactInfo` | Метод предназначен для получения информации о контакте | [GetContactInfo](https://green-api.com/docs/api/service/GetContactInfo/) | 171 | | `serviceMethods.editMessage` | Метод редактирует сообщение в чате | [EditMessage](https://green-api.com/docs/api/service/editMessage/) | 172 | | `serviceMethods.deleteMessage` | Метод удаляет сообщение из чата | [DeleteMessage](https://green-api.com/docs/api/service/deleteMessage/) | 173 | | `serviceMethods.archiveChat` | Метод архивирует чат | [ArchiveChat](https://green-api.com/docs/api/service/archiveChat/) | 174 | | `serviceMethods.unarchiveChat` | Метод разархивирует чат | [UnarchiveChat](https://green-api.com/docs/api/service/unarchiveChat/) | 175 | | `serviceMethods.setDisappearingChat` | Метод предназначен для изменения настроек исчезающих сообщений в чатах | [SetDisappearingChat](https://green-api.com/docs/api/service/SetDisappearingChat/) | 176 | | `webhooks.startReceivingNotifications` | Метод предназначен для старта получения новых уведомлений | | 177 | | `webhooks.stopReceivingNotifications` | Метод предназначен для остановки получения новых уведомлений | | 178 | | `statuses.sendTextStatus` | Метод предназначен для отправки текстового статуса | [SendTextStatus](https://green-api.com/docs/api/statuses/SendTextStatus/) | 179 | | `statuses.sendVoiceStatus` | Метод предназначен для отправки голосового статуса | [SendVoiceStatus](https://green-api.com/docs/api/statuses/SendVoiceStatus/) | 180 | | `statuses.sendMediaStatus` | Метод предназначен для отправки медиа-файлов | [SendMediaStatus](https://green-api.com/docs/api/statuses/SendMediaStatus/) | 181 | | `statuses.getIncomingStatuses` | Метод возвращает крайние входящие статусы аккаунта | [GetIncomingStatuses](https://green-api.com/docs/api/statuses/GetIncomingStatuses/) | 182 | | `statuses.getOutgoingStatuses` | Метод возвращает крайние отправленные статусы аккаунта | [GetOutgoingStatuses](https://green-api.com/docs/api/statuses/GetOutgoingStatuses/) | 183 | | `statuses.getStatusStatistic` | Метод возвращает массив получателей со статусами, отмеченных как отправлено/доставлено/прочитано, для данного статуса | [GetStatusStatistic](https://green-api.com/docs/api/statuses/GetStatusStatistic/) | 184 | 185 | ## Документация по методам сервиса 186 | 187 | [https://green-api.com/docs/api/](https://green-api.com/docs/api/) 188 | 189 | ## Лицензия 190 | 191 | Лицензировано на условиях MIT. Смотрите файл [LICENSE](LICENSE) 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # whatsapp-api-client-php 2 | [![Total Downloads](https://poser.pugx.org/green-api/whatsapp-api-client-php/downloads?format=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 3 | [![Downloads per month](https://img.shields.io/packagist/dm/green-api/whatsapp-api-client-php.svg?style=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 4 | [![License](https://img.shields.io/badge/license-Apache%202.0-red.svg?style=flat-square)](https://packagist.org/packages/green-api/whatsapp-api-client-php) 5 | 6 | - [Документация на русском языке](README_RUS.md) 7 | 8 | PHP library for integration with WhatsApp messenger via API of [green-api.com](https://green-api.com/en/) service. To use the library you have to get a registration token and an account id in the [personal area](https://console.green-api.com). There is a free developer account tariff plan. 9 | 10 | ## API 11 | 12 | You can find REST API documentation by [url](https://green-api.com/en/docs/api/). The library is a wrapper for REST API, so the documentation at the above url applies to the library as well. 13 | 14 | ## Installation 15 | 16 | Via [Composer](https://getcomposer.org): 17 | 18 | ```bash 19 | composer require green-api/whatsapp-api-client-php 20 | ``` 21 | 22 | ## Import 23 | 24 | ``` 25 | require './vendor/autoload.php'; 26 | ``` 27 | ## Authorization 28 | 29 | To send a message or to execute some other Green-API method, you have to have the WhatsApp account in the phone application to be authorized. To authorize your account please go to the [personal area](https://console.green-api.com) and scan a QR-code using the WhatsApp application. 30 | 31 | ## Running index.php 32 | 33 | ``` 34 | php -S localhost:8080 35 | ``` 36 | 37 | ## Examples 38 | 39 | ### How to initialize an object 40 | 41 | ``` 42 | $greenApi = new GreenApiClient( ID_INSTANCE, API_TOKEN_INSTANCE ); 43 | ``` 44 | 45 | ### Sending a text message to a WhatsApp number 46 | 47 | ``` 48 | $result = $greenApi->sending->sendMessage('11001234567@g.us', 'Message text'); 49 | ``` 50 | 51 | Example url: [sendTextMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendTextMessage.php) 52 | 53 | Please note that keys can be obtained from environment variables: 54 | ``` 55 | sending->sendFileByUrl( 66 | '11001234567@c.us', 'https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 67 | 'googlelogo_color_272x92dp.png', 'Google logo'); 68 | ``` 69 | 70 | Example url: [sendPictureByLink.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByLink.php) 71 | 72 | ### Sending an image by uploading from the disk 73 | 74 | ``` 75 | $result = $greenApi->sending->sendFileByUpload('11001234567@c.us', 76 | 'C:\Games\PicFromDisk.png', 'PicFromDisk.jpg', 'Picture from disk'); 77 | ``` 78 | 79 | Example url: [sendPictureByUpload.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByUpload.php) 80 | 81 | ### Group creation and sending a message to the group 82 | 83 | ``` 84 | $chatIds = [ 85 | '11001234567@c.us' 86 | ]; 87 | $resultCreate = $greenApi->groups->createGroup('GroupName', $chatIds ); 88 | 89 | if ($resultCreate->code == 200) 90 | $resultSend = $greenApi->sending->sendMessage($resultCreate->data->chatId, 91 | 'Message text'); 92 | ``` 93 | 94 | IMPORTANT: If one tries to create a group with a non-existent number, WhatsApp 95 | may block the sender's number. The number in the example is non-existent. 96 | 97 | Example url: [createGroupAndSendMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/createGroupAndSendMessage.php) 98 | 99 | ### Receive incoming messages by HTTP API 100 | 101 | The general concept of receiving data in the Green API is described [here](https://green-api.com/en/docs/api/receiving/) 102 | To start receiving messages by the HTTP API you need to execute the library method: 103 | 104 | ``` 105 | greenAPI.webhooks.startReceivingNotifications(onEvent) 106 | ``` 107 | 108 | onEvent - your method which should contain parameters: 109 | Parameter | Description 110 | ----- | ----- 111 | typewebhook | received message type (string) 112 | body | message body (json) 113 | 114 | Message body types and formats [here](https://green-api.com/en/docs/api/receiving/notifications-format/) 115 | 116 | This method will be called when an incoming message is received. Next, process messages according to the business logic of your system. 117 | 118 | ## Examples list 119 | 120 | | Description | Module | 121 | |----------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------| 122 | | Example of sending text | [sendTextMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendTextMessage.php) | 123 | | Example of sending a picture by URL | [sendPictureByLink.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByLink.php) | 124 | | Example of sending a picture by uploading from the disk | [sendPictureByUpload.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/sendPictureByUpload.php) | 125 | | Example of a group creation and sending a message to the group | [createGroupAndSendMessage.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/createGroupAndSendMessage.php) | 126 | | Example of incoming webhooks receiving | [receiveNotification.php](https://github.com/green-api/whatsapp-api-client-php/blob/master/examples/receiveNotification.php) | 127 | 128 | ## The full list of the library methods 129 | 130 | | API method | Description | Documentation link | 131 | |----------------------------------------|--------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| 132 | | `account.getSettings` | The method is designed to get the current settings of the account | [GetSettings](https://green-api.com/en/docs/api/account/GetSettings/) | 133 | | `account.setSettings` | The method is designed to set the account settings | [SetSettings](https://green-api.com/en/docs/api/account/SetSettings/) | 134 | | `account.getStateInstance` | The method is designed to get the state of the account | [GetStateInstance](https://green-api.com/en/docs/api/account/GetStateInstance/) | 135 | | `account.getStatusInstance` | The method is designed to get the socket connection state of the account instance with WhatsApp | [GetStatusInstance](https://green-api.com/en/docs/api/account/GetStatusInstance/) | 136 | | `account.reboot` | The method is designed to restart the account | [Reboot](https://green-api.com/en/docs/api/account/Reboot/) | 137 | | `account.logout` | The method is designed to unlogin the account | [Logout](https://green-api.com/en/docs/api/account/Logout/) | 138 | | `account.qr` | The method is designed to get a QR code | [QR](https://green-api.com/en/docs/api/account/QR/) | 139 | | `account.getAuthorizationCode` | The method is designed to authorize an instance by phone number | [GetAuthorizationCode](https://green-api.com/en/docs/api/account/GetAuthorizationCode/) | 140 | | `account.setProfilePicture` | The method is designed to set the avatar of the account | [SetProfilePicture](https://green-api.com/en/docs/api/account/SetProfilePicture/) | 141 | | `groups.createGroup` | The method is designed to create a group chat | [CreateGroup](https://green-api.com/en/docs/api/groups/CreateGroup/) | 142 | | `groups.updateGroupName` | The method changes the name of the group chat | [UpdateGroupName](https://green-api.com/en/docs/api/groups/UpdateGroupName/) | 143 | | `groups.getGroupData` | The method gets group chat data | [GetGroupData](https://green-api.com/en/docs/api/groups/GetGroupData/) | 144 | | `groups.addGroupParticipant` | The method adds a participant to the group chat | [AddGroupParticipant](https://green-api.com/en/docs/api/groups/AddGroupParticipant/) | 145 | | `groups.removeGroupParticipant` | The method removes the participant from the group chat | [RemoveGroupParticipant](https://green-api.com/en/docs/api/groups/RemoveGroupParticipant/) | 146 | | `groups.setGroupAdmin` | The method designates a member of a group chat as an administrator | [SetGroupAdmin](https://green-api.com/en/docs/api/groups/SetGroupAdmin/) | 147 | | `groups.removeAdmin` | The method deprives the participant of group chat administration rights | [RemoveAdmin](https://green-api.com/en/docs/api/groups/RemoveAdmin/) | 148 | | `groups.setGroupPicture` | The method sets the avatar of the group | [SetGroupPicture](https://green-api.com/en/docs/api/groups/SetGroupPicture/) | 149 | | `groups.leaveGroup` | The method logs the user of the current account out of the group chat | [LeaveGroup](https://green-api.com/en/docs/api/groups/LeaveGroup/) | 150 | | `journals.getChatHistory` | The method returns the chat message history | [GetChatHistory](https://green-api.com/en/docs/api/journals/GetChatHistory/) | 151 | | `journals.lastIncomingMessages` | The method returns the most recent incoming messages of the account | [LastIncomingMessages](https://green-api.com/en/docs/api/journals/LastIncomingMessages/) | 152 | | `journals.lastOutgoingMessages` | The method returns the last sent messages of the account | [LastOutgoingMessages](https://green-api.com/en/docs/api/journals/LastOutgoingMessages/) | 153 | | `queues.showMessagesQueue` | The method is designed to get the list of messages that are in the queue to be sent | [ShowMessagesQueue](https://green-api.com/en/docs/api/queues/ShowMessagesQueue/) | 154 | | `queues.clearMessagesQueue` | The method is designed to clear the queue of messages to be sent | [ClearMessagesQueue](https://green-api.com/en/docs/api/queues/ClearMessagesQueue/) | 155 | | `marking.readChat` | The method is designed to mark chat messages as read | [ReadChat](https://green-api.com/en/docs/api/marks/ReadChat/) | 156 | | `receiving.receiveNotification` | The method is designed to receive a single incoming notification from the notification queue | [ReceiveNotification](https://green-api.com/en/docs/api/receiving/technology-http-api/ReceiveNotification/) | 157 | | `receiving.deleteNotification` | The method is designed to remove an incoming notification from the notification queue | [DeleteNotification](https://green-api.com/en/docs/api/receiving/technology-http-api/DeleteNotification/) | 158 | | `receiving.downloadFile` | The method is for downloading received and sent files | [DownloadFile](https://green-api.com/en/docs/api/receiving/files/DownloadFile/) | 159 | | `sending.sendMessage` | The method is designed to send a text message to a personal or group chat | [SendMessage](https://green-api.com/en/docs/api/sending/SendMessage/) | 160 | | `sending.sendButtons` | The method is designed to send a message with buttons to a personal or group chat | [SendButtons](https://green-api.com/en/docs/api/sending/SendButtons/) | 161 | | `sending.sendTemplateButtons` | The method is designed to send a message with interactive buttons from the list of templates in a personal or group chat | [SendTemplateButtons](https://green-api.com/en/docs/api/sending/SendTemplateButtons/) | 162 | | `sending.sendListMessage` | The method is designed to send a message with a selection button from a list of values to a personal or group chat | [SendListMessage](https://green-api.com/en/docs/api/sending/SendListMessage/) | 163 | | `sending.sendFileByUpload` | The method is designed to send a file loaded through a form (form-data) | [SendFileByUpload](https://green-api.com/en/docs/api/sending/SendFileByUpload/) | 164 | | `sending.sendFileByUrl` | The method is designed to send a file downloaded via a link | [SendFileByUrl](https://green-api.com/en/docs/api/sending/SendFileByUrl/) | 165 | | `sending.sendLocation` | The method is designed to send a geolocation message | [SendLocation](https://green-api.com/en/docs/api/sending/SendLocation/) | 166 | | `sending.sendContact` | The method is for sending a message with a contact | [SendContact](https://green-api.com/en/docs/api/sending/SendContact/) | 167 | | `sending.sendLink` | The method is designed to send a message with a link that will add an image preview, title and description | [SendLink](https://green-api.com/en/docs/api/sending/SendLink/) | 168 | | `sending.forwardMessages` | The method is designed for forwarding messages to a personal or group chat | [ForwardMessages](https://green-api.com/en/docs/api/sending/ForwardMessages/) | 169 | | `serviceMethods.checkWhatsapp` | The method checks if there is a WhatsApp account on the phone number | [CheckWhatsapp](https://green-api.com/en/docs/api/service/CheckWhatsapp/) | 170 | | `serviceMethods.getAvatar` | The method returns the avatar of the correspondent or group chat | [GetAvatar](https://green-api.com/en/docs/api/service/GetAvatar/) | 171 | | `serviceMethods.getContacts` | The method is designed to get a list of contacts of the current account | [GetContacts](https://green-api.com/en/docs/api/service/GetContacts/) | 172 | | `serviceMethods.getContactInfo` | The method is designed to obtain information about the contact | [GetContactInfo](https://green-api.com/en/docs/api/service/GetContactInfo/) | 173 | | `serviceMethods.editMessage` | The method edits a message in a chat | [EditMessage](https://green-api.com/en/docs/api/service/editMessage/) | 174 | | `serviceMethods.deleteMessage` | The method deletes the message from chat | [DeleteMessage](https://green-api.com/en/docs/api/service/deleteMessage/) | 175 | | `serviceMethods.archiveChat` | The method archives the chat | [ArchiveChat](https://green-api.com/en/docs/api/service/archiveChat/) | 176 | | `serviceMethods.unarchiveChat` | The method unarchives the chat | [UnarchiveChat](https://green-api.com/en/docs/api/service/unarchiveChat/) | 177 | | `serviceMethods.setDisappearingChat` | The method is designed to change the settings of disappearing messages in chats | [SetDisappearingChat](https://green-api.com/en/docs/api/service/SetDisappearingChat/) | 178 | | `webhooks.startReceivingNotifications` | The method is designed to start receiving new notifications | | 179 | | `webhooks.stopReceivingNotifications` | The method is designed to stop receiving new notifications | | 180 | | `statuses.sendTextStatus` | The method is aimed for sending a text status | [SendTextStatus](https://green-api.com/en/docs/api/statuses/SendTextStatus/) | 181 | | `statuses.sendVoiceStatus` | The method is aimed for sending a voice status | [SendVoiceStatus](https://green-api.com/en/docs/api/statuses/SendVoiceStatus/) | 182 | | `statuses.sendMediaStatus` | The method is aimed for sending a pictures or video status | [SendMediaStatus](https://green-api.com/en/docs/api/statuses/SendMediaStatus/) | 183 | | `statuses.getIncomingStatuses` | The method returns the incoming status messages of the instance | [GetIncomingStatuses](https://green-api.com/en/docs/api/statuses/GetIncomingStatuses/) | 184 | | `statuses.getOutgoingStatuses` | The method returns the outgoing statuses of the account | [GetOutgoingStatuses](https://green-api.com/en/docs/api/statuses/GetOutgoingStatuses/) | 185 | | `statuses.getStatusStatistic` | The method returns an array of recipients marked sent/delivered/read for a given status | [GetStatusStatistic](https://green-api.com/en/docs/api/statuses/GetStatusStatistic/) | 186 | 187 | ## Service methods documentation 188 | 189 | [https://green-api.com/en/docs/api/](https://green-api.com/en/docs/api/) 190 | 191 | ## License 192 | 193 | Licensed under MIT terms. Please see file [LICENSE](LICENSE) 194 | --------------------------------------------------------------------------------