A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints.

Overview

WPPConnect Team

Wppconnect Laravel Client

A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints.

Requirements

  • PHP 7.4 or newer
  • Laravel 8.x or newer

Note that the above requirements will always reflect the latest release. Older releases may support older PHP and Laravel versions.

Install - Laravel

Require this package with Composer (Packagist), using the following command:

$ composer require wppconnect-team/wppconnect-laravel-client

Register the WppconnectServiceProvider to the providers array in config/app.php:

 WPPConnectTeam\Wppconnect\WppconnectServiceProvider::class

Publish vendor files (config file):

$ php artisan vendor:publish

Optional Register the facade in config/app.php:

'Wppconnect' => WPPConnectTeam\Wppconnect\Facades\Wppconnect::class

Config

Associative array of Request Options, that are applied to every request, created by the client.

Example:

'defaults' => [
     /**
      * Configures a base URL for the client so that requests created using a relative URL are combined with the base_url
      * See: http://guzzle.readthedocs.org/en/latest/quickstart.html#creating-a-client
      */
     'base_uri' => 'http://192.168.0.39:21465',

     /**
      * Secret Key
      * See: https://github.com/wppconnect-team/wppconnect-server#secret-key
      */
     'secret_key' => 'MYKeYPHP'
 ]

Usage

You can use this package without any configuration. Just use the Wppconnect facade in your controller or Inject into the class where you need the client:

/**
 * @var RequestInterface
 */
protected $client;

/**
 * @param Wppconnect $client
 */
public function __construct(Wppconnect $client)
{
    $this->client = $client;
}

Facade Example:

class WppconnectController extends Controller
{

    protected $url;
    protected $key;
    protected $session;

    /**
     * __construct function
     */
    public function __construct()
    {
        $this->url = config('wppconnect.defaults.base_uri');
        $this->key = config('wppconnect.defaults.secret_key');
	$this->session = "mySession";
    }

    public function index(){

	#Function: Generated Token
	# /api/:session/generate-token
	
        //Session::flush();
        if(!Session::get('token') and !Session::get('session')):
            Wppconnect::make($this->url);
            $response = Wppconnect::to('/api/'.$this->session.'/'.$this->key.'/generate-token')->asJson()->post();
            $response = json_decode($response->getBody()->getContents(),true);
            if($response['status'] == 'Success'):
                Session::put('token', $response['token']);
                Session::put('session', $response['session']);
            endif;
        endif;

	#Function: Start Session 
	# /api/:session/start-session
		
        if(Session::get('token') and Session::get('session') and !Session::get('init')):
            Wppconnect::make($this->url);
            $response = Wppconnect::to('/api/'.Session::get('session').'/start-session')->withHeaders([
                'Authorization' => 'Bearer '.Session::get('token')
            ])->asJson()->post();
            $response = json_decode($response->getBody()->getContents(),true);
            Session::put('init', true);
        endif;
	
    }
 }
   #Function: Check Connection Session
   # /api/:session/check-connection-session
   	
   if(Session::get('token') and Session::get('session') and Session::get('init')):
       Wppconnect::make($this->url);
       $response = Wppconnect::to('/api/'. Session::get('session').'/check-connection-session')->withHeaders([
   	'Authorization' => 'Bearer '.Session::get('token')
       ])->asJson()->get();
       $response = json_decode($response->getBody()->getContents(),true);
       dd($response);
   endif;
   #Function: Close Session
   # /api/:session/close-session

   if(Session::get('token') and Session::get('session') and Session::get('init')):
       Wppconnect::make($this->url);
       $response = Wppconnect::to('/api/'. Session::get('session').'/close-session')->withHeaders([
   	'Authorization' => 'Bearer '.Session::get('token')
       ])->asJson()->post();
       $response = json_decode($response->getBody()->getContents(),true);
       dd($response);
   endif;
   #Function: Send Message
   # /api/:session/send-message
   	
   if(Session::get('token') and Session::get('session') and Session::get('init')):
       Wppconnect::make($this->url);
       $response = Wppconnect::to('/api/'. Session::get('session').'/send-message')->withBody([
   	'phone' => '0000000000000',
   	'message' => 'Opa, funciona mesmo!'
       ])->withHeaders([
   	'Authorization' => 'Bearer '.Session::get('token')
       ])->asJson()->post();
       $response = json_decode($response->getBody()->getContents(),true);
       dd($response);
   endif;
   #Function: Send File Base64
   # /api/:session/send-file-base64
   	
   if(Session::get('token') and Session::get('session') and Session::get('init')):
       Wppconnect::make($this->url);
       $response = Wppconnect::to('/api/'. Session::get('session').'/send-file-base64')->withBody([
   	'phone' => '0000000000000',
   	'base64' => 'data:image/jpg;base64,' . base64_encode(file_get_contents(resource_path('/img/xpto.jpg')))
       ])->withHeaders([
   	'Authorization' => 'Bearer '.Session::get('token')
       ])->asJson()->post();
       $response = json_decode($response->getBody()->getContents(),true);
       dd($response);
   endif;

Debugging

Using debug(bool|resource) before sending a request turns on Guzzle's debugger, more information about that here.

The debugger is turned off after every request, if you need to debug multiple requests sent sequentially you will need to turn on debugging for all of them.

Example

$logFile = './client_debug_test.log';
$logFileResource = fopen($logFile, 'w+');

$this->client->debug($logFileResource)->to('post')->withBody([
	'foo' => 'bar'
])->asJson()->post();

fclose($logFileResource);

This writes Guzzle's debug information to client_debug_test.log.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Tiny PHP library providing retry functionality with multiple backoff strategies and jitter support

JBZoo / Retry 4 retry strategies (plus the ability to use your own) Optional jitter / randomness to spread out retries and minimize collisions Wait ti

StringBuffer is a PHP class providing operations for efficient string buffering

StringBuffer is a PHP class providing operations for efficient string buffering

A Laravel Wrapper for the Binance API. Now easily connect and consume the Binance Public & Private API in your Laravel apps without any hassle.
A Laravel Wrapper for the Binance API. Now easily connect and consume the Binance Public & Private API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the Binance API and allows you to easily communicate with it. Important Note This package is in early deve

A simple Object Oriented wrapper for Linear API, written with PHP.

PHP Linear API A simple Object Oriented wrapper for Linear API, written with PHP. NOTE You should take a look Linear GraphQL API Schema for all nodes

Free ZIP Code API - Free Access to Worldwide Postal Code Data

About Zipcodebase - Free Zip Code API Zipcodebase is a zip code API that was founded in 2019 to solve common issues with postal code data. As we have

A list of documentation and example code to access the University of Florida's public (undocumented) API

uf_api A list of documentation and example code to access the University of Florida's public (undocumented) API Courses Gym Common Data (admissions an

PHP demo application showing how to access the Hubstaff Public API

Public API PHP Demo This repository contains a simple sample cli tool that shows off how to access the Hubstaff public api via PHP. The core access is

Standardized wrapper for popular currency rate APIs. Currently supports FixerIO, CurrencyLayer, Open Exchange Rates and Exchange Rates API.

💱 Wrapper for popular Currency Exchange Rate APIs A PHP API Wrapper to offer a unified programming interface for popular Currency Rate APIs. Dont wor

An un-offical API wrapper for logsnag.com to get notifications and track your project events
An un-offical API wrapper for logsnag.com to get notifications and track your project events

An un-offical API wrapper for logsnag.com to get notifications and track your project events

Comments
  • send-buttons

    send-buttons

    Hi,

    Can give me example to send buttons?

    I found that the wppconnect-server endpoint have "/api/:session/send-buttons" but when i try to send the button, no message received at the destination number

    below are my code

    Wppconnect::make($this->url);
                        $response = Wppconnect::to('/api/' . $setting->session . '/send-buttons')->withBody([
                            'phone' => $request->phone,
                            'title' => $request->title,
                            'buttons' => [
                                ["buttonId" => '1', "buttonText" => ["displayText" => 'Text of Button 1'], "type" => 1],
                                ["buttonId" => '2', "buttonText" => ["displayText" => 'Text of Button 2'], "type" => 1],
                                ["buttonId" => '3', "buttonText" => ["displayText" => 'Text of Button 3'], "type" => 1]
                            ]
                        ])->withHeaders([
                            'Authorization' => 'Bearer ' . $setting->token
                        ])->asJson()->post();
    
    opened by elgibor-solution 1
  • EXEMPLO COM FACADE (error)

    EXEMPLO COM FACADE (error)

    .......
                if($response['status'] == 'Success'):
                    Session::put('token', $response['token']);
                    Session::put('session', $response['session']);
                endif;
    ....
    

    No codigo acima, na linha if($response['status'] == 'Success'): o retorno de $response['status'] é success, fazendo com que apresente erro. eu corrigir colocando success e funcionou tranquilo.

    opened by willph 1
Releases(1.0.1)
Owner
null
It is an open-source and free project, which is faced with the drawing lovers, providing a free and simple Gallery service

It is an open-source and free project, which is faced with the drawing lovers, providing a free and simple Gallery service

WeepingDogel 5 Dec 15, 2022
Formcreator is a plugin which allow creation of custom forms of easy access

Formcreator is a plugin which allow creation of custom forms of easy access. At the same time, the plugin allow the creation of one or more tickets when the form is filled.

GLPI plugins 135 Dec 22, 2022
This package makes it easy to add early access mode to your existing application.

This package makes it easy to add early access mode to your existing application. This is useful for when you want to launch a product and need to gat

Neo 174 Nov 26, 2022
A wrapper around symplify/config-transformer used to update recipes and using easy coding standard for generating readable config files.

Symfony Recipes Yaml to PHP Converter This is a wrapper around the symplify/config-transformer used to convert Symfony core recipes which uses .yaml c

Alexander Schranz 3 Nov 24, 2022
PHP library providing retry functionality with multiple backoff strategies and jitter support

PHP Backoff Easily wrap your code with retry functionality. This library provides: 4 backoff strategies (plus the ability to use your own) Optional ji

Signature Tech Studio 145 Dec 21, 2022
Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

National Library of Finland 195 Dec 24, 2022
Bundle providing Honeypot field for the Form Builder in Ibexa DXP Experience/Commerce (3.X)

IbexaHoneypot Bundle providing Honeypot field for the Form Builder in Ibexa DXP Experience/Commerce (3.X) What is Honey pot? A honey pot trap involves

null 1 Oct 14, 2021
Small library providing some functional programming tools for PHP, based on Rambda

Functional library for PHP. Features: set of useful functions helpful in functional programming all functions are automatically curried every array ca

Wojciech Nawalaniec 5 Jun 16, 2022
Starless Sky is a network protocol for secure identities, providing the use of assymetric identities, public information, end-to-end messaging and smart contracts

Descentralized network protocol providing smart identity over an secure layer. What is the Starless Sky Protocol? Starless Sky is a network protocol f

Starless Sky Protocol 3 Jun 19, 2022
A PHP library providing ISO 3166-1 data

league/iso3166 A PHP library providing ISO 3166-1 data. What is ISO 3166-1 ISO 3166-1 is part of the ISO 3166 standard published by the International

The League of Extraordinary Packages 555 Dec 21, 2022