Giter Site home page Giter Site logo

msg91-laravel's Introduction

Laravel service provider for Msg91

Total Downloads Latest Stable Version License Status

This is a laravel service provider for Msg91 APIs. It wraps the msg91-php client and provides the same functionality for Laravel applications by exposing a Service Provider and Facade.

Table of Contents

Installation

The packages is available on Packagist and can be installed via Composer by executing following command in shell.

composer require craftsys/msg91-laravel

prerequisite

  • php^7.1
  • laravel^5|^6|^7|^8|^9|^10

The package is tested for 5.8+,^6.0,^7.0,^8.0,^9.0,^10.0 only. If you find any bugs for laravel (5.0< >5.8), please file an issue.

Laravel 5.5+

If you're using Laravel 5.5 or above, the package will automatically register the Craftsys\Msg91\Msg91LaravelServiceProvider provider and aliases Craftsys\Msg91\Facade\Msg91 facade to Msg91.

Laravel 5.4 and below

Add Craftsys\Msg91\Msg91LaravelServiceProvider to the providers array in your config/app.php:

'providers' => [
     // Other service providers...
     Craftsys\Msg91\Msg91LaravelServiceProvider::class,
],

If you want to use the facade interface, you can use the facade class when needed:

use Craftsys\Msg91\Facade\Msg91;

Or add an alias in your config/app.php

'aliases' => [
    // other aliases here
    'Msg91' => Craftsys\Msg91\Facade\Msg91::class,
],

To verify that everything is working as expected, excecute the following php code somewhere in your application, either in an example route or in php artisan tinker if you are in Laravel.

// this should print the `\Craftsys\Msg91\OTP\OTPService` of some default configuration values
echo Msg91::otp()::class

If there is an issue, please check the steps again or open an issue for support.

Configuration

As the msg91-php offers configuration that are similar to Laravel's configuration, this package simply ports the Laravel's configuration to the msg91-php client.

The package can be configured by providing a msg91 key inside your config/services.php configuration file.

<?php

return [
  // along with other services
  "msg91" => [
    'key' => env("Msg91_KEY"),
  ],
];

and update the .env file to get the desired values e.g. Msg91_KEY.

Please visit msg91-php configuration for a detailed description about the available options and their default values.

Usage

Once you have Configured the Laravel/Lumen application to use the service provider and have aliased the facade to Msg91, you will have a msg91-php client (Craftsys\Msg91\Client) instance.

// send otp
Msg91::otp()->to(919999999999)->send();

// resend otp
Msg91::otp()->to(919999999999)->viaVoice()->resend();

// verify otp
Msg91::otp(678612)->to(919999999999)->verify();

// send sms
Msg91::sms()->to(919999999999)->flow('<flow_id>')->send();

// in bulk
Msg91::sms()->to([919999999999, 918899898990])->flow('<flow_id>')->send();

// with variables in your flow template
Msg91::sms()->to([919999999999, 918899898990])->flow('<flow_id>')->variable('variable_name', 'value')->send();

// with variables per recipient
Msg91::sms()->recipients([
  ['mobiles' => 919999999999, 'name' => 'Sudhir M'],
  ['mobiles' => 918899898990, 'name' => 'Craft Sys']
])
  ->flow('<flow_id>')
  ->send();

Follow along with examples to learn more

Examples

Managing OTPs

OTP services like sending, verifying, and resending etc, can be accessed via otp method on the client instance e.g. Msg91::otp().

For a detailed usage, please visit msg91-php's documentation on managing OTPs.

Send OTP

Msg91::otp()
    ->to(912343434312) // phone number with country code
    ->template('your_template_id') // set the otp template
    ->send(); // send the otp

Verify OTP

Msg91::otp(1234) // OTP to be verified
    ->to(912343434312) // phone number with country code
    ->verify(); // Verify

Resend OTP

Msg91::otp()
    ->to(912343434312) // set the mobile with country code
    ->viaVoice() // set the otp sending method (can be "viaText" as well)
    ->resend(); // resend otp

Sending SMS

Msg91::sms()
    ->to(912343434312) // set the mobile with country code
    ->flow("your_flow_id_here") // set the flow id
    ->send(); // send

Bulk SMS

Msg91::sms()
    ->to([912343434312, 919898889892]) // set the mobiles with country code
    ->flow("your_flow_id_here") // set the flow id
    ->send(); // send

Message Variables

// send in bulk with variables    
Msg91::sms()
    ->to([912343434312, 919898889892]) // set the mobiles with country code
    ->flow("your_flow_id_here") // set the flow id
    ->variable('date', "Sunday") // the the value for variable "date" in your flow message template
    ->send(); // send
    
// send in bulk with variables per recipient
Msg91::sms()
    ->to([912343434312, 919898889892]) // set the mobiles with country code
    ->flow("your_flow_id_here") // set the flow id
    ->recipients([
      ['mobiles' => 919999223345, 'name' => 'Sudhir M'],
      ['mobiles' => 912929223345, 'name' => 'Craft Sys']
    ])
    // (optionally) set a "date" variable for all the recipients
    ->variable('date', "Sunday")
    ->send(); // send

For a detailed usage and options, please visit msg91-php's documentation on sending SMSs.

Handling Responses

All the services will return \Craftsys\Msg91\Support\Response instance for all successfully responses or will throw exceptions if request validation failed (\Craftsys\Msg91\Exceptions\ValidationException)or there was an error in the response (\Craftsys\Msg91\Exceptions\ResponseErrorException).

try {
    $response = $client->otp()->to(919999999999)->send();
} catch (\Craftsys\Msg91\Exceptions\ValidationException $e) {
    // issue with the request e.g. token not provided
} catch (\Craftsys\Msg91\Exceptions\ResponseErrorException $e) {
    // error thrown by msg91 apis or by http client
} catch (\Exception $e) {
    // something else went wrong
    // plese report if this happens :)
}

For all the examples and options, please consult msg91-php examples section

Related

Acknowledgements

We are grateful to the authors of existing related projects for their ideas and collaboration:

msg91-laravel's People

Contributors

laravel-shift avatar semantic-release-bot avatar sudkumar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

msg91-laravel's Issues

Php Deprecated Error - jsonSerialize()

Php 8.1
Laravel .80
In Laravel Tinker test
getting this error

>>> echo Msg91::otp()::class PHP Deprecated: Return type of Craftsys\Msg91\Options::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /MYAPP_PATH/vendor/craftsys/msg91-php/src/Options.php on line 215 Craftsys\Msg91\OTP\OTPService⏎

OTP Length Support

Any way you could add OTP length support parameter since the default is 4 if someone wants to send more than 4 digits of OTP.

It is working with queue

While I am trying to send SMS using this package I got following error:

Class 'Craftsys\Msg91\Facade\Msg91' not found {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Class 'Craftsys\\Msg91\\Facade\\Msg91' not found at /var/www/html/laravel/project/app/Common/Msg91Gateway.php:40)

Error - Dynamic class names are not allowed in compile-time ::class fetch

echo Msg91::otp()::class

Symfony\Component\ErrorHandler\Error\FatalError

Dynamic class names are not allowed in compile-time ::class fetch

at vendor/psy/psysh/src/ExecutionLoopClosure.php:55
51▕ // Convert all errors to exceptions
52▕ \set_error_handler([$psysh, 'handleError']);
53▕
54▕ // Evaluate the current code buffer
➜ 55▕ $_ = eval($psysh->onExecute($psysh->flushCode() ?: ExecutionClosure::NOOP_INPUT));
56▕ } catch (\Throwable $_e) {
57▕ // Clean up on our way out.
58▕ if (\ob_get_level() > 0) {
59▕ \ob_end_clean();

Whoops\Exception\ErrorException

Dynamic class names are not allowed in compile-time ::class fetch

at vendor/psy/psysh/src/ExecutionLoopClosure.php:55
51▕ // Convert all errors to exceptions
52▕ \set_error_handler([$psysh, 'handleError']);
53▕
54▕ // Evaluate the current code buffer
➜ 55▕ $_ = eval($psysh->onExecute($psysh->flushCode() ?: ExecutionClosure::NOOP_INPUT));
56▕ } catch (\Throwable $_e) {
57▕ // Clean up on our way out.
58▕ if (\ob_get_level() > 0) {
59▕ \ob_end_clean();

  +1 vendor frames 

2 [internal]:0
Whoops\Run::handleShutdown()

OTP Verification appears to be broken

Sending an OTP is working just fine but I'm getting an exception (Craftsys/Msg91/Exceptions/ResponseErrorException with message 'Invalid authkey') when trying to verify the OTP.

Steps to recreate:

  • Create a new Laravel 8 project
  • Install msg91-laravel
  • Set the msg91 key with the appropriate values in config/services.php
  • In Tinker (php artisan tinker), run Msg91::otp()->to(918888888888)->send(); to receive the OTP. Then run Msg91::otp(1234)->to(918888888888)->verify(); to verify. The verification statement throws the exception mentioned above.

If there's any other info you may need to recreate the issue, do let me know. Thanks for making this wonderful package (as well as msg91-php) 🤗

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.