Skip to content

Instantly share code, notes, and snippets.

@xadina02
Created March 25, 2024 07:17
Show Gist options
  • Save xadina02/d23c5aeb7fde894d03366f24970b01e0 to your computer and use it in GitHub Desktop.
Save xadina02/d23c5aeb7fde894d03366f24970b01e0 to your computer and use it in GitHub Desktop.
The functionality implemented is that of sending and receiving messages via WhatsApp. It tests four scenarios: sendingg data via WhatsApp, receiving text messages, media messages and location messages via WhatsApp.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WhatsAppController;
use App\Http\Controllers\ConfigurationController;
Route::get('/', function () {
return view('welcome');
});
Route::post('whatsapp/1/message', [WhatsAppController::class, 'handleMessageTemplate']);
Route::post('whatsapp/webhook', [WhatsAppController::class, 'webhook']);
<?php
/**
* This models the scenario where the application sends template messages in response to user messages. This is important for giving users a sense of assurance, for efficiency, consistency and branding.
* Expected Inputs:
* - The input for this test case is a POST request to the endpoint /whatsapp/1/message, containing a JSON payload with the message details.
* - The message details include the sender number (from), recipient number (to), message ID (messageId), message content (content), and language (language).
* Expected Outputs:
* - The expected output is a JSON response indicating the status of the message sending operation.
* - The response should include details such as the recipient number, message count, message ID, and status, confirming that the message was successfully sent or is pending.
**/
test('sends data via WhatsApp', function () {
// Initiating a request to send a message to my applications WhatsApp, leveraging the infobip API
$response = $this->post('/whatsapp/1/message', [
'messages' => [
[
'from' => '447860099299',
'to' => '237620438703',
'messageId' => 'f6c18def-26c1-47bf-a32d-cee385741c75',
'content' => [
'templateName' => 'message_test',
'templateData' => [
'body' => [
'placeholders' => ['Adina']
]
],
'language' => 'en'
]
]
]
]);
/** Asserting that the request was successful and that the response message conatins all necessary fields to verify the request by,
*
* verifying the destination number
* ensuring the message count is 1
* asserting that the status depicts a sent message (Along with all other properties that support the state)
*
* */
$response->assertStatus(200)->assertJson([
'messages' => [
[
"to" => "237620438703",
"messageCount" => 1,
"messageId" => "f6c18def-26c1-47bf-a32d-cee385741c75",
"status" => [
"groupId" => 1,
"groupName" => "PENDING",
"id" => 7,
"name" => "PENDING_ENROUTE",
"description" => "Message sent to next instance"
]
]
]
]);
});
/**
* This models the scenario of receiving text messages via WhatsApp
* Expected Inputs:
* - For this test case, the input is a mocked WhatsApp message received by the application at the /whatsapp/webhook endpoint.
* - The message data includes details such as sender number, recipient number, message type (TEXT), message content, and timestamp of receipt.
* Expected Outputs:
* - The expected output is a JSON response from the application indicating the success of processing the incoming message.
* - The response should include the date and time of receipt (date_and_time) and the text content of the message (text).
**/
test('receives and processes WhatsApp text messages', function () {
// Simulating the incoming WhatsApp message
$mockedMessageData = [
'results' => [
[
'from' => '237620438703',
'to' => '48123234567',
'integrationType' => 'string',
'receivedAt' => date('Y-m-d\TH:i:s.v\Z'),
'messageId' => 'f6c18def-26c1-47bf-a32d-cee385741c75',
'callbackData' => 'string',
'message' => [
'type' => 'TEXT',
'text' => 'Hello Ushahidi, stay tuned for subsequent reports on human rights violation!'
]
]
]
];
// Sending mock WhatsApp message to my application for processing and extraction
$response = $this->post('/whatsapp/webhook', $mockedMessageData);
/** Asserting that the request was successful and that the key fields were detected and extracted and their values match the expected results - comprising information about the messages:
*
* time and description
* */
$response->assertStatus(200)->assertJson([
"message" => "success",
"date_and_time" => date('Y-m-d\TH:i:s.v\Z'),
"text" => "Hello Ushahidi, stay tuned for subsequent reports on human rights violation!"
]);
});
/**
* This models the scenario of receiving media messages via WhatsApp
* Expected Inputs:
* - Similar to the previous test case, the input is a mocked WhatsApp message with media content (document) received by the application.
* - The message data includes sender number, recipient number, message type (DOCUMENT), media URL, caption, and timestamp of receipt.
* Expected Outputs:
* - The expected output is a JSON response indicating the successful processing of the incoming media message.
* - The response should contain the date and time of receipt (date_and_time), media URL (media_url), and media caption (media_caption).
**/
test('receives and processes WhatsApp media messages', function () {
// Simulating the incoming WhatsApp message
$mockedMessageData = [
'results' => [
[
'from' => '237620438703',
'to' => '48123234567',
'integrationType' => 'string',
'receivedAt' => date('Y-m-d\TH:i:s.v\Z'),
'messageId' => 'f6c18def-26c1-47bf-a32d-cee385741c75',
'callbackData' => 'string',
'message' => [
'type' => 'DOCUMENT', // Also: IMAGES / AUDIO
'url' => 'https://example.com/media_name.extension',
'caption' => 'document type'
]
]
]
];
// Sending mock WhatsApp message to my application for processing and extraction
$response = $this->post('/whatsapp/webhook', $mockedMessageData);
/** Asserting that the request was successful and that the key fields were detected and extracted and their values match the expected results - comprising information about the messages:
*
* time and media attachments
* */
$response->assertStatus(200)->assertJson([
"message" => "success",
"date_and_time" => date('Y-m-d\TH:i:s.v\Z'),
"media_url" => "https://example.com/media_name.extension",
"media_caption" => "document type"
]);
});
/**
* This models the scenario of receiving location messages via WhatsApp
* Expected Inputs:
* - This test case involves a mocked WhatsApp location message received by the application.
* - The message data includes sender number, recipient number, message type (LOCATION), latitude, longitude, location address, location name, location URL, and timestamp of receipt.
* Expected Outputs:
* - The expected output is a JSON response indicating the successful handling of the incoming location message.
* - The response should include the date and time of receipt (date_and_time), latitude (latitude), longitude (longitude), location address (location_address), location name (location_name), and location URL (location_url).
**/
test('receives and processes WhatsApp location messages', function () {
// Simulating the incoming WhatsApp message
$mockedMessageData = [
'results' => [
[
'from' => '237620438703',
'to' => '48123234567',
'integrationType' => 'string',
'receivedAt' => date('Y-m-d\TH:i:s.v\Z'),
'messageId' => 'f6c18def-26c1-47bf-a32d-cee385741c75',
'callbackData' => 'string',
'message' => [
'type' => 'LOCATION',
'latitude' => 3.8763,
'longitude' => 11.5079,
'address' => 'Unity Palace, Yaoundé, Cameroon',
'name' => 'Unity Palace',
'url' => 'https://www.google.com/maps/place/Unity+Palace/@3.8763,11.5079,17z/data=!3m1!4b1!4m5!3m4!1s0x105f0a3e3de3dced:0xd79b2b6f6d99370f!8m2!3d3.8763!4d11.5098'
]
]
]
];
// Sending mock WhatsApp message to my application for processing and extraction
$response = $this->post('/whatsapp/webhook', $mockedMessageData);
/** Asserting that the request was successful and that the key fields were detected and extracted and their values match the expected results - comprising information about the messages:
*
* time and location
* */
$response->assertStatus(200)->assertJson([
"message" => "success",
"date_and_time" => date('Y-m-d\TH:i:s.v\Z'),
"latitude" => 3.8763,
"longitude" => 11.5079,
"location_address" => "Unity Palace, Yaoundé, Cameroon",
"location_name" => "Unity Palace",
"location_url" => "https://www.google.com/maps/place/Unity+Palace/@3.8763,11.5079,17z/data=!3m1!4b1!4m5!3m4!1s0x105f0a3e3de3dced:0xd79b2b6f6d99370f!8m2!3d3.8763!4d11.5098"
]);
});
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class WhatsAppController extends Controller
{
public function handleMessageTemplate(Request $request)
{
$response = Http::withHeaders([
'Authorization' => 'App 037c2e76f9c87dd4d63a6cabfd397dbe-096f521e-f02e-4d30-aca8-ba408123cd3d',
'Content-Type' => 'application/json',
'Accept' => 'application/json',
])->post('https://z1y653.api.infobip.com/whatsapp/1/message/template', [
'messages' => $request->input('messages')
], [
'follow_redirects' => true
]);
return $response;
}
public function webhook(Request $request) {
// Process the incoming WhatsApp message
$messageData = $request->all();
$result = $messageData['results'][0];
// Extract date and time
$dateTime = $result['receivedAt'];
// Extract message type
$type = $result['message']['type'];
// Initialize response array
$response = ['message' => 'success', 'date_and_time' => $dateTime];
// Check message type and add relevant data to the response
switch($type) {
case 'TEXT':
$response['text'] = $result['message']['text'];
break;
case 'DOCUMENT':
$response['media_url'] = $result['message']['url'];
$response['media_caption'] = $result['message']['caption'];
break;
case 'LOCATION':
$response['latitude'] = $result['message']['latitude'];
$response['longitude'] = $result['message']['longitude'];
$response['location_address'] = $result['message']['address'];
$response['location_name'] = $result['message']['name'];
$response['location_url'] = $result['message']['url'];
break;
default:
// Handle unsupported message types
$response['message'] = 'error';
$response['error'] = 'Unsupported message type';
}
// Return extracted data
return response()->json($response);
}
}
@jatinder14
Copy link

@xadina02 Which php framework you are using ?

@xadina02
Copy link
Author

@xadina02 Which php framework you are using ?

Laravel with Laravel Pest for testing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment