Convert Terminal cURL Call to PHP cURL Request - php

I am trying to send a cURL request from PHP to ExpressPigeon.com RESTFUL API.
The documentation says that this is how to create contact in a list using cURL command:
curl -X POST -H "X-auth-key: 00000000-0000-0000-0000-000000000000" \
-H "Content-type: application/json" \
-d '{"list_id": 11,
"contacts": [
{"email": "john#doe.net",
"first_name":"John",
"last_name": "Doe"
},
{"email": "jane#doe.net",
"first_name":"Jane",
"last_name": "Doe"
}] }' \
https://api.expresspigeon.com/contacts
Here's what I did:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.expresspigeon.com/contacts');
$fields = array(
'list_id' => $this->list_code,
'contacts' => array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name'])
);
$this->http_build_query_for_curl($fields); //This generates the $this->post_data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $this->post_data);
$headers = array(
'X-auth-key: '.$this->api_key,
'Content-type: application/json',
'Content-Length: '.strlen(serialize($post))
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$res = (array) json_decode(curl_exec($ch));
curl_close($ch);
print_r($res);
function http_build_query_for_curl( $arrays, $prefix = null )
{
if ( is_object( $arrays ) ) {
$arrays = get_object_vars( $arrays );
}
foreach ( $arrays AS $key => $value ) {
$k = isset( $prefix ) ? $prefix . '['.$key.']' : $key;
if ( is_array( $value ) OR is_object( $value ) ) {
$this->http_build_query_for_curl( $value, $k );
} else {
$this->post_data[$k] = $value;
}
}
}
I have this as a result though:
Array
(
[status] => error
[code] => 400
[message] => required Content-type: application/json
)

you need to add one more level of array nesting to achieve the desired JSON output so that contacts is an array instead of an object:
$fields = array(
'list_id' => $this->list_code,
'contacts' => array(array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name']))
);
and then use json_encode on that; you add debug printouts and compare against what you need

Support just replied and this is the working code. I've tried it and it works! The only thing I did not do is the the SSL parameters on cURL. Thanks to Hans Z for his revision on my contacts array.
$fields = array(
'list_id' => $this->list_code,
'contacts' => array(array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name']))
);
$requestBody = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.expresspigeon.com/contacts");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','X-auth-key:'.$this->api_key));
$result = curl_exec($ch);
curl_close($ch);

Related

PHP CURL syntax for WIX

I'm using Wix's API to query products. I've made progress converting their examples to PHP but am stumped with their filtering method. For example, this basic query:
curl -X POST \
'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"includeVariants": true
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'enter code here
works fine when rewritten as:
public function getProducts($code){
$curl_postData = array(
'includeVariants' => 'true'
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
But I'm having trouble filtering to a specific collection. Here's their example:
curl 'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"query": {
"filter": "{\"collections.id\": { \"$hasSome\": [\"32fd0b3a-2d38-2235-7754-78a3f819274a\"]} }"
}
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'
And here's my interpretation of it ($collection is my variable to replace the fixed value in Wix's example):
public function getProducts($code, $collection){
$curl_postData = array(
'filter' => array(
'collections.id' => array(
'$hasSome' => $collection
)
)
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
The response is identical to the first example--I get all the products instead of just one collection. The problem is almost certainly my interpretation of their example. I think it's meant to be a multidimensional array, but I could be reading it wrong. I'd appreciate any suggestions.
In the second code block, the value of the filter property is not an object, but a JSON-encoded object. I'm not sure why the API requires that, but it means you have to use nested json_encode() in PHP.
$curl_postData = array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
);
Thanks, Barmar. Your answer was correct with a minor change. Here's the final code segment that works properly.
$curl_postData = array(
'query' => array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
)
);

Adding OneSignal segments to filters array

I am using following PHP script to send OneSignal push notifications to subscribed devices.
<?PHP
function sendMessage(){
$content = array(
"en" => 'Testing Message desde el backend small icon '
);
$fields = array(
'app_id' => "xxxx",
'filters' => array(array("field" => "tag", "key" => "correo", "relation" => "=", "value" => "xxx")),
'data' => array("foo" => "bar"),
'small_icon' =>"ic_push",
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic xxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
This script is working fine, and the notifications are sent.
Now I need to add more filters, for example I need to add a filter to two other segments that I have created at the OneSignal dashboard.
The segments are "skateboard" and "administrators".
How can I add these two segment to the filters array?
You need to pass segments name array in fields like you are passing tags.
$content = array(
"en" => 'Notification Message Here..'
);
$heading = array(
"en" => 'Heading goes here..'
);
$fields = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXXX',
'contents' => $content,
'headings' => $heading,
'included_segments' => array('SegmentName1','SegmentName2'),
'tags' = array(array("key" => "state", "relation" => "=", "value" => 'Delhi'))
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXXXXXXXXXXXXXX'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;

PHP curl POST for Watson Video Enrichment

Am trying to use PHP 7.2 to submit a new job to the Watson Video Enrichment API.
Here's my code:
//set some vars for all tasks
$apiUrl = 'https://api-dal.watsonmedia.ibm.com/video-enrichment/v2';
$apiKey = 'xxxxxxxx';
//vars for this task
$path = '/jobs';
$name = 'Test1';
$notification_url = 'https://example.com/notification.php';
$url = 'https://example.com/video.mp4';
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => "simple.custom-model",
"upload" => array(
"url" => $url
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $apiUrl.$path );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: APIKey '.$apiKey
));
$result = curl_exec($ch);
echo $result;
But I can't get it to work, even with varying CURLOPTs, like:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
I keep getting the response: Bad Request.
Here's the API docs.
Am I setting up the POST CURL all wrong? Is my $data array wrong? Any idea how to fix this?
Reading their API documentation, it looks like the field preset is not of type string. Rather it has a schema defined here. This appears similar to how you are using the upload schema.
You should change your data array to look like this:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"video_url" => "https://example.com/path/to/your/video"
),
"upload" => array(
"url" => $url
)
);
Ok, I figured it out. Thanks to #TheGentleman for pointing the way.
My data array should look like:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"simple.custom-model" => array(
"video_url" => $url,
"language" => "en-US"
)
),
"upload" => array(
"url" => $url
)
);

Php Variable is null when i pass it to the array

I am trying to send user-specific web notifications with onesignal and i solved everything except this variable null problem.
I use that variable multiple times and there is no problem except these lines:
<?php
if(isset($_POST["sub"]))
{
$my_variable= $_POST["t1"];
$SQL = "some sql here";
if (mysqli_query($db, $SQL)) {
echo $my_variable;
echo "<br>";
function sendMessage(){
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => "$my_variable")),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
The result is :
1 JSON sent: {"app_id":"5b0eacfc-3ac8-4dc6-891b-xxxxx","filters":[{"field":"tag","key":"key","relation":"=","value":"null"}],"data":{"foo":"bar"},"contents":{"en":"test message"}}
I tried so many variations with/without quotas , json_encode() function but couldn't pass that variable to that array.
Your variable is out of scope.
You define $my_variable outside of the function sendMessage(), but proceed to try and use it within the function, without passing it as a parameter.
This can be fixed with the following:
function sendMessage($filterValue)
{
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => $filterValue)),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($my_variable);
$return["allresponses"] = $response;
$return = json_encode( $return);

Google Firebase iOS push works in console but not in API

I'm using https://github.com/arnesson/cordova-plugin-firebase/ to receive Google Firebase messages on a ionic based app.
After set certificates, install plugin and setup Firebase account I was able to receive notifications (on both android and ios devices) sended through the Firebase Console.
But when I send through the Firebase API (https://firebase.google.com/docs/cloud-messaging/http-server-ref) only android devices receive the notification. I'm using the following code:
$data = Array
(
[to] => <token>
[notification] => Array
(
[title] => My Title
[text] => Notification test
[sound] => default
[vibrate] => 1
[badge] => 0
)
)
$jsonData = json_encode($data);
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
$header = array(
'Content-Type: application/json',
"Authorization: key=".$gcmApiKey
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
No errors are returned:
{"multicast_id":904572753471539870406,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1477063422322568734%3d5c78243d5c7824"}]}
What can be wrong?
For iOS, try adding in parameter priority set to high and content_available set to true in your payload.
See the parameter details here.
try this code
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_KEY_HERE",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
also try it in curl terminal
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"body\":\"Yellow\"},\"priority":10}"
a little late but with working example,
I'm using the code below for ios and android push, you are missing the priority and content_available fields
example :
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'notification' => array('body' => $message , "sound" => "default"),
'data' => $message,
"sound"=> "default",
'priority' => "high" ,
'content_available' => false
);
$headers = array(
'Authorization:key = your-key',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);

Categories