Coder Social home page Coder Social logo

messagebird / php-rest-api Goto Github PK

View Code? Open in Web Editor NEW
159.0 159.0 94.0 979 KB

This repository contains the open source PHP client for MessageBird's REST API.

Home Page: https://developers.messagebird.com/

License: BSD 2-Clause "Simplified" License

PHP 100.00%

php-rest-api's People

Contributors

bviolier avatar chrisminett avatar dennisvdvliet avatar dirk94 avatar dstotijn avatar edofre avatar epels avatar gronostajo avatar guiajlopes avatar jalerson avatar jildertmiedema avatar johnstoncode avatar kcroxford-mb avatar marcelcorso avatar mariuspot avatar melvinloos avatar michalbundyra avatar mrdm-nl avatar paolobueno avatar rfeiner avatar rjelierse avatar samwierema avatar sotoz avatar spacepossum avatar spaitnet avatar surik avatar vallerion avatar xethron avatar yevkov avatar ziming 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  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  avatar  avatar

Watchers

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

php-rest-api's Issues

No ID in the response

Hi,

according to the documentation each request should get a response including an ID attribute.
However, when I'm doing a post request including a scheduled dateTime, the response does not include this ID.
What am I doing wrong here?

To replicate, here's the call I'm making in PHP:

$message 					= new \MessageBird\Objects\Message();
$message->scheduledDatetime = "2017-01-07T18:00:00+00:00";
$message->originator 		        = 'Mister X';
$message->recipients 		        = array('0641107800')
$message->body 				= "Test message";

The server response in JSON is as following:

body
	
	"Dit bericht wordt 2 dagen van te voren verzonden"
datacoding
	
	"plain"
direction
	
	"mt"
gateway
	
	2
mclass
	
	1
originator
	
	"Sector X"
recipients
	
	Object { totalCount=1,  totalSentCount=0,  totalDeliveredCount=0,  meer...}
reference
	
	null
scheduledDatetime
	
	"2017-01-07T18:00:00+00:00"
type
	
	"sms"
typeDetails
	
	Object {}
validity
	
	null

This differs from the example response (as shown on (https://developers.messagebird.com/docs/messaging#messaging-send) on several variables but most importantly to me, this ID parameter is missing, which makes it impossible to store the ID and retrieve it's status on a different moment in time.

For a bit more insight: I'm developing an application that allows the user of the application to schedule messages for certain registered members. Therefore I need to determine for each user which messages are scheduled already, and therefore need their ID's to do a GET request (or even a POST delete request).

Any thoughts are more then welcome. Thanks!

Discontinue support for old PHP versions

As you can see from the list of supported versions, most of the versions we're still actively supporting are no longer supported by PHP itself. It might be time to drop support for these versions and update to use language features that are only available on later versions (e.g. type hinting of scalars). Older versions of this package will still be available to those that insist of running on ancient PHP versions, but they would be excluded from new functionality onwards.

Cannot access whatsapp contact list

Hi,
I'm pulling whatsapp conversations using "list.php" under the conversation folder. first and last name fields returns null. I could not reach the whatsapp contact list records on the site with the API. I will be glad if you help. have a nice day.

New release

Currently latest tagged release produces deprecations on PHP 8.1.

These are fixed in main.

Could you please tag a new release so that we can upgrade?

HTTPClient injection through constructor is wrongfully reused

When construction the client you can only pass one HTTPClient; @ see
https://github.com/messagebird/php-rest-api/blob/master/src/MessageBird/Client.php#L95
The client is used for both chat and messaging while the services have diff. end-points.

I would like to suggest to add an additional parameter to the constructor allowing two HTTPClient's to be passed, i.e. something like this;

public function __construct($accessKey = null, Common\HttpClient $httpClient = null, Common\HttpClient $httpChatClient = null)

Since the class is not declared final the change would be a BC break, so I would like to suggest doing the change on a new 2.x line and release the change on a 2.0 tag.

Whatsapp template with URL button and variable

I have a Whatsapp template approved which includes a variable in the body text {{1}} and a variable in the URL of a button: https://[fixed-url]/{{1}}. Both variables were required to start with index 1 to get the template approved.

The code below works with templates with just one variable, without any buttons.
When I tried to add a second parameter, I am getting an error MessageBird\Exceptions\RequestException: An internal error occurred. It seems the variable for the button should not be submitted the same as regular variables, also given the index number.

While searching through the code, I'm not sure if buttons in templates with variables are supported in this library. Anybody would be able to confirm this? If so, I will look for alternatives to make this work.

EDIT: seems #121 is related. So not possible with the library out of the box...

$messageBird = new \MessageBird\Client('api_key'); // Set your own API access key here.

$param = new \MessageBird\Objects\Conversation\HSM\Params();
$param->default = 'XXXXX';

$language = new \MessageBird\Objects\Conversation\HSM\Language();
$language->policy = \MessageBird\Objects\Conversation\HSM\Language::DETERMINISTIC_POLICY;
$language->code = 'nl';

$hsm = new \MessageBird\Objects\Conversation\HSM\Message();
$hsm->templateName	= 'name_template';
$hsm->namespace		= 'namespace';
$hsm->params		= array($param);
$hsm->language		= $language;

$content = new \MessageBird\Objects\Conversation\Content();
$content->hsm = $hsm;

$message = new \MessageBird\Objects\Conversation\Message();
$message->channelId = 'channelid';
$message->content = $content;
$message->to = '31612345678';
$message->type = 'hsm';

try {
	$conversation = $messageBird->conversations->start($message);
    echo '<pre>';
	var_dump($conversation);
} catch (\Exception $e) {
    echo sprintf("%s: %s", get_class($e), $e->getMessage());
}

No support for HTTP proxies

We would like to connect to the MessageBird API using an HTTP proxy.

Unfortunately there is no option available to set this.

SignedRequest->createFromGlobals() does not set requestTimestamp to integer

When I am trying to use the SignedRequest->createFromGlobals(), it pulls the requestTimestamp but returns it as a string instead of as an integer, even though it is actually all numeric digits. So it was failing the validation (!is_int($param['requestTimestamp']) in the loadFromArray() method and throwing an Exception.

That has required me to use the SignedRequest->create() and manually retrieve the necessary variables. It seems to work so far, but it would be nice to be able to use the createFromGlobals() method and not have to manually retrieve and pass those values.

I'm using php7.2 with nginx with Laravel 5.8.9 if that makes a difference.

Map incoming message to Message object

I'd expect an SDK to have a method for mapping an incoming message (on the callback URL) to a Message object or am I overlooking something completely? The only method loadFromArray only maps properties with the same name, so from an incoming JSON as array like this:

Array
(
    [id] => .....
    [contactId] => .....
    [channelId] => .....
    [type] => text
    [payload] => blah
    [mediaPath] => 
    [status] => received
    [direction] => mo
    [reference] => 
    [scheduledAt] => 
    [createdAt] => 2018-07-28 04:19:50
    [updatedAt] => 
    [_links] => Array(.....)
)

I get this:

MessageBird\Objects\Message Object
(
    [id:protected] => ab68350c5b5beee6b27742n19299373
    [href:protected] => 
    [direction] => mo
    [type] => text
    [originator] => 
    [body] => 
    [reference] => 
    [validity] => 
    [gateway] => 
    [typeDetails] => Array()
    [datacoding] => plain
    [mclass] => 1
    [scheduledDatetime] => 
    [createdDatetime:protected] => 
    [recipients] => Array()
    [reportUrl] => 
)

Of course I can write a simple mapper, it's just that I expected it to be already there.
Any idea?

Thanks!

Recipient Class - Extend to include additional data i.e. messagePartCount

We're currently building an integration using this API and have become a little stuck, hoping for any advice if there is a different way forward.

After calling the create method and receiving a response the recipients are looped over an created using the loadFromArray function in base however this only populates variables that are defined on the class. The Recipient class only contains the status and statusDatetime fields however the response returned from the API contains many more e.g. messagePartCount, messageLength, mccmnc, etc...

The general issue this causes is that you lack possibly useful information that the code throws away. In our specific case the messagePartCount is useful for determining specifically how many messages were used but I'm sure that many others may have other cases.

Is there any reason why the Recipient class could not simply be extended with all of the fields available? Or allow it to be extended by a custom instance (perhaps using a config file to determine which class to use as a recipient)? As I said the method of fixing is completely up for debate but any help would be greatly appreciated.

`getList()` breaks when no results are present (Invalid argument supplied for foreach())

The following is happening in MessageBird\Resources\Base getList()

if ($status === 200) {
            $body = json_decode($body);

            $Items = $body->items;
            unset($body->items);

            $BaseList = new Objects\BaseList();
            $BaseList->loadFromArray($body);

            $objectName = $this->Object;

            foreach ($Items AS $Item) {

Now this will work fine until for example you want to fetch all webhooks while no webhooks have been created yet. The api will return {"offset":0,"limit":10,"count":0,"totalCount":0,"items":null} and after the json_decode $Items will contain null and the foreach happening on line 103 will break with an

Invalid argument supplied for foreach()

environment: php 7.4.9

Am i the first one having this issue or am i doing something wrong?

HSM Components objects are missing

How can I send a Media Template using the PHP SDK. As the HSM Components and Components/Parameters are missing, I don't know how to do it with the existing classes.

Do you have an example? Do I have to use plain curl?

Thank you very much.

Replace YOUR_ACCESS_KEY with safer alternative in api literal

Many (all?) of the examples create a Client instance as follows:

$Messagebird = new \MessageBird\Client('YOUR_ACCESS_KEY')

It is dangerous to put sensitive credentials in the code when it is easy to push to a public location (.e.g. this github repo). Everytime a user wants to run an example. that person is forced to do one of two things:

  • replace YOUR_ACCESS_KEY with the string literal containing the actual sensitive key, and remember not to push until the key has been replaced back,
  • replace YOUR_ACCESS_KEY with something like getenv and change it back again before pushing.

I propose that we just replace YOUR_ACCESS_KEY with getenv everywhere. Running the examples then no longer require a possibly dangerous code change.

Message 'id' and 'href' missing in $MessageBird->messages->getList() response

When I retieve the list of messages I don't see the ["id":protected] and the ["href":protected] information in the response like it's shown in the documentation (https://developers.messagebird.com/api/sms-messaging/#list-messages):

object(MessageBirdObjectsBaseList)#128 (6) {
  ["limit"]=>
  int(30)
  ["offset"]=>
  int(0)
  ["count"]=>
  int(18)
  ["totalCount"]=>
  int(18)
  ["links"]=>
  object(stdClass)#55 (4) {
    ["first"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
    ["previous"]=>
    NULL
    ["next"]=>
    NULL
    ["last"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
  }
  ["items"]=>
  array(1) {
    [0]=>
    object(MessageBirdObjectsMessage)#123 (16) {
      ["id":protected]=>
      string(32) "7f6526d794ac4cd1bdb262d86356d341"
      ["href":protected]=>
      string(70) "https://rest.messagebird.com/messages/7f6526d794ac4cd1bdb262d86356d341"
      ["direction"]=>
      string(2) "mt"

The response I receive starts with the ["direction"] information for each of the items (=messages).

Is something broken? Or am I doing something wrong?

I'm using:

$MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
var_dump($MessageList);

to get hold of the list with messages.

I'm using v2.0.1 of the php-rest-api.

Fix PHP 5.3 incompatibility

The Content, Message and Webhook models for the Conversations API use the JsonSerializable interface, which was introduced in PHP 5.4 - so this breaks compatibility with 5.3.

Recipients are broken since 1.19.1

I believe 1.19.1, which featured #103 should not be released as a minor change, but rather in a new major version release, as it's not backwards compatible:

  1. Since the types changed, all code using recipients as arrays broke.
    Previously, this worked fine:
$messageBirdMessage->recipients = [$number];

But that now breaks.
2. The Recipient class defines the $recipient property as integer (https://github.com/messagebird/php-rest-api/blob/master/src/MessageBird/Objects/Recipient.php#L16), while that formerly accepted a string, which can still be seen in the examples (https://github.com/messagebird/php-rest-api/blob/master/examples/message-create.php#L9). The original documentation also shows that string values are allowed (https://developers.messagebird.com/quickstarts/sms/send-sms-curl/), so why this changed is unclear. This doesn't break code as much, as it's not strictly enforced by the compiler, but does break PHPStan checking my code.
3. Examples have not been updated, so documentation is now very confusing for new users.

All-in-all, I think the best course of action now would be to:

  1. Revert the changes in 1.19.1, releasing 1.19.2 as a fix
  2. Fix the documentation, examples and types
  3. Release 2.0 with this change again

msidn duplicate exception

I know that this issue might be more related to the API itself but ..

<?php
require 'vendor/autoload.php';
$ACCESS_KEY = '';//FILL access key

$c = new \MessageBird\Client($ACCESS_KEY);
$contact = new \MessageBird\Objects\Contact();
$contact->msisdn = "31613371337";
$contact->firstName = "Foo";
$contact->lastName = "Bar";
$contact = $c->contacts->create($contact);


$contact->firstName = "Foo changed";
$c->contacts->update($contact, $contact->getId());

This code snippet causes an exception like:

contact with this msisdn already exists in your contact list

The system checks if the msidn already exists, but in this case i am just not changing it...

Why? Keeping track if the phone number did or did not change is not very practical in a lot of use cases. I can work around it by always deleting and then adding the contact again but that has some disadvantages.

Message->create() not returning id

I don't get an id in the response, it also does not return the value I set for reportUrl


$Message = new \MessageBird\Objects\Message();

$Message->scheduledDatetime = date('Y-m-d\TH:i:sP', $sms['sms_send_time']);
$Message->originator = $sms['sms_from'];
$Message->reference = $sms['sms_id'];
$Message->recipients = [$sms['sms_to']];
$Message->body = $sms['message'];

$Message->reportUrl = 'https://api.alpaka.io/_sms/sms_callback.php?c='.$sms['cust_id'].'&s='.$sms['sms_id'];
			
$r = $clients['messagebird']->messages->create($Message);

$r = json_encode($r, true);
$r = json_decode($r);

echo '<pre>';
print_r($r);
echo '</pre>';

response as an array is


Array
(
    [direction] => mt
    [type] => sms
    [originator] => +447418310---
    [body] => Hi, I can't make it today, sorr
    [reference] => 143
    [validity] => 
    [gateway] => 10
    [typeDetails] => Array
        (
        )

    [datacoding] => plain
    [mclass] => 1
    [scheduledDatetime] => 2019-05-05T18:32:56+00:00
    [recipients] => Array
        (
            [totalCount] => 1
            [totalSentCount] => 0
            [totalDeliveredCount] => 0
            [totalDeliveryFailedCount] => 0
            [items] => Array
                (
                    [0] => Array
                        (
                            [recipient] => 447540739---
                            [status] => scheduled
                            [statusDatetime] => 
                        )

                )

        )

    [reportUrl] => 
)

Test message with test number not sending to mobile

It give the response that message is sent. But did not display in sms overview and not able to get on mobile as well.

From the message unique id I try to get that message with this api:

MessageBird->messages->read();

then also in response it get no message found.

In GUI it is working perfectly fine. with api it not.

here is the response:

MessageBird\Objects\Message Object
(
    [id:protected] => 53ad3b2858804ca5ab5b2bb73d3d84a4
    [href:protected] => https://rest.messagebird.com/messages/53ad3b2858804ca5ab5b2bb73d3d84a4
    [direction] => mt
    [type] => sms
    [originator] => mobile number
    [body] => 072822
    [reference] => 
    [validity] => 
    [gateway] => 10
    [typeDetails] => stdClass Object
        (
        )

    [datacoding] => plain
    [mclass] => 1
    [scheduledDatetime] => 
    [createdDatetime:protected] => 2018-06-12T11:47:22+00:00
    [recipients] => stdClass Object
        (
            [totalCount] => 1
            [totalSentCount] => 1
            [totalDeliveredCount] => 0
            [totalDeliveryFailedCount] => 0
            [items] => Array
                (
                    [0] => MessageBird\Objects\Recipient Object
                        (
                            [recipient] => mobile number
                            [status] => sent
                            [statusDatetime] => 2018-06-12T11:47:22+00:00
                        )

                )

        )

    [reportUrl] => 
)

Please use semver and release 1.14.1

Following semantic versioning (https://semver.org/), your "oops" version of 1.14.0.1 does not fit as proper release tag. You should issue a 1.14.1 patch release instead.

Also, if you want to use the version of your package inside your package, there are alternatives to using a hardcoded string

See:

Package managers could interpret 1.14.0.1 with the .1 suffix being a pre-release or build metadata info and not a real version.

Updated Certificate

Hello,

I have just gotten word that the certificate that is used for the REST api is being updated, will this also impact applications utilizing this library?

If so, will this library be updated to support the new certificate?

MessageBirdException improvement

Hi MessageBird team,

I'm having some inconveniences handling MessageBirdExceptions.
My code looks like this:

try {
    $this->messageBirdClient->messages->create($message);
} catch (MessageBirdException $e) {
    $this->writeln($e->getMessage()); // console output
}

It works fine but in case of catching certain exceptions types $e->getMessage() returns null (see https://github.com/messagebird/php-rest-api/blob/master/src/MessageBird/Common/ResponseError.php#L44). At the same time reasonable error message is returned in a response:

...
["errors"]=>
      array(1) {
        [0]=>
        object(stdClass)#62 (3) {
          ["code"]=>
          int(2)
          ["description"]=>
          string(42) "Request not allowed (incorrect access_key)"
          ["parameter"]=>
          string(10) "access_key"
        }
      }
...

Because of this I have to handle these cases separately which is not what I want to do.

My suggestion is to add error description to MessageBirdException in all cases.

Thanks,
Andrey

Messagebird API Lookup function does not reset on consecutive requests

I am using the messagebird API to send messages through Messagebird from a client website.

This works very well with a single lookup ($nummer is the number to check):

try {
$Lookup = $MessageBird->lookup->read($nummer);
} catch (\MessageBird\Exceptions\AuthenticateException $e) {
echo 'Onjuiste toegangscode';
} catch (\Exception $e) {
var_dump($e->getMessage());
}

The response is good, it shows a hlr object when the number is valid and no hlr object when the number is not:

MessageBird\Objects\Lookup Object
(
[href:protected] => https://rest.messagebird.com/lookup/31645621997
[countryCode:protected] => NL
[countryPrefix:protected] => 31
[phoneNumber:protected] => 31645621997
[type:protected] => mobile
[formats:protected] => stdClass Object
(
[e164] => +31645621997
[international] => +31 6 45621997
[national] => 06 45621997
[rfc3966] => tel:+31-6-45621997
)

[hlr:protected] => stdClass Object
    (
        [id] => 0d9a26f5557bc00c02407d2h55197935
        [network] => 20412
        [details] => stdClass Object
            (
                [country_iso] => NLD
                [country_name] => Netherlands
                [imsi] => 204125900111663
                [location_iso] => nl
                [location_msc] => 31653
                [ported] => 0
                [roaming] => 0
                [status_desc] => 
            )

        [reference] => yoloswag3001
        [status] => active
        [createdDatetime] => 2016-08-23T07:52:32+00:00
        [statusDatetime] => 2016-08-23T07:52:34+00:00
    )

)

However, when i use the same lookup function in a loop (to verify multiple numbers from an Excel input form), the API returns a hlr oject with a status "valid" for each number, even if the number is bogus, example output:

MessageBird\Objects\Lookup Object
(
[href:protected] => https://rest.messagebird.com/lookup/31645621997
[countryCode:protected] => NL
[countryPrefix:protected] => 31
[phoneNumber:protected] => 31645621997
[type:protected] => mobile
[formats:protected] => stdClass Object
(
[e164] => +31645621997
[international] => +31 6 45621997
[national] => 06 45621997
[rfc3966] => tel:+31-6-45621997
)

[hlr:protected] => stdClass Object
    (
        [id] => 0d9a26f5557bc00c02407d2h55197935
        [network] => 20412
        [details] => stdClass Object
            (
                [country_iso] => NLD
                [country_name] => Netherlands
                [imsi] => 204125900111663
                [location_iso] => nl
                [location_msc] => 31653
                [ported] => 0
                [roaming] => 0
                [status_desc] => 
            )

        [reference] => yoloswag3001
        [status] => active
        [createdDatetime] => 2016-08-23T07:52:32+00:00
        [statusDatetime] => 2016-08-23T07:52:34+00:00
    )

)
MessageBird\Objects\Lookup Object
(
[href:protected] => https://rest.messagebird.com/lookup/31611111111
[countryCode:protected] => NL
[countryPrefix:protected] => 31
[phoneNumber:protected] => 31611111111
[type:protected] => mobile
[formats:protected] => stdClass Object
(
[e164] => +31611111111
[international] => +31 6 11111111
[national] => 06 11111111
[rfc3966] => tel:+31-6-11111111
)

[hlr:protected] => stdClass Object
    (
        [id] => 0d9a26f5557bc00c02407d2h55197935
        [network] => 20412
        [details] => stdClass Object
            (
                [country_iso] => NLD
                [country_name] => Netherlands
                [imsi] => 204125900111663
                [location_iso] => nl
                [location_msc] => 31653
                [ported] => 0
                [roaming] => 0
                [status_desc] => 
            )

        [reference] => yoloswag3001
        [status] => active
        [createdDatetime] => 2016-08-23T07:52:32+00:00
        [statusDatetime] => 2016-08-23T07:52:34+00:00
    )

)

The second number is bogus but does still return a hlr object with a status "active".

I have tried unsetting $Lookup after each lookup and i have tried to build in a sleep(5) to pause the loop, but neither resolve the problem.

The problem seems to occur because $MessageBird->lookup seems to save the hlr block after the first lookup, even if you call the function again.

[ Messaging Responses ]

Why the answer only returns 1 if I do ID sending to an array of numbers?

It should not be different IDs in each recipients-> items?

Example:

{
  "BulkId":"123abc",
  "href":"https://rest.messagebird.com/bulk/123abc",
  "direction":"mt",
  "type":"sms",
  "originator":"YourName",
  "body":"This is a test message",
  "reference":null,
  "validity":null,
  "gateway":null,
  "typeDetails":{

  },
  "datacoding":"plain",
  "mclass":1,
  "scheduledDatetime":null,
  "createdDatetime":"2016-04-30T00:33:22+00:00",
  "recipients":{
    "totalCount":1,
    "totalSentCount":1,
    "totalDeliveredCount":0,
    "totalDeliveryFailedCount":0,
    "items":[
      {
        "id":"1234",
        "href":"https://rest.messagebird.com/messages/1234",
        "recipient":31612345678,
        "status":"sent",
        "statusDatetime":"2016-04-30T00:33:22+00:00"
      },
      {
        "id":"1235",
        "href":"https://rest.messagebird.com/messages/1235",
        "recipient":31612345679,
        "status":"sent",
        "statusDatetime":"2016-04-30T00:33:22+00:00"
      }
    ]
  }
}

Status Message not Deliver

status is status: "sent" but message not coming on target number.

Message {#3451 ▼
  #id: "b6e7e1691c544a1ea478caee28388710"
  #href: "https://rest.messagebird.com/messages/b6e7e1691c544a1ea478caee28388710"
  +direction: "mt"
  +type: "sms"
  +originator: "EduFirm"
  +body: "Dear Student , Thankyou for register with us . this is api testing from messagebird."
  +reference: null
  +validity: null
  +gateway: 10
  +typeDetails: {#3492}
  +datacoding: "plain"
  +mclass: 1
  +scheduledDatetime: null
  #createdDatetime: "2018-06-04T01:47:59+00:00"
  +recipients: {#3493 ▼
    +"totalCount": 1
    +"totalSentCount": 1
    +"totalDeliveredCount": 0
    +"totalDeliveryFailedCount": 0
    +"items": array:1 [▼
      0 => Recipient {#3495 ▼
        +recipient: 9779868156047.0
        +status: "sent"
        +statusDatetime: "2018-06-04T01:47:59+00:00"
      }
    ]
  }
  +reportUrl: null
}

Proxy / HttpClient.php

Sometimes an specific Proxy adds a certain header. In the current version only a specific header is dismissed; but not mine. This code helps allthough it could be improved.

// Split the header and body
$parts = explode("\r\n\r\n", $response, 3);

if ( count( explode( "\r\n", $parts[0] ) ) === 1 ){
  array_shift( $parts );
}

list($responseHeader, $responseBody) = array ($parts[0], $parts[1]);

no (correct) recipients found.

I'm trying out the API and I'm getting the following error:

no (correct) recipients found. Note: during your test period you can only send messages to yourself.

I'm simply setting the receiver to: array($myNumber)

What exactly is meant with during your test period you can only send messages to yourself.? Is there some option/account setting where I can set a default recipient number?

curl timing out one third of the time when sending sms

When using the messages->create API method, one third of my attempts are ending up throwing exceptions with the message "Resolving timed out after 2514 milliseconds". So I was wondering if the number of seconds on curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); on performHttpRequest@HttpClient could become a config parameter, or maybe I should fork the repo?

Boundary conditions are not covered for timeouts in HttpClient

How to Reproduce

  1. In HttpClient code, change timeout check on line 58 from:
if (!is_int($timeout) || $timeout < 1) {

to

if (!is_int($timeout) || $timeout <= 1) {
  1. In HttpClient code, change connection timeout check on line 67 from:
if (!is_int($connectionTimeout) || $connectionTimeout < 0) {

to

if (!is_int($connectionTimeout) || $connectionTimeout <= 0) {

What Should Happen

  1. Some unit tests are broken because they detect the logic change which was not reflected by tests.

What Happens

  1. All unit tests are passing.

HSM Start: Invalid JSON

Hello.

We've tried using the SDK to send a WhatsApp HSL message. To do this we've used the create-hsm example from the example folder. However, it will throw an exception JSON is not a valid format. Then I got looking and found out that this issue is already known for the conversation API. We're using start and not create (Which was the possible fix in the other issue) #95

When we use create instead of start the error gets even funnier. Got an invalid JSON response from the server. I have a feeling that the SDK is not running things correctly, but it can be our stupidity too. I've attached the code.

       $param = new \MessageBird\Objects\Conversation\HSM\Params();
        $param->default = $this->body;

        $language = new \MessageBird\Objects\Conversation\HSM\Language();
        $language->policy = \MessageBird\Objects\Conversation\HSM\Language::DETERMINISTIC_POLICY;
        $language->code = 'EN';

        $hsm = new \MessageBird\Objects\Conversation\HSM\Message();
        $hsm->templateName = $this->template;
        $hsm->namespace = $_ENV['WA_NAMESPACE'];
        $hsm->params = array($param);
        $hsm->language = $language;

        $content = new \MessageBird\Objects\Conversation\Content();
        $content->hsm = $hsm;

        $message = new \MessageBird\Objects\Conversation\Message();
        $message->channelId = $this->channel;
        $message->content = $content;
        $message->to = $this->recipients[0];
        $message->type = 'hsm';

        $conversation = $this->client->conversations->start($message);

Default 2 seconds connection timeout value too low?

I've been having problems sending SMS messages because of connection timeouts. It doesn't happen every time, it's just "random" (my guess just because of the network connection quality "randomness"). Looks like I've been able to fix this using a custom HttpClient with a higher connect timeout value (10 seconds):

use MessageBird\Client;
use MessageBird\Common\HttpClient;

class MessageBird
{
    /** @var \MessageBird\Client $messageBirdClient */
    protected $messageBirdClient;

    public function __construct($key)
    {
        $httpClient = new HttpClient(Client::ENDPOINT, 10, 10); // Change default connection timeout from 2 seconds to 10
        $this->messageBirdClient = new Client($key, $httpClient);
        ...
    }
}

Although this is fine for me, it would make Chat and Voice endpoints not work as addressed in #29 because the endpoints are different and setting a custom HttpClient makes the same client be used in the 3 endpoints, making this solution not perfect for everyone.

The default value for CURLOPT_CONNECTTIMEOUT seems to be 300 seconds, much higher than our 2 seconds. Other language rest API libraries for MessageBird (I've briefly looked at Java, C# and Python libraries) use their HTTP client default values which most of the times AFAIK are set to "infinite".

The last PR that set this value was #28

Having all this in count, may be the default value should be raised. Not just me, I suspect more people may be having the same issue. In that case those 2 lines should be changed and I could provide a PR:

https://github.com/messagebird/php-rest-api/blob/master/src/MessageBird/Common/HttpClient.php#L59

https://github.com/messagebird/php-rest-api/blob/master/src/MessageBird/Client.php#L147

Mac OSX 10.9.5 local development gives SSL certificate problem

On Mac OSX 10.9.5 a call to the API gives an SSL error

MessageBird\Exceptions\HttpException: SSL certificate problem: unable to get local issuer certificate

I did not find out why the MessageBird Cert is not trusted. But the error does not seem to occur on other os (linux etc)

One can switch off verification in Development by using this hack in vendor/messagebird/php-rest-api/src/MessageBird/Common/HttpClient.php:106

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Maybe it is possible to add a function to skip SSL verification in the high level API?

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.