Bölüm 1: Okumaya Zamanınız Yoksa
- Bilinmeyen bir komuta yanıt, bu talimatlarınız veya karşılama mesajınız olabilir;
- Normal mesaj gönderme;
- Resim gönderme;
- Dosya gönderme;
- Video gönderme;
- Kişi (vCard) gönderme;
- Ürün gönderme;
- Yeni bir grup oluşturma, davetiye gönderme ve gruba mesaj gönderme;
- Gelen mesajları almak ve okumak;
Ve yardıma ihtiyacınız olursa, sadece web sitemizdeki destek sohbetine yazın.
Hangi sağlayıcıyı seçeceğinize karar veriyorsanız veya WhatsApp Business API ile WhatsApp API arasındaki farkı tam olarak anlamadıysanız, sağlayıcıları, işlevselliği, fiyatları ve mevcut çözümleri karşılaştıracağımız kılavuzumuzu incelemeniz yararlı olacaktır. Bu, herkesin hangi API'yi ve hangi sağlayıcıyı seçeceğine karar vermesi için faydalı olacaktır. Öyleyse, "WhatsApp API nasıl seçilir? Karşılaştırma."
WhatsApp Botu Neden Oluşturmalısınız?
- WhatsApp API ile nasıl çalışılacağını;
- PHP üzerinde chat-bot oluşturmanın inceliklerini;
- Müşterilerle etkileşiminizi otomatikleştirmeyi ve iyileştirmeyi;
Başlamaya Hazırlık - İhtiyacınız Olanlar
- Whapi.Cloud Hesabı. WhatsApp API ile çalışmak için Whapi.Cloud üzerinde bir hesaba ihtiyacınız olacak. Bu, geliştiricilere WhatsApp otomasyonu ve API dokümantasyonu için yöntemler sunan bir sağlayıcıdır. Bugün itibariyle Whapi.Cloud, WhatsApp API'ye uygun fiyatlı erişim sağlayan en işlevsel ve stabil sağlayıcıdır. Kayıt olduktan sonra, PHP uygulamanız/entegrasyonunuzun mesajlaşma uygulamasıyla etkileşim kurmasını sağlayacak bireysel bir API anahtar-tokenı ile ücretsiz bir kanal alacaksınız.
- PHP Sunucusu veya Yerel Geliştirme. Botunuzu yerel olarak test etmeye karar verirseniz ve Webhook aracılığıyla WhatsApp ile etkileşime girmesini istiyorsanız, ngrok gibi araçları kullanabilirsiniz. Bu uygulama, yerel sunucunuza güvenli tüneller oluşturarak testleriniz için geçici genel URL'ler sağlar. Sunucunuzun yeni mesajlar aldığında betiğimizi çağırabilmesi için, kanal ayarlarında WebHook URL'sini belirtmemiz gerekecek. Bunun hakkında aşağıda ayrıca bahsedeceğiz.
Whapi.Cloud Aracılığıyla WhatsApp API'sini Kullanma
![open WhatsApp on your mobile device, go to Settings -> Connected devices](../assets/img/blog/start-whatsapp-api-phone1.png)
![Scan the QR code in your WhatsApp](../assets/img/blog/start-whatsapp-api-phone2.png)
![Whatsapp API start working](../assets/img/blog/scan-qr-for-api.png)
![channels settings whatsapp bot](../assets/img/blog/first-step-whatsapp-api.png)
Kolaylık olması için kanala bir isim verin (bu arada, API'miz otomatik olarak standart veya işlevsellikleri genişletilmiş işletme sürümünü kullanıp kullanmadığınızı tespit edecektir). Daha sonra webhook ayarları ve diğer parametreler sizin tercihinize göre ayarlanabilir. Ancak, bu adımları daha sonra yapabilir ve bu aşamayı atlayabilirsiniz.
Kanalınızı etkinleştirdikten sonra, limitler bölümünde API tokeninizi bulun. Bu token, API'ye yapılan isteklerde kimlik doğrulama için kritik öneme sahiptir. Genellikle, Bearer Token olarak istek başlıklarında veya API'ye nasıl erişildiğine bağlı olarak bir parametre olarak iletilir.
Whapi.Cloud API, WhatsApp ile etkileşim için birçok yöntem sunar, gerçekten de mesajlaşma uygulamasının temel özelliklerini ve işlevlerini otomatikleştirmenize olanak tanır. Kanal sayfasında, mevcut tüm yöntemleri inceleyebilir ve deneyebilirsiniz. Geliştiriciler için kolaylık sağlamak amacıyla, her işlev kod örnekleri ve yerinde test imkanı ile donatılmış özel bir geliştirici merkezi sağlanmıştır, sunucudan gelen yanıtları ve sonuçları gösterir.
Bu, entegrasyon sürecini maksimum düzeyde basitleştirir ve hızlandırır, beğeneceksiniz! Whapi.Cloud'un avantajlarından biri, bağlantının kolaylığı ve hızıdır, bu da sadece birkaç dakika içinde WhatsApp ile etkileşime başlamanıza olanak tanır.
Webhook Nedir ve Nasıl Ayarlanır?
Webhook'larla çalışmanın tüm inceliklerini bilgi bankamızda ayrıntılı olarak ele aldık: Webhook'lar hakkındaki makaleyi görüntüleyin
![Whatsapp channel settings](../assets/img/blog/settings-whapi.png)
![set webhook for whatsapp bot](../assets/img/blog/Webhooks-settings-Whatsapp-Api.png)
PHP'de Botun Temelini Oluşturma
Mesaj Gönderme ve Alma
config.php
return [
// API endpoint URL
"apiUrl" => "https://gate.whapi.cloud",
// API token from your channel
"token" => "YOUR CHANNEL TOKEN",
// The ID of the group to which we will send the message. Use to find out the ID: https://whapi.readme.io/reference/getgroups
"group" => '[email protected]',
// The ID of the product we will send for the example. Create a product in your WhatsApp and find out the product ID: https://whapi.readme.io/reference/getproducts
"product" => '6559353560856703',
// Bot`s URL. Webhook Link to your server. At ( {server link}/messages ), when POST is requested, processing occurs in index.php
"botUrl" => "https://yoursite.com/messages"
];
index.php
require '../vendor/autoload.php';
use GuzzleHttp\Client;
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
// Don't forget to put your token in config.php
$config = require './config.php';
$app = new App();
$client = new Client([
'base_uri' => $config['apiUrl']
]);
// Commands for example bot
const COMMANDS = [
'TEXT' => 'Simple text message',
'IMAGE' => 'Send image',
'DOCUMENT' => 'Send document',
'VIDEO' => 'Send video',
'CONTACT' => 'Send contact',
'PRODUCT' => 'Send product',
'GROUP_CREATE' => 'Create group',
'GROUP_TEXT' => 'Simple text message for the group',
'GROUPS_IDS' => 'Get the id\'s of your three groups'
];
// Url files for example
const FILES = [
'IMAGE' => './files/file_example_JPG_100kB.jpg',
'DOCUMENT' => './files/file-example_PDF_500_kB.pdf',
'VIDEO' => './files/file_example_MP4_480_1_5MG.mp4',
'VCARD' => './files/sample-vcard.txt'
];
function sendWhapiRequest($endpoint, $params = [], $method = 'POST')
{
global $config, $client;
$url = $config['apiUrl'] . '/' . $endpoint;
$options = [
'headers' => [
'Authorization' => 'Bearer ' . $config['token'],
],
];
if ($params && count($params) > 0) {
if ($method === 'GET') {
$url .= '?' . http_build_query($params);
} else {
if(isset($params['media'])){
$options['multipart'] = toFormData($params);
}else{
$options['headers']['Content-Type'] = 'application/json';
$options['body'] = json_encode($params);
}
}
}
echo '$options: ' . print_r($options, true);
$response = $client->request($method, $url, $options);
$json = json_decode($response->getBody()->getContents(), true);
echo 'Whapi response: ' . print_r($json, true);
return $json;
}
function toFormData($params)
{
$multipart = [];
foreach ($params as $name => $contents) {
$multipart[] = ['name' => $name, 'contents' => $contents];
}
return $multipart;
}
// Call this function if you want to setup a webhook through the API. In this example it is not called: you will need to go to the channel settings in your personal cabinet and set the webhook link like {link to your server}/messages
function setHook()
{
global $config;
if ($config['botUrl']) {
sendWhapiRequest('settings', [
'webhooks' => [
[
'url' => $config['botUrl'],
'events' => [
[
'type' => 'messages',
'method' => 'post'
]
],
'mode' => 'body'
]
]
], 'PATCH');
}
}
$app->get('/', function (Request $request, Response $response) {
return $response->write('Bot is running');
});
$app->post('/messages', function (Request $request, Response $response) use ($config) {
$data = json_decode($request->getBody(), true);
$messages = $data['messages'] ?? [];
foreach ($messages as $message) {
if ($message['from_me']) {
continue;
}
$sender = ['to' => $message['chat_id']];
$endpoint = 'messages/text';
$textBody = trim($message['text']['body'] ?? '');
$commandIndex = is_numeric($textBody) ? (int)$textBody - 1 : null;
$commands = array_keys(COMMANDS);
$command = $commands[$commandIndex] ?? null;
switch ($command) {
case 'TEXT':
$sender['body'] = 'Simple text message';
break;
case 'IMAGE':
$sender['caption'] = 'Text under the photo.';
$sender['media'] = fopen(FILES['IMAGE'], 'r');
$endpoint = 'messages/image';
break;
case 'DOCUMENT':
$sender['caption'] = 'Text under the document.';
$sender['media'] = fopen(FILES['DOCUMENT'], 'r');
$endpoint = 'messages/document';
break;
case 'VIDEO':
$sender['caption'] = 'Text under the video.';
$sender['media'] = fopen(FILES['VIDEO'], 'r');
$endpoint = 'messages/video';
break;
case 'CONTACT':
$sender['name'] = 'Whapi Test';
$sender['vcard'] = file_get_contents(FILES['VCARD']);
$endpoint = 'messages/contact';
break;
case 'PRODUCT':
// Replace with your product ID
$endpoint = "business/products/{$config['product']}";
break;
case 'GROUP_CREATE':
$groupSettings = [
'subject' => 'Whapi.Cloud Test',
'participants' => [$message['from']]
];
$groupResponse = sendWhapiRequest('groups', $groupSettings, 'POST');
$sender['body'] = $groupResponse['group_id'] ? "Group created. Group id: {$groupResponse['group_id']}" : 'Error';
$endpoint = 'messages/text';
break;
case 'GROUP_TEXT':
$sender['to'] = $config['group'];
$sender['body'] = 'Simple text message for the group';
break;
case 'GROUPS_IDS':
$groupsResponse = sendWhapiRequest('groups', ['count' => 3], 'GET');
if (!empty($groupsResponse['groups'])) {
$groupIds = array_map(function ($group, $i) {
return ($i + 1) . ". {$group['id']} - {$group['name']}";
}, $groupsResponse['groups'], array_keys($groupsResponse['groups']));
$sender['body'] = implode(",\n ", $groupIds);
} else {
$sender['body'] = 'No groups';
}
break;
default:
$sender['body'] = "Hi. Send me a number from the list. Don't forget to change the actual data in the code! \n\n" .
implode("\n", array_map(function ($text) {
static $i = 0;
$i++;
return ($i) . ". $text";
}, COMMANDS, array_keys(COMMANDS)));
break;
}
try {
sendWhapiRequest($endpoint, $sender);
} catch (\Exception $e) {
error_log($e->getMessage());
return $response->withStatus(500)->write('Error: ' . $e->getMessage());
}
}
return $response->withStatus(200)->write('Ok');
});
$app->run();
Gelişmiş Özellikler
![Whatsapp API send message docs](../assets/img/blog/whatsapp-api-docs.png)
![groups management whatsapp api](../assets/img/blog/groups-management-whatsapp-api.png)
Resimli bir medya mesajı gönderin
const BASE_URL = 'https://gate.whapi.cloud/';
$token = 'bg3FeZJ6jWGw32g03PRnoNkKO7k03GtX'; // Your API token
$data = array (
'media' => 'https://upload.wikimedia.org/wikipedia/commons/b/ba/Leonardo_self.jpg',
'to' => '[email protected]',
'mime_type' => 'jpg',
'caption' => 'Leonardo Self'
);
$data_json = json_encode($data);
$url = BASE_URL . 'messages/image';
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Authorization: Bearer '.$token,
'Content-Type: application/json',
'Accept: application/json'
),
'content' => $data_json
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
WhatsApp API üzerinden dosya gönder
const BASE_URL = 'https://gate.whapi.cloud/';// Ensure that the PHP allow_url_fopen setting is enabled, as file_get_contents requires it for URL handling.
$token = 'bg3FeZJ6jWGw32g03PRnoNkKO7k03GtX'; // Your API token
$data = array (
'to' => '[email protected]',
'media' => 'data:application/octet-stream;name=site.webmanifest;base64,ewogICAgIm5hbWUiOiAiIiwKICAgICJzaG9ydF9uYW1lIjogIiIsCiAgICAiaWNvbnMiOiBbCiAgICAgICAgewogICAgICAgICAgICAic3JjIjogIi9hbmRyb2lkLWNocm9tZS0xOTJ4MTkyLnBuZyIsCiAgICAgICAgICAgICJzaXplcyI6ICIxOTJ4MTkyIiwKICAgICAgICAgICAgInR5cGUiOiAiaW1hZ2UvcG5nIgogICAgICAgIH0KICAgIF0sCiAgICAidGhlbWVfY29sb3IiOiAiI2ZmZmZmZiIsCiAgICAiYmFja2dyb3VuZF9jb2xvciI6ICIjZmZmZmZmIiwKICAgICJkaXNwbGF5IjogInN0YW5kYWxvbmUiCn0K',
'filename' => 'webmanifest',
'caption' => "It's my file",
'view_once' => true
);
$data_json = json_encode($data);
$url = BASE_URL . 'messages/document';
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Authorization: Bearer '.$token,
'Content-Type: application/json',
'Accept: application/json'
),
'content' => $data_json
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;