Giter Site home page Giter Site logo

php-ovh-sms's Introduction

PHP OVH SMS

Send SMS directly from your code using OVH SMS offer.

<?php
/**
 * # Instantiate. Visit https://api.ovh.com/createToken/index.cgi?GET=/sms&GET=/sms/*&PUT=/sms/*&DELETE=/sms/*&POST=/sms/*
 * to get your credentials
 */
require __DIR__ . '/vendor/autoload.php';
use \Ovh\Sms\SmsApi;

$Sms = new SmsApi( $applicationKey,
                $applicationSecret,
                $endpoint,
                $consumer_key);
print_r($Sms->getAccounts());
?>

Install

To download this SDK and integrate it inside your PHP application, you can use Composer.

Add the repository in your composer.json file or, if you don't already have this file, create it at the root of your project with this content:

{
    "name": "Example Application",
    "description": "This is an example of OVH SMS APIs SDK usage",
    "require": {
        "ovh/php-ovh-sms": "dev-master"
    }
}

Then, you can install OVH SMS APIs SDK and dependencies with:

php composer.phar install

This will install ovh/php-ovh-sms to ./vendor, along with other dependencies including autoload.php.

Configure

To use this SDK, you'll need API credentials. API credentials allows you to log in and manage OVH products without ever storing your password.

Even better, the credentials can be configured to only allow access on some specific features. In this case, we only want the script to access the SMS features.

To generate credentials to access all the SMS features, you can simply visit https://api.ovh.com/createToken/index.cgi?GET=/sms&GET=/sms/*&PUT=/sms/*&DELETE=/sms/*&POST=/sms/*

And then use the generated credentials in you application.

For more advanced use cases, please consult the php-ovh or python-ovh wrappers.

Send a test message without specifying a sender using php-ovh-sdk

This example will create a new SDK instance, configure it to send a message to a french number without declaring a sender (a random shortcode will be used). It will then use this instance to plan a message in the future using the first account it finds.

To avoid consuming any credit accidentally, it will delete the message before actually sending it.

<?php
require __DIR__ . '/vendor/autoload.php';
use \Ovh\Sms\SmsApi;

// Informations about your application
// You may set them to 'NULL' if you are using
// a configuraton file
$applicationKey = "your_app_key";
$applicationSecret = "your_app_secret";
$consumerKey = "your_consumer_key";
$endpoint = 'ovh-eu';

// Init SmsApi object
$Sms = new SmsApi( $applicationKey, $applicationSecret, $endpoint, $consumerKey );

// Get available SMS accounts
$accounts = $Sms->getAccounts();

// Set the account you will use
$Sms->setAccount($accounts[0]);

// Create a new message that will allow the recipient to answer (to FR receipients only)
$Message = $Sms->createMessage(true);
$Message->addReceiver("+33601020304");
$Message->setIsMarketing(false);

// Plan to send it in the future
$Message->setDeliveryDate(new DateTime("2018-02-25 18:40:00"));
$Message->send("Hello world!");

// Get all planned messages
$plannedMessages = $Sms->getPlannedMessages();

// Delete all planned messages
foreach ($plannedMessages as $planned) {
    $planned->delete();
}
?>https://api.ovh.com/createToken/index.cgi

Send a test message by using a beforehand declared sender

This example will create a new SDK instance, configure it to send a message. It will then use this instance to plan a message in the future using the first account it finds and the first sender it finds in the account as the message sender.

To avoid consuming any credit accidentally, it will delete the message before actually sending it.

<?php
require __DIR__ . '/vendor/autoload.php';
use \Ovh\Sms\SmsApi;

// Informations about your application
// You may set them to 'NULL' if you are using
// a configuraton file
$applicationKey = "your_app_key";
$applicationSecret = "your_app_secret";
$consumerKey = "your_consumer_key";
$endpoint = 'ovh-eu';

// Init SmsApi object
$Sms = new SmsApi( $applicationKey, $applicationSecret, $endpoint, $consumerKey );

// Get available SMS accounts
$accounts = $Sms->getAccounts();

// Set the account you will use
$Sms->setAccount($accounts[0]);

// Get declared senders
$senders = $Sms->getSenders();

// Create a new message
$Message = $Sms->createMessage();
$Message->setSender($senders[0]);
$Message->addReceiver("+33601020304");
$Message->setIsMarketing(false);

// Plan to send it in the future
$Message->setDeliveryDate(new DateTime("2018-02-25 18:40:00"));
$Message->send("Hello world!");

// Get all planned messages
$plannedMessages = $Sms->getPlannedMessages();

// Delete all planned messages
foreach ($plannedMessages as $planned) {
    $planned->delete();
}
?>https://api.ovh.com/createToken/index.cgi

Hacking

Get the code:

$ git clone https://github.com/ovh/php-ovh-sms.git
$ cd php-ovh-sms

Submit your changes:

$ git commit -sam "change some feature because it makes my life easier"
$ git push

And visit Github to submit your change! https://github.com/ovh/php-ovh-sms/pulls

Related links

Licence

3-Clause BSD

php-ovh-sms's People

Contributors

chindit avatar dsferruzza avatar metrakit avatar vincentcasse avatar yadutaf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-ovh-sms's Issues

Error unknow

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error response [url] https://api.ovh.com/1.0/sms/ [status code] 403 [reason phrase] Forbidden' in /var/www/vhosts/formainap.net/subdomains/idiomas/application/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:89 Stack trace: #0 /var/www/vhosts/formainap.net/subdomains/idiomas/application/vendor/guzzlehttp/guzzle/src/Subscriber/HttpError.php(33): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Message\Request), Object(GuzzleHttp\Message\Response)) #1 /var/www/vhosts/formainap.net/subdomains/idiomas/application/vendor/guzzlehttp/guzzle/src/Event/Emitter.php(108): GuzzleHttp\Subscriber\HttpError->onComplete(Object(GuzzleHttp\Event\CompleteEvent), 'complete') #2 /var/www/vhosts/formainap.net/subdomains/idiomas/application/vendor/guzzlehttp/guzzle/src/RequestFsm.php(91): GuzzleHttp\Event\Emitter->emit('complete', Object(GuzzleHttp\Event\CompleteEvent)) #3 /var/www/vhosts/formainap.net/subdomains/idiomas/applica in /var/www/vhosts/formainap.net/subdomains/idiomas/application/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 89

The code:

`require $_SERVER['DOCUMENT_ROOT'].'/application/vendor/autoload.php';
use \Ovh\Api;

$endpoint = 'ovh-eu';
$applicationKey = "xxxxx";
$applicationSecret = "xxxxxx";
$consumer_key = "xxxxxxxx";

$conn = new Api( $applicationKey,
$applicationSecret,
$endpoint,
$consumer_key);

$smsServices = $conn->get('/sms/');
foreach ($smsServices as $smsService) {

print_r($smsService);

}

$content = (object) array(
"charset"=> "UTF-8",
"class"=> "phoneDisplay",
"coding"=> "7bit",
"message"=> "Ya están disponibles los SMS de OVHcloud en api.ovh.com",
"noStopClause"=> false,
"priority"=> "high",
"receivers"=> [ "+3460000000" ],
"senderForResponse"=> true,
"validityPeriod"=> 2880
);
$resultPostJob = $conn->post('/sms/'. $smsServices[0] . '/jobs/', $content);

print_r($resultPostJob);

$smsJobs = $conn->get('/sms/'. $smsServices[0] . '/jobs/');
print_r($smsJobs);
`

Different variables names for getOutgoingMessages parameters

In getOutgoingMessages declaration, you're using $dateStart and $dateEnd, but in implementation, you're checking $startDateTime and $endDateTime (and they are not defined) so PHP displays a notice :

PHP Notice: Undefined variable: startDateTime in /home/sms/www/vendor/ovh/php-ovh-sms/src/SmsApi.php on line 400
PHP Notice: Undefined variable: endDateTime in /home/sms/www/vendor/ovh/php-ovh-sms/src/SmsApi.php on line 408

SMS divisé en plusieurs

Par deux fois, sur une 20aine de tests, j'ai eu mon message envoyé tronqué en 3 voir 4 sms. Certes, mon SMS dépassait les 160 caractères, mais il est marqué dans la doc qu'à part coûter plusieurs crédits, cela ne pose pas de soucis.

La dernière fois que cela s'est produit la chaîne faisait 223 caractères et a été répartie sur 4 sms, qui ne sont même pas arrivé dans le bon ordre. J'ai beau regarder, je ne vois pas de caractères spéciaux qui pourraient entraîner un problème surtout que la plupart du temps, avec la même chaîne, le sms arrive en un seul morceau.

Avez-vous une idée d'où cela pourrait provenir ?

Merci

Problem with expiring API permissions

Hi. I am testing SMS sending using OVH Api and this tutorial -> https://docs.ovh.com/gb/en/sms/send_sms_with_ovhcloud_api_in_php/
(first 20 SMS I have for free).
I created a token (2022-01-31) at https://eu.api.ovh.com/createToken/index.cgi?GET=/sms&GET=/sms/*/jobs&POST=/sms/*/jobs
setting Validity to "UNLIMITED" and I was able to send messages. After a few days it looks like the permissions have expired.

https://eu.api.ovh.com/1.0/sms` resulted in a 403 Forbidden response: {"message": "This credential is not valid", "httpCode": "403 Forbidden", "errorCode": "INVALID_CREDENTIAL"}

Is this normal?

Tagger une version

Salut!

Je viens de mettre en ligne un paquet pour Laravel utilisant l'API OVH (https://github.com/AkibaTech/laravel-ovh-sms).

Il s'avère que mon paquet (taggé en 1.1.0) require ovh/php-ovh-sms en "dev-master".
A moins de mettre toute son install Laravel en "minimum-stability": "dev" (ou alors je sais pas comment faire), il est impossible de require mon package Laravel (la stabilité par défaut de Laravel empêchant les @dev).

Auriez-vous une piste ?
Sinon je forke php-ovh-sms et je le tag en 1.0 mais c'est pas cool.

Merci :)

Support for GuzzleHttp v6

Can you add support for GuzzleHttp v6 please ?
Our project depends on this version and we can't use the library (guzzle is supported until 5.3 max).

Update lib and dependencies

Last ovh/php-ovh-sms requires ovh/ovh 2.0.1 that requires guzzle 6.0 that is not compatible with php 7.4.... Please update dependencies:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- ovh/php-ovh-sms dev-master requires ovh/ovh ~2.0.1 -> satisfiable by ovh/ovh[v2.0.1].
- Installation request for ovh/php-ovh-sms dev-master -> satisfiable by ovh/php-ovh-sms[dev-master].
- Conclusion: remove guzzlehttp/guzzle 7.2.0
- Conclusion: don't install guzzlehttp/guzzle 7.2.0
- ovh/ovh v2.0.1 requires guzzlehttp/guzzle ^6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3, 6.3.0, 6.3.1, 6.3.2, 6.3.3, 6.4.0, 6.4.1, 6.5.0, 6.5.1, 6.5.2, 6.5.3, 6.5.4, 6.5.5].
- Can only install one of: guzzlehttp/guzzle[7.2.0].
- Conclusion: don't install ovh/ovh 2.0.1

Installation failed, reverting ./composer.json to its original content.

Client error

J'ai cet erreur quand je tente d'avoir les informations sur mon compte.
"Client error response [url] https://api.ovh.com/1.0/sms [status code] 403 [reason phrase] Forbidden" on line 89 of /Developer/www/octobercms/smsaplpha/plugins/dcolsay/sms/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php

obtenir le zip avec les dependances

Bonjour,

Je cherche à avoir le script au format .zip que je puisse juste uploader sur mon ftp après avoir mis mes informations de clés dans un fichier. Un lien quelque part ? Merci

Client error response [url] https://api.ovh.com/1.0/sms/sms-xxxxxxxxxx-1/jobs [status code] 403 [reason phrase] Forbidden

Salut !
J'ouvre cette issue parceque j'ai essayé de voir les autres issues mais j'ai pas eu de solution à mon problème.

J'ai utilisé ce lien https://api.ovh.com/createToken/index.cgi?GET=/sms/&GET=/sms/*&PUT=/sms/*&DELETE=/sms/*&POST=/sms/ pour créer mes crédentials

Le code que j'ai utilisé est le suivant

`<?php

use Ovh\Sms\SmsApi;

public function __construct(){
$this->sms_app_key = "xxxxxxxxxxxxxxx";
$this->sms_app_secret = "xxxxxxxxxxxxxxx";
$this->sms_consumer_key = "xxxxxxxxxxxxxxx";
$this->sms_endpoint = 'ovh-eu';
}
public function index(){
$sms = new SmsApi( $this->sms_app_key, $this->sms_app_secret, $this->sms_endpoint, $this->sms_consumer_key);
$accounts = $sms->getAccounts();
$sms->setAccount($accounts[0]);

  $message = $sms->createMessage(true);
  $message->addReceiver("+33601020304");
  $message->setIsMarketing(false);

  // Plan to send it in the future
  $date = date('Y-m-d H:i:s');
  $date = date('Y-m-d H:i:s',strtotime('+2 hours',strtotime($date)));
  $message->setDeliveryDate(new \DateTime($date));
  $message->send("Hello world!");

}`
Je ne sais pas ce que j'ai mal fait dans ce code.
Le get getAccounts marche bien ainsi que le setAccount mais c'est au niveau de l'envoie du message que j'ai cette erreur.
SVP Si quelqu'un à une solution pour moi ça m'aidera vraiment
Merci pour votre attention !

getOutgoingMessages() parameters name are not correct

According to comments and body of the method, $startDateTime is used instead of $dateStart as well as $endDateTime instead of $dateEnd.

Using the current version result in notice :

Notice: Undefined variable: startDateTime in C:\Users\Pierre-Alain\Dev\api-v2\vendor\ovh\php-ovh-sms\src\SmsApi.php on line 400

Notice: Undefined variable: endDateTime in C:\Users\Pierre-Alain\Dev\api-v2\vendor\ovh\php-ovh-sms\src\SmsApi.php on line 408

Kohana

I work with the Kohana framework, and it gives me problems with autoload.php and the space with "use \ Ovh \ Sms \ SmsApi;" . I have tried to initialize the class directly and it gives me errors. How can I do?

curl error 60

Bonjour
comment faire pour tester cette api en local avec wamp sans se manger cette erreur.

capture

Merci bien

Paquet Laravel 5

Bonjour !

Seriez-vous intéressé par l'intégration d'un plugin pour Laravel 5 ?
Il pourrait être directement intégré sous un namespace Ovh\Sms\Laravel.

Si oui, je pourrais contribuer en cela :)

error !

Bonjour,
J'ai le même erreur ! et j'ai essayé de changer les credentials comme vous avez indiqué mais, je fait u $sms->getAccounts() et ca retourn bien le compte sms, mais dès que je fait setAccount() ou autre ca retourne le code suivant :

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error response [url] https://api.ovh.com/1.0/sms/sms-******-1 [status code] 403 [reason phrase] Forbidden' in /home/-_-/www/send_sms/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:89 Stack trace: #0 /home/--/www/send_sms/vendor/guzzlehttp/guzzle/src/Subscriber/HttpError.php(33): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Message\Request), Object(GuzzleHttp\Message\Response)) #1 /home/--/www/send_sms/vendor/guzzlehttp/guzzle/src/Event/Emitter.php(109): GuzzleHttp\Subscriber\HttpError->onComplete(Object(GuzzleHttp\Event\CompleteEvent), 'complete') #2 /home/--/www/send_sms/vendor/guzzlehttp/guzzle/src/RequestFsm.php(91): GuzzleHttp\Event\Emitter->emit('complete', Object(GuzzleHttp\Event\CompleteEvent)) #3 /home/--/www/send_sms/vendor/guzzlehttp/guzzle/src/RequestFsm.php(132): GuzzleHttp\RequestFsm->__invoke(Object(GuzzleHttp\Transaction)) #4 /home/--/ww in /home/-_-/www/send_sms/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 89

j'ai testé sur les deux
https://api.ovh.com/createToken/index.cgi?GET=/sms/&PUT=/sms/&DELETE=/sms/&POST=/sms/
et
https://api.ovh.com/createToken/index.cgi?GET=/sms/*&PUT=/sms/*&DELETE=/sms/*&POST=/sms/*

setSender does not work

Hi,
When I send an SMS from https://www.ovhtelecom.fr/manager with my sender that work.

When I do this with PHP the sms is never sent and the manager confirms this

    /**
     * @Route("confirmphone", name="app_phone_confirmation")
     * @Method({"POST"})
     */
    public function confirmationSmsAction(Request $request)
    {
        $phone = substr(str_replace(' ', '', $request->get('phone')), 1);

        $Sms = new SmsApi( 
            $this->getParameter('ovh_api_key'),
            $this->getParameter('ovh_api_secret'),
            'ovh-eu',
            $this->getParameter('ovh_api_consumer')
        );
        
        $accounts = $Sms->getAccounts();
        
        $Sms->setAccount($accounts[0]);
        $senders = $Sms->getSenders();
        $Message = $Sms->createMessage();
        $Message->setSender($senders[0]);  

        $Message->addReceiver('+33'.$phone);
        $Message->setIsMarketing(false);

        $res = $Message->send("Hello world!");
        
        return $this->json( $res );
    }

If i remove $Message->setSender($senders[0]); that work

    $( "#fos_user_registration_form_phone" ).blur(function() {
        var phone = $(this).val();
        $.post( "{{ path('app_phone_confirmation') }}", {phone: phone}, function( data ) {
            console.log( data );
        });
    });

And the api response is:

array(7) {
  ["comment"]=>
  string(0) ""
  ["sender"]=>
  string(7) "AChasse"
  ["status"]=>
  string(6) "enable"
  ["type"]=>
  string(5) "alpha"
  ["description"]=>
  string(9) "addsender"
  ["referer"]=>
  string(6) "custom"
  ["validationMedia"]=>
  string(10) "moderation"
}

Thank you for your help

$receiver parameter is never used in getOutgoingMessages()

The parameter and filter $receiver for the method getOutgoingMessages() in the class SmsApi is never used. We can't filter by receiver and we will always get every SMS.

Works fine if we add the following code before sending the request :

if (!is_null($receiver)) {
    $parameters['receiver'] = $receiver;
}

More information on /sms/{serviceName}/outgoing request parameters here : https://api.ovh.com/console/#/sms/%7BserviceName%7D/outgoing#GET

Installign whithout composer

Hi , Im facing issue installing the lib . im not using composer ans do not want to use it can you tell me how can i install the sms lib whithout using composer ?

Thanks in advance !

Support for OVH API v2

Hey,

I am already using Guzzle >= 6.2 for a project ;
And this SMS client locks the OVH wrapper to v1.1.1, which locks Guzzle < 6.

Would it please be possible to release even a dev version supporting OVH >= v2?

Thanks in advance :)

Sender avec espace

Bonjour,

Pour moi l'envoi des SMS fonctionne correctement. Cependant, cela ne fonctionne qu'avec un sender sans espace dans son nom ? Est-ce normal ou est-ce un bug ? Si c'est un bug, avez-vous une solution ?

Mon erreur est celle-ci :

[14-Nov-2016 12:20:20 Europe/Berlin] PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error response [url] https://api.ovh.com/1.0/sms/sms-pj163240-1/senders/BAH%20BOUH [status code] 404 [reason phrase] ObjectNotFound' in /Applications/MAMP/htdocs/_Spinon/ovh_api_sms/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:89

Bonne journée !

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.