Giter Site home page Giter Site logo

sendpulse-rest-api-php's People

Contributors

bilovol avatar dshemendiuk avatar emirii avatar erickthered avatar foolsoft avatar keanor avatar mdzhym avatar mekras avatar paulkolbovich avatar qzmenko avatar sendpulse avatar usemint avatar warlock-9000 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

sendpulse-rest-api-php's Issues

Added connection timeout settings

Було б чудово додати можливість конфіжити тамаути запиту - зараз у вашому клієнті юзається курл який наглухо зашитий в середині. Через це приходиться просто копіювати весь клас і додати лише дві опції, навіть наслідування не допоможе.
ІМХО курл викинути взагалі і юзати prs interface клієнту ну або хоча б Guzzle.

Undefined property: stdClass::$http_code

if ($data->http_code !== 200) {

Если случается повторная отправка через smtp, то в случае успеха handleResult отдаст пустой stdClass, который опять попадет в handleResult из-за рекурсивного вызова в smtpSendMail и соответственно второй handleResult будет жаловаться на Undefined property: stdClass::$http_code

function to add

hello
I think you can add this function to your class ;)

    /**
     * Get stats of push campaigns
     *
     * @param null $limit
     * @param null $offset
     * @return mixed
     */
  
    
    public function statListCampaigns( $campainId ) {
        $requestResult = $this->sendRequest( 'push/tasks/'.$campainId, 'GET' );

        return $this->handleResult( $requestResult );
    }

yahoo inbox issue

i tried this for yahoo , but email no receive in inbox . always in spam folder , is there any special setting for yahoo .

> /*
>  * Example: Send mail using SMTP
>  */
> $email = array(
>     'html' => '<p>Hello!</p>',
>     'text' => 'Hello!',
>     'subject' => 'Mail subject',
>     'from' => array(
>         'name' => 'John',
>         'email' => '[email protected]',
>     ),
>     'to' => array(
>         array(
>             'name' => 'Subscriber Name',
>             'email' => '[email protected]',
>         ),
>     ),
>     'bcc' => array(
>         array(
>             'name' => 'Manager',
>             'email' => '[email protected]',
>         ),
>     ),
>     'attachments' => array(
>         'file.txt' => file_get_contents(PATH_TO_ATTACH_FILE),
>     ),
> );
> var_dump($SPApiClient->smtpSendMail($email));

Add listTemplates function

A listTemplates function

     /**
     * Get list of templates
     *
     * @param null $owner
     *
     * @return mixed
     */
    public function listTemplates($owner = null)
    {
        $data = array();
        if (!empty($owner)) {
            $data['owner'] = $owner;
        }
        $requestResult = $this->sendRequest('templates','GET',$data);
        return $this->handleResult($requestResult);
    }

Could not connect to api, check your ID and SECRET

use Sendpulse\RestApi\ApiClient;
use Sendpulse\RestApi\Storage\FileStorage;

class test {
    public static function index()
    {
        define('PATH_TO_ATTACH_FILE', __FILE__);
        $SPApiClient = new ApiClient(config::app('sendpulse_api_user_id'), config::app('sendpulse_api_secret'), new FileStorage());
    }
}

i get error: Could not connect to api, check your ID and SECRET
sendpulse_api_user_id and sendpulse_api_secret i get on https://login.sendpulse.com/settings/#api.

Client authentication failed since few months

Authorization always return response

{
    "error": "invalid_client",
    "error_description": "Client authentication failed.",
    "message": "Client authentication failed.",
    "error_code": 1
}

I dont know wtf, but cause of this problems is Content-Type: application/x-www-form-urlencoded header.

You have to replace line 120 from

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

to

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

in src/ApiClient.php file.

Read official CURL documentation (https://www.php.net/manual/ru/function.curl-setopt.php) for more information about content typing.

{"is_error":true,"http_code":500}

Пытаюсь добавить email через апи, всё вроде верно сделал, но вижу ответ

{"is_error":true,"http_code":500}

Нашел коды ошибок в документации, там нет 500, только 400 и 502, между ними ничего нет.
Плиз хелп ми.

вот код:
$sp = new SendpulseApi($config->id, $config->secret, 'file');
$bookid = '917511';
$email = '[email protected]';
$name = 'Test Test';
$emails = array(
'email' => $email,
'status' => "0",
'variables' => array(
'имя' => $name
)
);
$result = $sp->addEmails($bookid,$emails);

API urls need to be updated

Old URL:

`public function getCampaignInfo($id)
{
if (empty($id)) {
return $this->handleError('Empty campaign id');
}

    $requestResult = $this->sendRequest('campaigns/' . $id);

    return $this->handleResult($requestResult);
}

`

Latest Works:

`public function getCampaignInfo($id)
{
if (empty($id)) {
return $this->handleError('Empty campaign id');
}

    $requestResult = $this->sendRequest('push/tasks/' . $id);

    return $this->handleResult($requestResult);
}

`
See - https://sendpulse.com/integrations/api/web-push#statistics

smtpSendMail code 800

response

"error_code": 800
"message": "Unauthorized action."
"is_error": true
"http_code": 403

but other methods is ok.

Creating New Mailing List

Although the API supports creating mailing list, the PHP wrapper class does not support creating new mailing list.

Am I missing something?

Method getBookInfo has wrong type hint

В аннотации метода getBookInfo указан stdClass как возвращаемое значение, однако возвращается array<stdClass> с единственным элементом, возможно следует изменить поведение API или обработать эту ситуацию на стороне клиента?

addPhonesWithVariables возвращает ошибку 500

Добрый день. Не могу добавить телефон в адресную книгу.

$phone_var=[ "12345678901"=>[ [ "name" =>"test1", "type" =>"date", "value"=>"2018-10-10", ] ] ]; $response=$SPApiClient->addPhonesWithVariables($addressbook, $phone_var);

получаю вот такой ответ:

stdClass Object ( [is_error] => 1 [http_code] => 500 [headers] => HTTP/1.1 500 Internal Server Error Server: nginx/1.14.0 (Ubuntu) Date: Fri, 08 Jan 2021 09:21:54 GMT Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive X-Powered-By: PHP/7.1.33 Cache-Control: no-cache, private x-sp-pr: lpr7 [curlErrors] => [ip] => 168.119.2.85 [method] => POST:https://api.sendpulse.com//sms/numbers/variables [timestamp] => 2021-01-08 02:21:55+05:00 )

Обычное добавление телефона, без переменных (addPhones), работает.

Ошибка при отправке массива в методе sendRequest

Добрый день! При отправке события через метод startEventAutomation360() с variables имеющими вложенные массивы (тип поля "структура" в панели управления) возникает ошибка "Array to string conversion" в строке

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
Эта ошибка скорее всего связанна с параметрами не позволяющими отправить вложенный массив при помощи curl.

Если отправить тот же массив методом POST в формате json по адресу эвента то никаких проблем нет.

Пример массива:

[ 'email' => '', 'phone' => '', 'full_name' => '', 'sales' => [ [ 'image' => '', 'period' => '', 'title' => '', 'link' => '' ], [ 'image' => '', 'period' => '', 'title' => '', 'link' => '' ], [ 'image' => '', 'period' => '', 'title' => '', 'link' => '' ], [ 'image' => '', 'period' => '', 'title' => '', 'link' => '' ] ] ]

PHP version: 7.3.9

Unsubsribe method

Added to class ApiClient
/**
* unsubscribed emails from list
*
* @param $bookID
* @param $emails
*
* @return stdClass
*/
public function unsubscribedFromList($bookID, $emails)
{
if (empty($emails)) {
return $this->handleError('Empty emails');
}
if (empty($bookID)) {
return $this->handleError('Empty bookList');
}

    $data = array(
        'emails' => serialize($emails),
    );

    $requestResult = $this->sendRequest('addressbooks/' . $bookID . '/emails/unsubscribe', 'POST', $data);

    return $this->handleResult($requestResult);

}

Now can unsibscribe emails from some list.

Содержимое сообщения

При отправке viber письма через api
Содежимое письма:
Любите котов? - Вам к нам 🙂 !
Сообщение приходит без смайла

message2

Есть ли возможность отправлять смайлы в сообщении?

Work with DTO/VO istead of stdClass

I would like to see major release that will work with DTO/VO istead of stdClass.

Currently I'm just guessing what kind of property will I get. I would like to see strictness

Нет поддержки параметра send_date в методе createCampaign

Согласно документации (https://sendpulse.com/integrations/api/bulk-email#create-campaign) при создании кампании есть возможность устанавливать дату отправки. В данный момент данного параметра в библиотеке нет

/**
* Create new campaign
*
* @param $senderName
* @param $senderEmail
* @param $subject
* @param $body
* @param $bookId
* @param string $name
* @param string $attachments
* @param string $type
* @return mixed
*/
public function createCampaign( $senderName, $senderEmail, $subject, $body, $bookId, $name = '', $attachments = '', $type = '' )

Add CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT

Maybe add curl options for preventing site error if API down.

curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_HEADER, 1 );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt( $curl, CURLOPT_TIMEOUT, 10);

Error is not thrown when API request body is wrong

Whenever you pass data that is not formed according do spec, sendpulse class fails silently. This need to be thrown out

stdClass Object
(
    [message] => Badly formed data. Check API documentation
    [error_code] => 21356
    [is_error] => 1
    [http_code] => 422
    [headers] => HTTP/2 422
server: nginx/1.14.0 (Ubuntu)
date: Tue, 22 Jun 2021 10:58:55 GMT
content-type: application/json
x-powered-by: PHP/7.1.33
cache-control: no-cache
x-sp-pr: lpr7


    [curlErrors] =>
    [ip] => 168.119.2.85
    [method] => POST:https://api.sendpulse.com/addressbooks/******/emails
    [timestamp] => 2021-06-22 01:58:46+03:00
)

Send SMS

Hi, thank for the work
How can i send sms to any mobile from this api

Исключение 'Could not connect to api, check your ID and SECRET', вызванное устаревшими сертификатами на сервере

На хостингах, где давно ничего не обновлялось, при использовании этой библиотеки может вылезти исключение 'Could not connect to api, check your ID and SECRET', при этом ни ID, ни SECRET не виноваты. А виноват curl, который не в состоянии верифицировать сертификат. Чтобы обойти эту неприятность можно использовать опцию

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

Create push error: Not all data

When I try to run the example to create a new push I get this error message:

object(stdClass)#3 (2) { ["is_error"]=> bool(true) ["message"]=> string(12) "Not all data" }

Braking changes

Ребята, а давайте начнем версионировать изменения нарушающие обратную совместимость.
Это не первый раз, у нас прод падает 😢

Не получилось найти метод для получения "Детальной информации по балансу"

https://api.sendpulse.com/user/balance/detail

{
    "balance": {
        "main": "9.36",
        "bonus": "5.00",
        "currency": "USD"
    },
    "email": {
        "tariff_name": "Пакет 10 000 писем",
        "finished_time": "2019-04-25 08:03:02",
        "emails_left": 9914,
        "maximum_subscribers": 10000,
        "current_subscribers": 0
    },
    "smtp": {
        "tariff_name": "SMTP Free",
        "end_date": "2018-11-21 15:05:39",
        "auto_renew": 1
    },
    "push": {
        "tariff_name": "White Label",
        "end_date": "2018-11-30",
        "auto_renew": 1
    }
}

Nothing happens when i create a new push campaign from API

I tried to use web push notification from sendpulse rest API, the response

{"result":true,"id":20663}

but nothing happens after this, so i just tried manually create web push from website and it's working properly.

`
$sendpulse = $this->get('sendpulse');

    $task = array(
            'title'      => 'Hello!',
            'body'       => 'This is my first push message',
            'website_id' => 5081,
            'ttl'        => 20,
            'stretch_time' => 10
    );

    $additionalParams = [];

    return new JsonResponse($sendpulse->createPushTask($task, $additionalParams));`

push demo test file

hello.
I've modified the push test file to test some functions ..
may be you can add this one in your package to help new testers to understand ;)



<?php

    /*
     * SendPulse REST API Usage Example
     *
     * Documentation
     * https://login.sendpulse.com/manual/rest-api/
     * https://sendpulse.com/api
     */

    require_once( 'api/sendpulseInterface.php' );
    require_once( 'api/sendpulse.php' );

    // https://login.sendpulse.com/settings/#api
    //compte [email protected]
    define( 'API_USER_ID', '' );
    define( 'API_SECRET', '' );

    define( 'TOKEN_STORAGE', 'file' );
    
    error_reporting(E_ALL);
ini_set('display_errors', 1);

    $SPApiProxy = new SendpulseApi( API_USER_ID, API_SECRET, TOKEN_STORAGE );

//    // Get Mailing Lists list example
//    var_dump( $SPApiProxy->listAddressBooks() );
//
//    // Send mail using SMTP
//    $email = array(
//        'html' => '<p>Hello!</p>',
//        'text' => 'text',
//        'subject' => 'Mail subject',
//        'from' => array(
//            'name' => 'John',
//            'email' => '[email protected]'
//        ),
//        'to' => array(
//            array(
//                'name' => 'Client',
//                'email' => '[email protected]'
//            )
//        ),
//        'bcc' => array(
//            array(
//                'name' => 'Manager',
//                'email' => '[email protected]'
//            )
//        ),
//        'attachments' => array(
//            'file.txt' => file_get_contents(PATH_TO_ATTACH_FILE)
//        )
//    );
//    var_dump($SPApiProxy->smtpSendMail($email));


    /*
     * Example: create new push
     */
    
    //liste de mes sites

    $sites = $SPApiProxy->pushListWebsites() ;
    
    echo '<pre>';
    
        echo '<h2>sites</h2>';
    var_dump($sites);
//    var_dump($_SERVER);
    
    foreach($sites as $s) {
        if ($s->url == $_SERVER['HTTP_HOST']) {
            $idSite = $s->id; //to send push with the current declared site
        }
        var_dump($s);
    }
    
    //nb de suscribers
    //
    //
        echo '<h2>nb suscribers</h2>';
    $nbsuscribers = $SPApiProxy->pushCountWebsiteSubscriptions($idSite);
    
     var_dump($nbsuscribers);
     
     
     
    //détail suscribers
    //    echo '<h2>suscribers</h2>';
//     $suscribers = $SPApiProxy->pushListWebsiteSubscriptions($idSite);
//      var_dump($suscribers);
     
 
    
    
    //liste des campagnes
    
    echo '<h1>Campaigns</h1>';
    $campagnes = $SPApiProxy->pushListCampaigns($idSite);
    
//     var_dump($campagnes);
     
    //stats des campagnes
     foreach  ($campagnes as $c) {
          echo '<h2>STATS '.$c->title.'</h2>';
        $stats = $SPApiProxy->statListCampaigns($c->id);
        var_dump($stats);
     }
     
     
     
     
     
     
     
     
     
         //----- ENVOI PUSH MSG
     


      if (trim(@$_POST['message']) != '' ) {
    $task = array(
        'title'      => $_POST['title'],
        'body'       => $_POST['message'],
        'website_id' => $idSite,
        'ttl'        => 220, //temps d'affichage du message à l'écran
        'stretch_time' => 1 //areter l'envoi après XX secondes si tte les notifications ne sont pas parties
    );
    

//    // This is optional
//    $additionalParams = array(
//        'link' => 'http://labo-altilab.com',
//        'filter_browsers' => 'Chrome,Safari',
//        'filter_lang' => 'en',
//        'filter' => '{"variable_name":"some","operator":"or","conditions":[{"condition":"likewith","value":"a"},{"condition":"notequal","value":"b"}]}'
//    );
    
//    var_dump($SPApiProxy->createPushTask($task, $additionalParams));
  
//    //envoi à tout le mode
    $reponse = $SPApiProxy->createPushTask($task);
    var_dump($reponse);
    if (isset($reponse->is_error) and ($reponse->is_error == true or $reponse->is_error=='true') ){
        echo 'ERREUR : '.$reponse->message.' <a href="./">Autre envoi</a>';
 
    } else {
                echo 'push message ok <a href="./">Autre envoi</a>';
    }
    } else {
        
             ?> 
<form method="post">
    title<br />
    <input type="text" name="title" required/><br />
    message<br />
    <textarea name="message" required></textarea>
    <input type="submit" value="envoyer" />
</form>
  <?php
    }
    

generated files in root folder

I have some generated files after api call with names like '17le7mrzIYBP9nlpZFzsPKlvETlX0IdtFBt2FgsD'. How can I get rid of them?

Code got stuck on 401. Token update failed.

sendpulse/rest-api/src/ApiClient.php:153
getToken() was called, but the response is timeout:
var_export($retval);

(object) array(
'is_error' => true,
'http_code' => 0,
)

and then any request gives 'http_code' => 401. Had to reset the program.

composer?

https://packagist.org/search/?q=sendpulse
No packages found :(
Почему бы не сделать простенький composer.json чтобы можно было устанавливать по "модному"? :)

ЗЫ. А вообще, спасибо! Не часто увидишь такую доступность по API, а где то даже примеров не выпросишь, а только махровые совковые инструкции. Молодцы!

Работа без Сomposer

Тогда уж к
// Without Composer:
// require("your-path/sendpulse-rest-api-php/src/ApiInterface.php");
// require("your-path/sendpulse-rest-api-php/src/ApiClient.php");

в редми добавить

// require("your-path/sendpulse-rest-api-php/src/Storage/FileStorage.php");
// require("your-path/sendpulse-rest-api-php/src/Storage/TokenStorageInterface.php");
// require("your-path/sendpulse-rest-api-php/src/Storage/SessionStorage.php");
// require("your-path/sendpulse-rest-api-php/src/Storage/MemcachedStorage.php");
// require("your-path/sendpulse-rest-api-php/src/Storage/MemcacheStorage.php");

P.S. Простите за назойливость.

Не отправляется ссылка через API

Делаю плагин для WordPress и столкнулся с такой проблемой, что при создании рассылки из вашей панели все прекрасно работает, а как только я начинаю пушить из скрипта, то перестает передаваться ссылка, что я делаю не так?

function wpsp_publish_post( $id, $post ) {

    // Пушим только для обычных постов
    if ( 'post' == $post->post_type ) {

        // https://login.sendpulse.com/settings/#api
        $api_user_id = '';
        $api_secret = '';
        $website_id = '';

        $body = ( ! empty( $post->post_excerpt ) )
            ? $post->post_excerpt
            : mb_substr( $post->post_content, 0, 140 );

        // Инициализация API
        $SPApiProxy = new SendpulseApi( $api_user_id, $api_secret );

        // Данные для отправки
        $task = array(
            'title'      => esc_html( $post->post_title ),
            'body'       => esc_html( $body ),
            'website_id' => $website_id,
            'ttl'        => 86400
        );
        // Дополнительные параметры
        $additionalParams = [
            'link' => add_query_arg([
                'utm_source' => 'push' // Добавить UTM-метку к урлу для статистики переходов
            ], get_permalink( $id ) ),
        ];

        $complete = $SPApiProxy->createPushTask( $task, $additionalParams );

        //PC::debug($complete);
        //PC::debug($post);
    }
}
add_action( 'publish_post', 'wpsp_publish_post', 10, 2 );

{"is_error":true,"http_code":0,"headers":""}

Very often a connection error occurs. But the reason for this error simply cannot be found, because you do not return it. Why not just do:

if(curl_errno($ch)){   
   $retval->error = curl_error($ch);
}

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.