N
N
number12017-05-12 19:47:48
PHP
number1, 2017-05-12 19:47:48

Why is push mailing not created on sendpulse api?

https://sendpulse.com/en/integrations/api
I am a beginner and therefore I can be very wrong.
There is a push.php file. It has a class taken from github. There is a push_int.php file. In this file, the interface from which the class is implemented.
I created a timer.php file that creates a class object and calls the createPushTask function. I put timer.php on cron.
There is also token.txt in which, as I understand it, the token is written, since I wrote in the class itself that the token will be written to the file.

the code

push_int.php
<?php
    /*
     * Interface for SendPulse REST API
     *
     * Documentation
     * https://login.sendpulse.com/manual/rest-api/
     * https://sendpulse.com/api
     *
     */
    interface SendpulseApi_Interface {
        
        public function pushListCampaigns( $limit = NULL, $offset = NULL );
        /**
         * Get list of websites
         *
         * @param null $limit
         * @param null $offset
         */
        public function pushListWebsites( $limit = NULL, $offset = NULL );
        /**
         * Get amount of websites
         */
        public function pushCountWebsites();
        /**
         * Get list of all variables for the website
         *
         * @param $websiteId
         */
        public function pushListWebsiteVariables( $websiteId );
        /**
         * Get list of all subscriptions for the website
         *
         * @param $websiteId
         */
        public function pushListWebsiteSubscriptions( $websiteId, $limit = NULL, $offset = NULL );
        /**
         * Get amount of subscriptions for the site
         *
         * @param $websiteId
         */
        public function pushCountWebsiteSubscriptions( $websiteId );
        /**
         * Set state for subscription
         *
         * @param $subscriptionId
         * @param $stateValue
         */
        public function pushSetSubscriptionState( $subscriptionId, $stateValue );
        /**
         * Create new push campaign
         *
         * @param $taskInfo
         * @param array $additionalParams
         */
        public function createPushTask( $taskInfo, $additionalParams = array() );
    }

push.php
<?php
/*
 * SendPulse REST API PHP Class
 *
 * Documentation
 * https://login.sendpulse.com/manual/rest-api/
 * https://sendpulse.com/api
 *
 */
 include 'push_int.php';
 
class SendpulseApi implements SendpulseApi_Interface {
    private $apiUrl = 'https://api.sendpulse.com';
    private $userId = 'тут юзерид';
    private $secret = 'тут секрет';
    private $token = NULL;
    private $refreshToken = 0;
    /*
     *  Define where script will save access token
     *  Types: session, file, memcache
     */
    private $storageType = 'file';
    private $apiFilesPath = 'token.txt';
    
    
    
    
    
    
    
    /**
     * Sendpulse API constructor
     *
     * @param $userId
     * @param $secret
     * @param string $storageType
     *        Define where script will save access token
     *        Types: session, file, memcache
     * @throws Exception
     */
    public function __construct( $userId, $secret, $storageType = 'file' ) {
        if( empty( $userId ) || empty( $secret ) ) {
            throw new Exception( 'Empty ID or SECRET' );
        }
        $this->userId = $userId;
        $this->secret = $secret;
        $this->storageType = $storageType;
        $hashName = md5( $userId . '::' . $secret );
        switch ($this->storageType) {
            case 'session':
                if (isset($_SESSION[$hashName]) && !empty($_SESSION[$hashName])) {
                    $this->token = $_SESSION[$hashName];
                }
                break;
            case 'memcache':
                $memcache = new Memcache();
                $memcache->connect('localhost', 11211) or die('Could not connect to Memcache');
                $token = $memcache->get($hashName);
                if (!empty($token)) {
                    $this->token = $token;
                }
                break;
            default:
                $filePath = $this->apiFilesPath.$hashName;
                if (file_exists($filePath)) {
                    $this->token = file_get_contents($filePath);
                }
        }
        if( empty( $this->token ) ) {
            if( !$this->getToken() ) {
                throw new Exception( 'Could not connect to api, check your ID and SECRET' );
            }
        }
    }
    
    
    
    
    
    
    /**
     * Get token and store it
     *
     * @return bool
     */
    private function getToken() {
        $data = array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $this->userId,
            'client_secret' => $this->secret,
        );
        $requestResult = $this->sendRequest( 'oauth/access_token', 'POST', $data, false );
        if( $requestResult->http_code != 200 ) {
            return false;
        }
        $this->refreshToken = 0;
        $this->token = $requestResult->data->access_token;
        $hashName = md5( $this->userId . '::' . $this->secret );
        switch ($this->storageType) {
            case 'session':
                $_SESSION[$hashName] = $this->token;
                break;
            case 'memcache':
                $memcache = new Memcache();
                $memcache->connect('localhost', 11211) or die('Could not connect to Memcache');
                $memcache->set($hashName, $this->token, false, 3600);
                break;
            default:
                $tokenFile = fopen($this->apiFilesPath.$hashName, "w");
                fwrite($tokenFile, $this->token);
                fclose($tokenFile);
        }
        return true;
    }
    
    
    
    
    
    
    
    /**
     * Form and send request to API service
     *
     * @param $path
     * @param string $method
     * @param array $data
     * @param bool $useToken
     * @return array|NULL
     */
    private function sendRequest( $path, $method = 'GET', $data = array(), $useToken = true ) {
        $url = $this->apiUrl . '/' . $path;
        $method = strtoupper( $method );
        $curl = curl_init();
        if( $useToken && !empty( $this->token ) ) {
            $headers = array( 'Authorization: Bearer ' . $this->token );
            curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
        }
        switch( $method ) {
            case 'POST':
                curl_setopt( $curl, CURLOPT_POST, count( $data ) );
                curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $data ) );
                break;
            case 'PUT':
                curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, "PUT" );
                curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $data ) );
                break;
            case 'DELETE':
                curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'DELETE' );
                curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $data ) );
                break;
            default:
                if( !empty( $data ) ) {
                    $url .= '?' . http_build_query( $data );
                }
        }
        curl_setopt( $curl, CURLOPT_URL, $url );
        curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $curl, CURLOPT_HEADER, 1 );
        $response = curl_exec( $curl );
        $header_size = curl_getinfo( $curl, CURLINFO_HEADER_SIZE );
        $headerCode = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
        $responseBody = substr( $response, $header_size );
        curl_close( $curl );
        if( $headerCode == 401 && $this->refreshToken == 0 ) {
            $this->refreshToken += 1;
            $this->getToken();
            $return = $this->sendRequest( $path, $method, $data );
        } else {
            $return = new stdClass();
            $return->data = json_decode( $responseBody );
            $return->http_code = $headerCode;
        }
        return $return;
    }
    
    
    
    
    
    
    /**
     * Process results
     *
     * @param $data
     * @return mixed
     */
    private function handleResult( $data ) {
        if( empty( $data->data ) ) {
            $data->data = new stdClass();
        }
        if( $data->http_code != 200 ) {
            $data->data->is_error = true;
            $data->data->http_code = $data->http_code;
        }
        return $data->data;
    }
    
    
    
    
    
    
    /**
     * Process errors
     *
     * @param null $customMessage
     * @return stdClass
     */
    private function handleError( $customMessage = NULL ) {
        $message = new stdClass();
        $message->is_error = true;
        if( !is_null( $customMessage ) ) {
            $message->message = $customMessage;
        }
        return $message;
    }
    
    
    
    
    
    
    
    public function createPushTask( $taskInfo, $additionalParams = array() ) {
        $data = $taskInfo;
        if (!isset($data['ttl'])) {
            $data['ttl'] = 0;
        }
        if( empty($data['title']) || empty($data['website_id']) || empty($data['body']) ) {
            return $this->handleError( 'Not all data' );
        }
        if ($additionalParams) {
            foreach($additionalParams as $key=>$val) {
                $data[$key] = $val;
            }
        }
        $requestResult = $this->sendRequest( '/push/tasks', 'POST', $data );
        return $this->handleResult( $requestResult );
    }
}

timer.php
<?php
include 'push.php';
$push = array(
    "title" => "dfgfhfhf",
    "website_id" => "41081",
    "body" => "gfhtghgh",
    "ttl" => "200",
);

$p = array(
    "link" => "https://toster.ru/"
);

$object = new SendpulseApi;
$object->createPushTask($push, $p);

?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shimdim, 2017-05-12
@number1

Leave the lib you took from the github as is - you don't need to edit anything there.
And here in the timer.php file:

<?php
require_once('./sendpulse-rest-api-php/api/sendpulseInterface.php');
require_once('./sendpulse-rest-api-php/api/sendpulse.php');

define('API_USER_ID', 'ТУТ_ВАШ_ID'); // https://login.sendpulse.com/settings/#api
define('API_SECRET', 'ВАШ_SECRET'); // там же

$SPApiProxy = new SendpulseApi( API_USER_ID, API_SECRET, 'file' );

// дальше ваш код
$push = array(
    "title" => "dfgfhfhf",
    "website_id" => "41081",
    "body" => "gfhtghgh",
    "ttl" => "200",
    "stretch_time" => 1
);

$p = array(
    "link" => "https://toster.ru/"
);

$SPApiProxy->createPushTask($push, $p);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question