IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Utilisation de l'API de Vonage (ex-nexmo)


Sujet :

Langage PHP

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Webmaster
    Inscrit en
    Mai 2020
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 27
    Localisation : Bénin

    Informations professionnelles :
    Activité : Webmaster
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Mai 2020
    Messages : 6
    Points : 7
    Points
    7
    Par défaut Utilisation de l'API de Vonage (ex-nexmo)
    salut le forum. Je suis entrain d'utiliser l'API de Vonage pour l'envoie des sms personnalisés sur mon site.. mais ça code que j'ai retrouvé marche très bien pour envoyer un sms à un seul numéro.. mais pour l'envoi en masse(c'est à dire à plusieurs numéros d'un coup) ça ne marche pas.. j'avoue que cela peut être dû à mon niveau un peu bas en php... alors aider moi svp..merc d'avance

    voici le code du fichier send.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    <?php
     
    $password = $_POST['password'];
    if ($password !=='Mot_de_passe') {
    echo "Mot de passe Incorrect .... ";
    die();
     
    }
    else {
     
     
     
        include ( "message.php" );
     
     
        /**
         * To send a text message.
         *
         */
         $toNumber = $_POST['toNumber'];
         $from     = $_POST['from'];
         $message  = $_POST['message'];
     
     
     
        $nexmo_sms = new NexmoMessage('mes info API ici', 'mes info API ici');
     
     
        $info = $nexmo_sms->sendText( $toNumber, $from, $message );
     
     
        echo $nexmo_sms->displayOverview($info);
     
    }  
     
    ?>

    ici celui du ficihier message.php


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    <?php
     
    /**
     * Class NexmoMessage handles the methods and properties of sending an SMS message.
     *
     * Usage: $var = new NexoMessage ( $account_key, $account_password );
     * Methods:
     *     sendText ( $to, $from, $message, $unicode = null )
     *     sendBinary ( $to, $from, $body, $udh )
     *     pushWap ( $to, $from, $title, $url, $validity = 172800000 )
     *     displayOverview( $nexmo_response=null )
     *    
     *     inboundText ( $data=null )
     *     reply ( $text )
     *    
     *
     */
     
    class NexmoMessage {
     
        // Nexmo account credentials
        private $nx_key = '';
        private $nx_secret = '';
     
        /**
         * @var string Nexmo server URI
         *
         * We're sticking with the JSON interface here since json
         * parsing is built into PHP and requires no extensions.
         * This will also keep any debugging to a minimum due to
         * not worrying about which parser is being used.
         */
        var $nx_uri = 'https://rest.nexmo.com/sms/json';
     
     
        /**
         * @var array The most recent parsed Nexmo response.
         */
        private $nexmo_response = '';
     
     
        /**
         * @var bool If recieved an inbound message
         */
        var $inbound_message = false;
     
     
        // Current message
        public $to = '';
        public $from = '';
        public $text = '';
        public $network = '';
        public $message_id = '';
     
        // A few options
        public $ssl_verify = false; // Verify Nexmo SSL before sending any message
     
     
        function NexmoMessage ($api_key, $api_secret) {
            $this->nx_key = $api_key;
            $this->nx_secret = $api_secret;
        }
     
     
     
        /**
         * Prepare new text message.
         *
         * If $unicode is not provided we will try to detect the
         * message type. Otherwise set to TRUE if you require
         * unicode characters.
         */
        function sendText ( $to, $from, $message, $unicode=null ) {
     
            // Making sure strings are UTF-8 encoded
            if ( !is_numeric($from) && !mb_check_encoding($from, 'UTF-8') ) {
                trigger_error('$from needs to be a valid UTF-8 encoded string');
                return false;
            }
     
            if ( !mb_check_encoding($message, 'UTF-8') ) {
                trigger_error('$message needs to be a valid UTF-8 encoded string');
                return false;
            }
     
            if ($unicode === null) {
                $containsUnicode = max(array_map('ord', str_split($message))) > 127;
            } else {
                $containsUnicode = (bool)$unicode;
            }
     
            // Make sure $from is valid
            $from = $this->validateOriginator($from);
     
            // URL Encode
            $from = urlencode( $from );
            $message = urlencode( $message );
     
            // Send away!
            $post = array(
                'from' => $from,
                'to' => $to,
                'text' => $message,
                'type' => $containsUnicode ? 'unicode' : 'text'
            );
            return $this->sendRequest ( $post );
     
        }
     
     
        /**
         * Prepare new WAP message.
         */
        function sendBinary ( $to, $from, $body, $udh ) {
     
            //Binary messages must be hex encoded
            $body = bin2hex ( $body );
            $udh = bin2hex ( $udh );
     
            // Make sure $from is valid
            $from = $this->validateOriginator($from);
     
            // Send away!
            $post = array(
                'from' => $from,
                'to' => $to,
                'type' => 'binary',
                'body' => $body,
                'udh' => $udh
            );
            return $this->sendRequest ( $post );
     
        }
     
     
        /**
         * Prepare new binary message.
         */
        function pushWap ( $to, $from, $title, $url, $validity = 172800000 ) {
     
            // Making sure $title and $url are UTF-8 encoded
            if ( !mb_check_encoding($title, 'UTF-8') || !mb_check_encoding($url, 'UTF-8') ) {
                trigger_error('$title and $udh need to be valid UTF-8 encoded strings');
                return false;
            }
     
            // Make sure $from is valid
            $from = $this->validateOriginator($from);
     
            // Send away!
            $post = array(
                'from' => $from,
                'to' => $to,
                'type' => 'wappush',
                'url' => $url,
                'title' => $title,
                'validity' => $validity
            );
            return $this->sendRequest ( $post );
     
        }
     
     
        /**
         * Prepare and send a new message.
         */
        private function sendRequest ( $data ) {
            // Build the post data
            $data = array_merge($data, array('username' => $this->nx_key, 'password' => $this->nx_secret));
            $post = '';
            foreach($data as $k => $v){
                $post .= "&$k=$v";
            }
     
            // If available, use CURL
            if (function_exists('curl_version')) {
     
                $to_nexmo = curl_init( $this->nx_uri );
                curl_setopt( $to_nexmo, CURLOPT_POST, true );
                curl_setopt( $to_nexmo, CURLOPT_RETURNTRANSFER, true );
                curl_setopt( $to_nexmo, CURLOPT_POSTFIELDS, $post );
     
                if (!$this->ssl_verify) {
                    curl_setopt( $to_nexmo, CURLOPT_SSL_VERIFYPEER, false);
                }
     
                $from_nexmo = curl_exec( $to_nexmo );
                curl_close ( $to_nexmo );
     
            } elseif (ini_get('allow_url_fopen')) {
                // No CURL available so try the awesome file_get_contents
     
                $opts = array('http' =>
                    array(
                        'method'  => 'POST',
                        'header'  => 'Content-type: application/x-www-form-urlencoded',
                        'content' => $post
                    )
                );
                $context = stream_context_create($opts);
                $from_nexmo = file_get_contents($this->nx_uri, false, $context);
     
            } else {
                // No way of sending a HTTP post
                return false;
            }
     
     
            return $this->nexmoParse( $from_nexmo );
     
        }
     
     
        /**
         * Recursively normalise any key names in an object, removing unwanted characters
         */
        private function normaliseKeys ($obj) {
            // Determine is working with a class or araay
            if ($obj instanceof stdClass) {
                $new_obj = new stdClass();
                $is_obj = true;
            } else {
                $new_obj = array();
                $is_obj = false;
            }
     
     
            foreach($obj as $key => $val){
                // If we come across another class/array, normalise it
                if ($val instanceof stdClass || is_array($val)) {
                    $val = $this->normaliseKeys($val);
                }
     
                // Replace any unwanted characters in they key name
                if ($is_obj) {
                    $new_obj->{str_replace('-', '', $key)} = $val;
                } else {
                    $new_obj[str_replace('-', '', $key)] = $val;
                }
            }
     
            return $new_obj;
        }
     
     
        /**
         * Parse server response.
         */
        private function nexmoParse ( $from_nexmo ) {
            $response = json_decode($from_nexmo);
     
            // Copy the response data into an object, removing any '-' characters from the key
            $response_obj = $this->normaliseKeys($response);
     
            if ($response_obj) {
                $this->nexmo_response = $response_obj;
     
                // Find the total cost of this message
                $response_obj->cost = $total_cost = 0;
                if (is_array($response_obj->messages)) {
                    foreach ($response_obj->messages as $msg) {
                        $total_cost = $total_cost + (float)$msg->messageprice;
                    }
     
                    $response_obj->cost = $total_cost;
                }
     
                return $response_obj;
     
            } else {
                // A malformed response
                $this->nexmo_response = array();
                return false;
            }
     
        }
     
     
        /**
         * Validate an originator string
         *
         * If the originator ('from' field) is invalid, some networks may reject the network
         * whilst stinging you with the financial cost! While this cannot correct them, it
         * will try its best to correctly format them.
         */
        private function validateOriginator($inp){
            // Remove any invalid characters
            $ret = preg_replace('/[^a-zA-Z0-9]/', '', (string)$inp);
     
            if(preg_match('/[a-zA-Z]/', $inp)){
     
                // Alphanumeric format so make sure it's < 11 chars
                $ret = substr($ret, 0, 11);
     
            } else {
     
                // Numerical, remove any prepending '00'
                if(substr($ret, 0, 2) == '00'){
                    $ret = substr($ret, 2);
                    $ret = substr($ret, 0, 15);
                }
            }
     
            return (string)$ret;
        }
     
     
     
        /**
         * Display a brief overview of a sent message.
         * Useful for debugging and quick-start purposes.
         */
        public function displayOverview( $nexmo_response=null ){
            $info = (!$nexmo_response) ? $this->nexmo_response : $nexmo_response;
     
            if (!$nexmo_response ) return 'Cannot display an overview of this response';
     
            // How many messages were sent?
            if ( $info->messagecount > 1 ) {
     
                $status = 'Your message was sent in ' . $info->messagecount . ' parts';
     
            } elseif ( $info->messagecount == 1) {
     
                $status = 'Your message was sent';
     
            } else {
     
                return 'There was an error sending your message';
            }
     
            // Build an array of each message status and ID
            if (!is_array($info->messages)) $info->messages = array();
            $message_status = array();
            foreach ( $info->messages as $message ) {
                $tmp = array('id'=>'', 'status'=>0);
     
                if ( $message->status != 0) {
                    $tmp['status'] = $message->errortext;
                } else {
                    $tmp['status'] = 'OK';
                    $tmp['id'] = $message->messageid;
                }
     
                $message_status[] = $tmp;
            }
     
     
            // Build the output
            if (isset($_SERVER['HTTP_HOST'])) {
                // HTML output
                $ret = '<table><tr><td colspan="2">'.$status.'</td></tr>';
                $ret .= '<tr><th>Status</th><th>Message ID</th></tr>';
                foreach ($message_status as $mstat) {
                    $ret .= '<tr><td>'.$mstat['status'].'</td><td>'.$mstat['id'].'</td></tr>';
                }
                $ret .= '</table>';
     
            } else {
     
                // CLI output
                $ret = "$status:\n";
     
                // Get the sizes for the table
                $out_sizes = array('id'=>strlen('Message ID'), 'status'=>strlen('Status'));
                foreach ($message_status as $mstat) {
                    if ($out_sizes['id'] < strlen($mstat['id'])) {
                        $out_sizes['id'] = strlen($mstat['id']);
                    }
                    if ($out_sizes['status'] < strlen($mstat['status'])) {
                        $out_sizes['status'] = strlen($mstat['status']);
                    }
                }
     
                $ret .= '  '.str_pad('Status', $out_sizes['status'], ' ').'   ';
                $ret .= str_pad('Message ID', $out_sizes['id'], ' ')."\n";
                foreach ($message_status as $mstat) {
                    $ret .= '  '.str_pad($mstat['status'], $out_sizes['status'], ' ').'   ';
                    $ret .= str_pad($mstat['id'], $out_sizes['id'], ' ')."\n";
                }
            }
     
            return $ret;
        }
     
     
     
     
     
     
     
        /**
         * Inbound text methods
         */
     
     
        /**
         * Check for any inbound messages, using $_GET by default.
         *
         * This will set the current message to the inbound
         * message allowing for a future reply() call.
         */
        public function inboundText( $data=null ){
            if(!$data) $data = $_GET;
     
            if(!isset($data['text'], $data['msisdn'], $data['to'])) return false;
     
            // Get the relevant data
            $this->to = $data['to'];
            $this->from = $data['msisdn'];
            $this->text = $data['text'];
            $this->network = (isset($data['network-code'])) ? $data['network-code'] : '';
            $this->message_id = $data['messageId'];
     
            // Flag that we have an inbound message
            $this->inbound_message = true;
     
            return true;
        }
     
     
        /**
         * Reply the current message if one is set.
         */
        public function reply ($message) {
            // Make sure we actually have a text to reply to
            if (!$this->inbound_message) {
                return false;
            }
     
            return $this->sendText($this->from, $this->to, $message);
        }
     
    }

  2. #2
    Membre confirmé Avatar de ma5t3r
    Homme Profil pro
    Développeur freelance
    Inscrit en
    Mai 2015
    Messages
    320
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2015
    Messages : 320
    Points : 492
    Points
    492
    Par défaut
    Salut,
    pour faire ton envoi multiple, il faut logiquement mettre ton traitement dans une "boucle".
    En PHP (comme dans d'autres langages), il existe plusieurs façons de faire.

    https://www.php.net/manual/fr/contro...ures.while.php
    https://www.php.net/manual/fr/contro...s.do.while.php
    https://www.php.net/manual/fr/contro...ctures.for.php
    https://www.php.net/manual/fr/contro...es.foreach.php

  3. #3
    Membre confirmé Avatar de ma5t3r
    Homme Profil pro
    Développeur freelance
    Inscrit en
    Mai 2015
    Messages
    320
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2015
    Messages : 320
    Points : 492
    Points
    492
    Par défaut
    Voici un exemple que tu peux mettre à ta sauce

    Ceci doit s'approcher de ce dont tu as besoin
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    $messages = array(
      array('number' => '0000000000', 'from' => 'message from', 'message' => 'un message pour le number 0000000000',),
      array('number' => '0000000001', 'from' => 'message from', 'message' => 'un message pour le number 0000000001',),
      array('number' => '0000000002', 'from' => 'message from', 'message' => 'un message pour le number 0000000002',),
      array('number' => '0000000003', 'from' => 'message from', 'message' => 'un message pour le number 0000000003',),
    );
     
    foreach($message as $m):
       $nexmo_sms = new NexmoMessage('mes info API ici', 'mes info API ici');
       $info = $nexmo_sms->sendText( $m['number'], $m['from'], $m['message']);
       echo $nexmo_sms->displayOverview($info);
    endforeach;

  4. #4
    Futur Membre du Club
    Homme Profil pro
    Webmaster
    Inscrit en
    Mai 2020
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 27
    Localisation : Bénin

    Informations professionnelles :
    Activité : Webmaster
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Mai 2020
    Messages : 6
    Points : 7
    Points
    7
    Par défaut
    cool.. ça marche ... Grand merci à vous

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Comment utiliser Windows Shell API ?
    Par evlan dans le forum Windows
    Réponses: 1
    Dernier message: 11/02/2007, 22h38
  2. [VB.Net]Utilisation de l'API OOo
    Par DonF dans le forum Windows Forms
    Réponses: 2
    Dernier message: 24/01/2007, 13h13
  3. [SOAP] Utilisation de quelle API ?
    Par _beber85 dans le forum Services Web
    Réponses: 3
    Dernier message: 29/05/2006, 13h21
  4. [DOM] Utilisation de l'API DOM pour créer du HTML sous IE
    Par pedouille dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 11/01/2006, 14h48
  5. (Problème) Utilisation de l'API mySQL [Delphi 2005 Perso]
    Par will-scs dans le forum Bases de données
    Réponses: 2
    Dernier message: 08/08/2005, 18h26

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo