Git Product home page Git Product logo

php-pushwoosh's Introduction

php-pushwoosh

A PHP Library to easily send push notifications with the Pushwoosh REST Web Services.

Total Downloads Latest Stable Version Build Status Coverage Code Climate License

First sample, creating a Pushwoosh message

// Create a Pushwoosh client
$pushwoosh = Pushwoosh::create()
    ->setApplication('XXXX-XXX')
    ->setAuth('xxxxxxxx');

// Create a request for the '/createMessage' Web Service
$request = CreateMessageRequest::create()
    ->addNotification(Notification::create()->setContent('Hello Jean !'));

// Call the REST Web Service
$response = $pushwoosh->createMessage($request);

// Check if its ok
if($response->isOk()) {
    print 'Great, my message has been sent !';
} else {
    print 'Oups, the sent failed :-('; 
    print 'Status code : ' . $response->getStatusCode();
    print 'Status message : ' . $response->getStatusMessage();
}

Easy, isn't it ?

Documentation

Framework Integrations

If you have integrated php-pushwoosh into a popular PHP framework let us know !

About Gomoob

At Gomoob we build high quality software with awesome Open Source frameworks everyday. Would you like to start your next project with us? That's great! Give us a call or send us an email and we will get back to you as soon as possible !

You can contact us by email at [email protected] or by phone number (+33) 6 85 12 81 26 or (+33) 6 28 35 04 49.

Visit also http://gomoob.github.io to discover more Open Source softwares we develop.

php-pushwoosh's People

Contributors

ahmedfawzy avatar anibalsanchez avatar bgaillard avatar curtisgibby avatar falldi avatar p-golovin avatar simonbaudry avatar vinkla 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-pushwoosh's Issues

Add several checks in response to CURL requests

To day we encountered a strange error while trying to send a Pushwoosh message.

Here it is :

Argument 1 passed to Gomoob\Pushwoosh\Model\Response\CreateMessageResponse::create() must be of the type array, null given, called in /home/ec2-user/project-xxxx/zf2/vendor/gomoob/php-pushwoosh/src/main/php/Gomoob/Pushwoosh/Client/Pushwoosh.php on line 142 and defined

It appears the CURLClient.pushwooshCall($method, array $data) returned a null response which is not normal.

The implementation of the CURLClient is not robust enough because it simply log errors in the console which is very very bad.

...

        $response = curl_exec($ch);
        $error = curl_error($ch);

        if ($error) {
            $info = curl_getinfo($ch);

            // FIXME
            var_dump($error);
            var_dump($info);

        }

        curl_close($ch);

        return json_decode($response, true);

Here we should do 2 things :

  • If a curl error is encountered wrap it inside a PushwooshException (perhaps this class has to be improved to be able to attach more details to an exception)
  • If no curl error is encountered and the $response variable is null create a PushwooshException too

In all cases throw the exception if an error is encountered.

Replace the 3 first badges on the home page by shields.io badges

For unknown reasons Pager https://poser.pugx.org does not work, so we have to replace Badge Poser by an other badge service. Shields.io seems to be a good candidate.

Here is the Markdown code to replace de 3 first badges :

  • Total Downloads
  • Latest Stable Version
  • License
[![Total Downloads](https://img.shields.io/packagist/dt/gomoob/php-pushwoosh.svg)](https://packagist.org/packages/gomoob/php-pushwoosh) 
[![Latest Stable Version](https://img.shields.io/github/release/gomoob/php-pushwoosh.svg)](https://packagist.org/packages/gomoob/php-pushwoosh) 
[![License](https://img.shields.io/packagist/l/gomoob/php-pushwoosh.svg)](https://packagist.org/packages/gomoob/php-pushwoosh)

As the library should be a good quality one we could also add the following badges :

  • Issues
[![Issues](https://img.shields.io/github/issues/gomoob/php-pushwoosh.svg)](https://github.com/gomoob/php-pushwoosh/issues)

Create a CURL abstraction.

The Pushwoosh client uses plain CURL calls https://github.com/gomoob/php-pushwoosh/blob/master/src/main/php/Gomoob/Pushwoosh/Client/CURLClient.php.

It works but it does not allow to unit test the class easily, we should create the following abstraction to improve it.

<?php

/**
 * Copyright 2015 SARL GOMOOB. All rights reserved.
 */
namespace Gomoob\Curl;

/**
 * Interface used to abstract the CURL PHP methods.
 *
 * @author Baptiste GAILLARD ([email protected])
 * @see http://php.net/manual/book.curl.php
 */
interface ICurlRequest
{
    /**
     * Set an option for a cURL transfer.
     * 
     * @param int option The CURLOPT_ option to set.
     * @param mixed $value The value to be set on option.
     * 
     * @return {Boolean} Returns TRUE on success or FALSE on failure.
     */
    public function setOpt($option, $value);

    /**
     * Perform a cURL session.
     * 
     * @return mixed Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, 
     *         it will return the result on success, FALSE on failure.
     */
    public function exec();

    /**
     * Get information regarding a specific transfer.
     * 
     * @param int $opt This may be one of the following constants:
     *        * CURLINFO_EFFECTIVE_URL           - Last effective URL
     *        * CURLINFO_HTTP_CODE               - Last received HTTP code
     *        * CURLINFO_FILETIME                - Remote time of the retrieved document, if -1 is returned the time of 
     *                                             the document is unknown
     *        * CURLINFO_TOTAL_TIME              - Total transaction time in seconds for last transfer
     *        * CURLINFO_NAMELOOKUP_TIME         - Time in seconds until name resolving was complete
     *        * CURLINFO_CONNECT_TIME            - Time in seconds it took to establish the connection
     *        * CURLINFO_PRETRANSFER_TIME        - Time in seconds from start until just before file transfer begins
     *        * CURLINFO_STARTTRANSFER_TIME      - Time in seconds until the first byte is about to be transferred
     *        * CURLINFO_REDIRECT_COUNT          - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
     *        * CURLINFO_REDIRECT_TIME           - Time in seconds of all redirection steps before final transaction was 
     *                                             started, with the CURLOPT_FOLLOWLOCATION option enabled
     *        * CURLINFO_REDIRECT_URL            - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found 
     *                                             in the last transaction, that should be requested manually next. With 
     *                                             the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The 
     *                                             redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
     *        * CURLINFO_PRIMARY_IP              - IP address of the most recent connection
     *        * CURLINFO_PRIMARY_PORT            - Destination port of the most recent connection
     *        * CURLINFO_LOCAL_IP                - Local (source) IP address of the most recent connection
     *        * CURLINFO_LOCAL_PORT              - Local (source) port of the most recent connection
     *        * CURLINFO_SIZE_UPLOAD             - Total number of bytes uploaded
     *        * CURLINFO_SIZE_DOWNLOAD           - Total number of bytes downloaded
     *        * CURLINFO_SPEED_DOWNLOAD          - Average download speed
     *        * CURLINFO_SPEED_UPLOAD            - Average upload speed
     *        * CURLINFO_HEADER_SIZE             - Total size of all headers received
     *        * CURLINFO_HEADER_OUT              - The request string sent. For this to work, add the 
     *                                             CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
     *        * CURLINFO_REQUEST_SIZE            - Total size of issued requests, currently only for HTTP requests
     *        * CURLINFO_SSL_VERIFYRESULT        - Result of SSL certification verification requested by setting 
     *                                             CURLOPT_SSL_VERIFYPEER
     *        * CURLINFO_CONTENT_LENGTH_DOWNLOAD - content-length of download, read from Content-Length: field
     *        * CURLINFO_CONTENT_LENGTH_UPLOAD   - Specified size of upload
     *        * CURLINFO_CONTENT_TYPE            - Content-Type: of the requested document, NULL indicates server did 
     *                                             not send valid Content-Type: header
     *        * CURLINFO_PRIVATE                 - Private data associated with this cURL handle, previously set with 
     *                                             the CURLOPT_PRIVATE option of curl_setopt()
     *                                             
     * @return mixed If opt is given, returns its value. Otherwise, returns an associative array with the following 
     *         elements (which correspond to opt), or FALSE on failure:
     *          * "url"
     *          * "content_type"
     *          * "http_code"
     *          * "header_size"
     *          * "request_size"
     *          * "filetime"
     *          * "ssl_verify_result"
     *          * "redirect_count"
     *          * "total_time"
     *          * "namelookup_time"
     *          * "connect_time"
     *          * "pretransfer_time"
     *          * "size_upload"
     *          * "size_download"
     *          * "speed_download"
     *          * "speed_upload"
     *          * "download_content_length"
     *          * "upload_content_length"
     *          * "starttransfer_time"
     *          * "redirect_time"
     *          * "certinfo"
     *          * "primary_ip"
     *          * "primary_port"
     *          * "local_ip"
     *          * "local_port"
     *          * "redirect_url"
     *          * "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to 
     *            curl_setopt())
     *            
     *         Note that private data is not included in the associative array and must be retrieved individually with 
     *         the CURLINFO_PRIVATE option.
     */
    public function getInfo($opt = 0);

    /**
     * Close a cURL session.
     */
    public function close();
}

Add missing notification properties

It seems Pushwoosh added new Android notification properties in their documentation, we should reflect this in our implementation.

// Android related
"android_root_params": {"key": "value"}, // custom key-value object. root level parameters for the android payload recipients
"android_sound" : "soundfile", // Optional. No file extension
"android_header":"header",    // Optional. Android notification header
"android_icon": "icon",
"android_custom_icon": "http://example.com/image.png", // Optional. Full path URL to the image file
"android_banner": "http://example.com/banner.png", // Optional. Full path URL to the image file
"android_badges": 5, // Optional, integer. Android application icon badge number
"android_gcm_ttl": 3600, // Optional. Time to live parameter - the maximum lifespan of a message in seconds

"android_vibration": 0,   // Android force-vibration for high-priority pushes, boolean
"android_led":"#rrggbb",  // LED hex color, device will do its best approximation
"android_priority":-1,  // Priority of the push in the Android push drawer, valid values are -2, -1, 0, 1 and 2
"android_ibc":"#RRGGBB",  // Icon background color on Lollipop, #RRGGBB, #AARRGGBB, "red", "black", "yellow", etc.

We should also check properties for other OS.

Run tests with PHP 7.1

It seems Travis now supprts PHP 7.1 with identifier 7.1.0alpha1, we should add it to our travis confuguration.

Internal Server Error and vendor folder

I am using php-pushwoosh library and am getting an internal server error. I believe we may need to white list the ip but it seems it is constantly changing based on the server data. Also I find it strange that no folder/library was added to vendor for php-pushwoosh after installing it using composer. It shows when doing โ€œphp composer.phar showโ€ but has no files it seems in the vendor folder. I was hoping you could help me figure out what I may need to do for this to work. Here is some screen shots of the afore mentioned instances.

vendor

terminal1

error

Send push notification only to testDevice

We are implementing pushwoosh in production and I don't know how to send push messages only to test devices. That's why I have to be careful doing tests.

Looking in the documentation I found that filters can be applied, can it be that there is a native filter "TestDevices"?

Notification::create()->setFilter ("TestDevices")->setContent ("Content");

If not, as would be the steps to send push notification only to test device, sorry if it is in the documentation and I did not see it.

The PushwooshMock should allow to return testing responses.

The Gomoob\Pushwoosh\Client\PushwooshMock class has several functions, each function is empty and returns nothing which is not really good.

We should be able to return testing payloads in return to those functions, also we should be able to configure the Mock to test several scenarios (success, errors, etc.).

No DefaultTimeOut

We found an issue, that in the CurlClient, you are using there is no default timeout-value set.
In our case the call got stuck.

  • CURLOPT_CONNECTTIMEOUT

    The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

  • CURLOPT_TIMEOUT

    The maximum number of seconds to allow cURL functions to execute.

PHP curl_setopt doc

Better Error Handler

Today our premium account had ended and we had no idea what was going on until I tried making a request directly against the Pushwoosh API. The answer from the Pushwoosh API was:

{#363
  +"status_code": 210
  +"status_message": "This feature is available for Premium accounts only"
  +"response": null
}

Though, this is what I got back from this library:

ErrorException array_key_exists() expects parameter 2 to be array, null given
    vendor/gomoob/php-pushwoosh/src/main/php/Gomoob/Pushwoosh/Model/Response/CreateMessageResponse.php:43

Maybe we can return the error messages whenever the Pushwoosh API return 210?

Code Climate reports a wrong code coverage

It appears that Code Climate displays a bad code coverage (71% but should be 93% now).

This is because Code Climate does not support multiple code coverage payloads for one commit. As a workaround I added a code-climate-test-reporter custom publisher script at the root of the project. This scripts publishes to code climate only if the PHP version is 5.3.

Check if it works when the develop branch is merge into the master branch.

Implement attachment of additional help when an error is encountered

Issue #13 describes an error message This feature is available for Premium accounts only returned by Pushwoosh when the Pushwoosh subscription ended.

As @vinkla indicated in the issue re-activating the subscription takes several hours, so developers will receive a message to activate their premium account even if it is already activated.

The Puhswoosh support indicates that it usually takes up to a half hour before it kicks in.

It could be great to be able to attach additional informations to the php-pushwoosh responses when an error is encountered and this error is not presice enough.

For example we could do something like that :

if(!$response->isOk()) {

    // Display the HTTP status code
    echo $response->getStatusCode();

    // Standard error message returned by Pushwoosh
    echo $response->getStatusMessage(); 

    // The previous error message gives a clue but its not precise enough
    // So we ask the php-pushwoosh library if it has more indications about our 
    // error
    echo $response->getStatusMessageHelp();
}

The third echo could display something like.

The Pushwoosh servers indicates your Premium account subscription is expired. If you reniewed your subscription please be aware that re-activating the subscription could take several hours.

Implement new requests

Recently Pushwoosh updated its Remote Guide API documentation, version 2.x.x of the library should progressively implement the new requests.

Add Better API Error Handling

Today our premium subscription to pushwoosh ended. When we tried to push a message to the API it returned the following:

array (size=3)
  'status_code' => int 210
  'status_message' => string 'This feature is available for Premium accounts only' (length=51)
  'response' => null

Though, the package didn't return the status message as an error. Instead it returned this:

array_key_exists() expects parameter 2 to be array, null given

// Gomoob/Pushwoosh/Model/Response/CreateMessageResponse.php:43
if (array_key_exists('Messages', $json['response'])) {

Maybe we could implement a way to handle these kinds of status messages? What do you think?

Add utility conditions for language and country tags

As explained in the http://docs.pushwoosh.com/docs/createmessage documentation it is possible to specify Country and Language conditions.

For example.

"conditions": [["Country", "EQ", "BR"],["Language", "EQ", "pt"]]

It would be useful to have 2 new conditions names CountryCondition and LanguageCondition with utility constants for country codes (i.e ISO_3166-2) and language codes (i.e ISO-639-1).

Here is a sample.

CountryCondition::create()->eq(CountryCode::FR);
LanguageCondition::create()->noteq(LanguageCode::GB);

The CountryCondition and LanguageCondition classes are specific StringCondition which do not allow to specify the name of the tag.

Implement powerful DSL for targeted message filters

For now the TargetedMessageRequest allows to set a devicesFilter property as a string only.

It would be great to have a powerful DSL to create the device filters, for example.

$filters = StringTagFilter::create('username')->eq('my_username')->and(IntTagFilter::create('age')->between(15, 50))->join(ApplicationTagFilter::create('XXXXX-XXXXX');

This sample will be equivalent to (T("username", EQ, "my_username"), T("favorite_color", IN, ["red","green","blue"])) + A('XXXXX-XXXXX).

A first implementation has been started on the devices-filter branch.

CreateMessageResponse does not pass along UnknownDevices

Pushwoosh now includes in its raw createMessage response a list of devices/tokens for which it does not know what they are (likely because the user removed the app or the token was renewed.) This is similar to the bulk /getunregistereddevices call, but applies to each message in the moment as you try to send it. See example output $json from CreateMessageResponse::create below:

Array
(
    [status_code] => 200
    [status_message] => OK
    [response] => Array
        (
            [Messages] => Array
                (
                    [0] => CODE_NOT_AVAILABLE
                )

            [UnknownDevices] => Array
                (
                    [] => Array
                        (
                            [0] => 0017a2859e0cc1d37bdfc83cf3e92a8bb47f6405b213516eba76082562d3a646
                        )

                )

        )

)

It would be helpful if CreateMessageResponse could pass these unknown devices back up the chain to userland code to allow me to remove my records of those bad tokens. A method similar to the existing setMessages would be nice, something like setUnknownDevices:

// If 'UnknownDevices' are provided
if (array_key_exists('UnknownDevices', $json['response'])) {
    $createMessageResponseResponse->setUnknownDevices($json['response']['UnknownDevices']);
}

Describe how to use the library without composer

Composer install problems with phpdocumentor

Trying to build version 1.5.3 on Travis it appears that our version of phpdocumentor cannot be installed because of Zend packages and PHP version.

$ composer install
You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Installation request for zendframework/zend-serializer 2.8.0 -> satisfiable by zendframework/zend-serializer[2.8.0].
    - zendframework/zend-serializer 2.8.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.9) does not satisfy that requirement.
  Problem 2
    - zendframework/zend-serializer 2.8.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.9) does not satisfy that requirement.
    - phpdocumentor/phpdocumentor v2.0.1 requires zendframework/zend-serializer 2.* -> satisfiable by zendframework/zend-serializer[2.8.0].
    - Installation request for phpdocumentor/phpdocumentor v2.0.1 -> satisfiable by phpdocumentor/phpdocumentor[v2.0.1].
The command "composer install" failed and exited with 2 during .

As end of life associated to PHP 5.5 is planned for 10 July 2016 (http://php.net/supported-versions.php) version 1.6 of php-pushwoosh should require a minimum version of PHP 5.6.

As a workaround for version 1.5.3 phpdocumentor has been downgraded to version 2.7.0 (see also FIXME comment in Gruntfile).

Add `use XXXX` namespaces to examples and readme

Examples are complicated to follow because no use definitions are documented.

For example first example:

// Create a Pushwoosh client
$pushwoosh = Pushwoosh::create()
    ->setApplication('XXXX-XXX')
    ->setAuth('xxxxxxxx');

// Create a request for the '/createMessage' Web Service
$request = CreateMessageRequest::create()
    ->addNotification(Notification::create()->setContent('Hello Jean !'));

// Call the REST Web Service
$response = $pushwoosh->createMessage($request);

// Check if its ok
if($response->isOk()) {
    print 'Great, my message has been sent !';
} else {
    print 'Oups, the sent failed :-('; 
    print 'Status code : ' . $response->getStatusCode();
    print 'Status message : ' . $response->getStatusMessage();
}

Could be documented as:

use Gomoob\Pushwoosh\Client\Pushwoosh;
use Gomoob\Pushwoosh\Model\Request\CreateMessageRequest;
use Gomoob\Pushwoosh\Model\Notification\Notification;

// Create a Pushwoosh client
$pushwoosh = Pushwoosh::create()
    ->setApplication('XXXX-XXX')
    ->setAuth('xxxxxxxx');

// Create a request for the '/createMessage' Web Service
$request = CreateMessageRequest::create()
    ->addNotification(Notification::create()->setContent('Hello Jean !'));

// Call the REST Web Service
$response = $pushwoosh->createMessage($request);

// Check if its ok
if($response->isOk()) {
    print 'Great, my message has been sent !';
} else {
    print 'Oups, the sent failed :-('; 
    print 'Status code : ' . $response->getStatusCode();
    print 'Status message : ' . $response->getStatusMessage();
}

Thanks :)

Internal Server Error When calling the sample code

When using the sample code with my api key and application code set I receive an internal server error. The library has been added by composer and when using the update command it says it has been generated. I tried putting the code in a page controller instead of the api and still no luck or reason why. If you could help me with this I would greatly appreciate it. I apologize and thank you for your time.

code

Create a Guzzle HTTP client

Today Guzzle is used in many Web Services PHP libraries, it would be great to allow the library to use Guzzle instead of the CURL HTTP client.

Allow CURL to have SSL certificates verification enabled

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.