✔ WhatsApp Group API: Guide for Developers
Tags: whatsapp, beginners, tutorial, php
Published: 2023-10-06 20:24:40

WhatsApp, the globally renowned messaging application, has offered a myriad of opportunities for developers to enhance its features. Automating group management stands out as a pivotal tool for businesses and community managers alike. In this guide, we'll explore how to efficiently handle various group operations using PHP.

**1. Setting Up**
Before diving into the code, ensure you have:
* Access to the WhatsApp API from [Whapi.Cloud](https://whapi.cloud). It is currently the most functional and stable provider that provides inexpensive access to WhatsApp APIs
* A working PHP environment.
* cURL enabled in your PHP configuration, as it's vital for making HTTP requests.

{% embed https://youtu.be/PlVVoWkDb08 %}

**Registration on Whapi.Cloud**
To kickstart your journey, register on [Whapi.Cloud](https://panel.whapi.cloud/register) by creating a free account. This step is straightforward and doesn’t require any credit card details. Post-registration, you gain immediate access to a test channel, albeit with some limitations.

**Connecting Your Phone**
The test channel requires around a minute to initiate. After its activation, connect your phone to enable WhatsApp automation. The service will utilize your connected phone to send messages. Here’s a step-by-step process:
1. Access the QR code by clicking on your trial channel in your Whapi.Cloud account.
2. Open WhatsApp on your mobile device.
3. Navigate to Settings -> Linked devices -> Link a device -> Scan QR code.
This swift connection process is a standout feature of Whapi.Cloud, enabling you to launch and operate within minutes.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ko0k4i7nik3mnup9x9ta.png)

[Start free](https://whapi.cloud)

**Channel Customization and Configuration**
During the second and third steps of the connection, you’ll be prompted to personalize your channel. You can name your channel, configure webhooks, and modify other settings as per your preference. However, these steps can be skipped initially and revisited later for refinement.

**Obtaining API Token**
Once your channel is operational, locate your API Token in the center block beneath the limits information. This token is pivotal for authenticating your API requests. Typically, it is included in the request headers as a Bearer Token or as a request parameter, adapting to the API method employed.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/elstybgvykit3uppenji.png)

## Creating a New WhatsApp Group
In WhatsApp, a group acts as a hub for multiple users to communicate collectively. Whether it's for a business, community, or personal use, automating group creation can save time.
To create a new group using PHP:

```
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://gate.whapi.cloud/groups?token=h0uXrELd3Q4i7jvX6ke1i3rCcWBZgpEi",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'subject' => 'Test name :)',
    'participants' => [
        '15056952654',
        '14046952648'
    ]
  ]),
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "content-type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

In this code, we initiate a POST request to the API endpoint provided by WhatsApp to create a new group. We pass the name of the group (subject) and the initial participants' numbers. Upon execution, the group will be created, and the API response will either confirm success or flag any encountered issues.
[WhatsApp API Docs](https://whapi.cloud/docs)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mti2whcxkh6nqvn4ztqp.png)

**Setting a Group Icon**
A group icon helps members quickly identify and distinguish the group from the list of their chats. Automating the task of updating group icons becomes crucial, especially for brands that frequently change their marketing campaigns or visuals.
Here's how you can set or update the group icon using PHP:

```
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://gate.whapi.cloud/groups/12031836356517114940g.us/icon?token=h0uXrELd3Q4i7jvX6ke1i3rCcWBZgpEi",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "content-type: image/jpeg"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

In this example, a PUT request is made to the provided API endpoint, specifying the group ID (12031833656517114940g.us). This ID represents the group for which we're updating the icon. The content-type: image/jpeg header ensures the API knows we're sending image data.

**Generating a Group Invite Link**
Growing your WhatsApp group becomes easier when you have a direct link to share with potential members. Instead of manually adding each user, an invite link allows users to join the group by themselves. Here's how to automate the process of generating a group invite link:

```
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://gate.whapi.cloud/groups/12036565318317114940g.us/invite?token=h0uXrELd3Q4i7jvX6ke1i3rCcWBZgpEi",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "accept: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

This code sends a GET request to the provided API endpoint, targeting a specific group ID (12036318651735114940g.us). The response will include the invitation link for that group, which can then be shared with potential members.

## Adding Participants to WhatsApp Group
Building your WhatsApp group requires adding members efficiently. Instead of a manual process, automating the addition of members can save time and reduce mistakes. Here's how to automate the process of adding participants to a group:

```
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://gate.whapi.cloud/groups/12036565318317114940g.us/participants?token=h0uXrELd3Q4i7jvX6ke1i3rCcWBZgpEi",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'participants' => [
        '<Recipient WA-ID, from Contacts API>',
        '15056984562'
    ]
  ]),
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "content-type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

In this code, a POST request is sent to the provided API endpoint, specifying the group ID (12036517131835614940g.us) you want to add participants to. You can list the IDs of the members you want to add in the 'participants' array. The <Recipient WA-ID, from Contacts API> placeholder should be replaced with the actual WhatsApp ID obtained from the Contacts API or any other source.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2nda1tjvqz9k125uw9u2.png)

## Get a list of Whatsapp group members via API
When managing several groups, it's essential to have a way to fetch details about a specific group. This helps in understanding group statistics, members, and other related information. Let's understand how to retrieve a group's details by its ID:

```
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://gate.whapi.cloud/groups/12036565318317114940g.us?token=h0uXrELd3Q4i7jvX6ke1i3rCcWBZgpEi",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "accept: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

The above code initiates a GET request to the specified API endpoint, pointing to the group ID (12036318517135614940g.us). Once executed, the code retrieves detailed information about the group, such as its name, group picture (chat_pic), last message, owner's name (name_owner), group description, and an array of group participants' IDs with names and phones.

For example:

```
"participants": [
    {
      "id": "5217554348750",
      "rank": "member"
    },
    {
      "id": "5215499583721",
      "rank": "creator"
    }
```

This can be very helpful to get insights into group activities, member count, and more.
When developing a bot, it is essential to continuously test and debug your application to ensure that it is working correctly and is free of errors. For local testing, you can use Postman or any other API testing tool to simulate incoming messages and check the responses from your bot.
[Try for free](https://panel.whapi.cloud/dashboard)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0lvzistz757pjnw78lvm.png)

**Conclusion**
WhatsApp has become more than just a messaging platform. With the rise of chatbots and integrations in various businesses, understanding and managing groups programmatically is of paramount importance. This manual aimed to guide developers through the process of automating group management in WhatsApp using PHP.
The provided code snippets cover essential operations, from creating groups to fetching detailed group data. Adapting these examples to specific use cases will streamline workflows, offer better insights into group activities, and elevate the overall user experience.

Remember always to handle user data with care, adhering to privacy regulations and WhatsApp's guidelines. The power of automation brings great responsibility, so use it wisely.

Happy coding!