A
A
Anton2019-02-07 17:43:33
PHP
Anton, 2019-02-07 17:43:33

How to properly compose a CURL POST request?

This code should add a new contact to the sendpulse address book

// $tokenset - ранее полученный токен
$emails = array(
    array(
        'email' => '[email protected]',
        'variables' => array(
            'phone' => '+12345678900',
            'name' => 'User Name',
        )
    )
);
$headers = array('Authorization: Bearer ' . $tokenset);
if( $curl = curl_init() ) {
    curl_setopt($curl, CURLOPT_URL, 'https://api.sendpulse.com/addressbooks/22608888/emails');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $emails);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $out = curl_exec($curl);
    echo $out;
    curl_close($curl);
  }

In response I get:
{"error_code":303,"message":"No emails"}
What am I doing wrong, I don’t understand?
From the docks:
Добавление email адресов в книгу

Нужно сделать POST запрос в виде ссылки

https://api.sendpulse.com/addressbooks/{id}/emails
Параметры запроса:

id	идентификатор книги
emails	сериализованный массив контактов (пример ["[email protected]", "[email protected]"])

если же нужно передать не только емейл, но и переменные, то используется следующая структура передачи значений:
email	 емейл адрес подписчика
variables (необязательный параметр)	
сериализованный массив переменных ("имя переменной":"значение переменной").
Для добавления номера телефона необходимо использовать системную переменную "Phone". 
Пример структуры массива email адресов
[
  {
    "email": "[email protected]",
    "variables": {
      "Имя": "Елизавета",
      "Phone": "380632727700"
    }
  },
  {
    "email": "[email protected]",
    "variables": {
      "имя переменной": "значение",
      "имя переменной": "значение"
    }
  }
]
В случае успеха вернет JSON строку с result = true

I suspect that I am making a mistake in the correct spelling in this part:
$emails = array(
    array(
        'email' => '[email protected]',
        'variables' => array(
            'phone' => '+12345678900',
            'name' => 'User Name',
        )
    )
);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valentin, 2019-02-07
@romanko_vn

I think there's something wrong here
Maybe you need to specify Content-Type also, for example application/json

A
Andrey, 2019-02-12
@Allepta

It seems to me that POSTFIELDS does not accept an array in the format in which you pass it.

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // требуется с PHP 5.6.0
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

Pay attention to the line in the example:
And to your code:
$emails = array(
    array(
        'email' => '[email protected]',
        'variables' => array(
            'phone' => '+12345678900',
            'name' => 'User Name',
        )
    )
);

I'll leave a link, just in case

S
seopublic, 2020-05-11
@seopublic

you can try this code, it works:

require '../../vendor/autoload.php';

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

   define( 'API_USER_ID', $_GET['client-id'] );
   define( 'API_SECRET', $_GET['secret-id'] );
   define( 'TOKEN_STORAGE', 'file' );

   $SPApiProxy = new ApiClient( API_USER_ID, API_SECRET, new FileStorage() );

$emails = array(
            array(
              'email' => $_GET['email'],
              'variables' => array(
                  'Phone' => $_GET['phone'],
                  'Name' => $_GET['name'],
                )
                ),
             );
$bookID = $_GET['bookID'];
$result = $SPApiProxy->addEmails($bookID,$emails);
$json_result = json_encode($result);
$json_beautified = str_replace(array("{", "}", ","), array("{<br />&nbsp;&nbsp;&nbsp;&nbsp;", "<br />}", ",<br />&nbsp;&nbsp;&nbsp;&nbsp;"), $json_result);
print_r($json_beautified);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question