sendpulse / sendpulse-rest-api-php Goto Github PK
View Code? Open in Web Editor NEWA simple SendPulse REST client library and example for PHP.
License: Apache License 2.0
A simple SendPulse REST client library and example for PHP.
License: Apache License 2.0
Можете ли вы при вызове http_build_query явно указывать в качестве разделителя '&'?
Було б чудово додати можливість конфіжити тамаути запиту - зараз у вашому клієнті юзається курл який наглухо зашитий в середині. Через це приходиться просто копіювати весь клас і додати лише дві опції, навіть наслідування не допоможе.
ІМХО курл викинути взагалі і юзати prs interface клієнту ну або хоча б Guzzle.
sendpulse-rest-api-php/src/ApiClient.php
Line 185 in 11473bb
Если случается повторная отправка через smtp, то в случае успеха handleResult отдаст пустой stdClass, который опять попадет в handleResult из-за рекурсивного вызова в smtpSendMail и соответственно второй handleResult будет жаловаться на Undefined property: stdClass::$http_code
The issue is that ID and Secret are correct.
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 );
}
you forgot to provide in parameters array 'country' => 'off'
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));
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);
}
Пробовал кто-то подключить это без Сomposer?
Такое ощущение, что тогда все связи рушатся.
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.
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.
Пытаюсь добавить 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);
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
i am getting that error and its thrown on this line
$SPApiClient = new ApiClient(API_USER_ID, API_SECRET, new FileStorage());
response
"error_code": 800
"message": "Unauthorized action."
"is_error": true
"http_code": 403
but other methods is ok.
Although the API supports creating mailing list, the PHP wrapper class does not support creating new mailing list.
Am I missing something?
В аннотации метода getBookInfo
указан stdClass
как возвращаемое значение, однако возвращается array<stdClass>
с единственным элементом, возможно следует изменить поведение API или обработать эту ситуацию на стороне клиента?
Добрый день. Не могу добавить телефон в адресную книгу.
$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), работает.
Добрый день! При отправке события через метод startEventAutomation360() с variables имеющими вложенные массивы (тип поля "структура" в панели управления) возникает ошибка "Array to string conversion" в строке
sendpulse-rest-api-php/src/ApiClient.php
Line 120 in ed3105e
Если отправить тот же массив методом 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
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.
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
Согласно документации (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 = '' )
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);
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
)
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', при этом ни ID, ни SECRET не виноваты. А виноват curl, который не в состоянии верифицировать сертификат. Чтобы обойти эту неприятность можно использовать опцию
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
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" }
Ребята, а давайте начнем версионировать изменения нарушающие обратную совместимость.
Это не первый раз, у нас прод падает 😢
composer.json "php": ">=5.4.0"
you do not have a method implemented: https://sendpulse.com/integrations/api/bulk-email - for this endpoint: https://api.sendpulse.com/addressbooks/{id}/emails/unsubscribe
Trying to send mail, passing template (not html or text), but got error:
$ApiClient->smtpSendMail([
'to' => '[email protected]',
'template' => [
'id' => 12345
]
]);
Error: http://skrinshoter.ru/s/111219/P24PvvVG
If i pass template
key, html/text not need.
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
}
}
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));`
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
}
I have some generated files after api call with names like '17le7mrzIYBP9nlpZFzsPKlvETlX0IdtFBt2FgsD'. How can I get rid of them?
Uncaught Error: Class 'Sendpulse\RestApi\ApiClientException' not found in
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.
https://packagist.org/search/?q=sendpulse
No packages found :(
Почему бы не сделать простенький composer.json чтобы можно было устанавливать по "модному"? :)
ЗЫ. А вообще, спасибо! Не часто увидишь такую доступность по API, а где то даже примеров не выпросишь, а только махровые совковые инструкции. Молодцы!
Тогда уж к
// 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. Простите за назойливость.
Делаю плагин для 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 );
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);
}
I would like to have a differnet reply address, like:
$email = array(
'html' => $htmlContent,
'text' => $htmlContent,
'subject' => 'Subject',
'from' => array(
'name' => 'Name',
'email' => '[email protected]',
),
'reply_to' => array(
'name' => 'Name',
'email' => '[email protected]',
),
'to' => array(
array(
'email' => '[email protected]',
),
),
);
В этом месте:
)
);
var_dump($SPApiClient
Одна скобка лишняя?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.