PHP curl file transfer - php

we're using GLPI API we need to create a ticket linked with documents .
The only curl part that i can't translate it's the document's upload .
With Curl (working) :
curl -i -X POST "http://glpitest/glpi/apirest.php/Document" -H "Content-Type: multipart/form-data" -H "Session-Token:sessiontoken"-H "App-Token:apptoken" -F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json" -F "filename[0]=#test.txt" "http://glpitest/glpi/apirest.php/Document"
But i can't translate this is in PHP CURL i tried something like this :
$headers = array(
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
'Http_Accept: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
echo $url = $_SESSION['api_url'] . "/Document";
$cfile = new CURLFile('testpj.txt', 'text/plain', 'test_name');
//$manifest = 'uploadManifest={"input": {"name": "test", "_filename" : "testpj.txt"}};type=application/json filename[0]=#'+$cfile;
$post = ["{\"input\": {\"name\": \"test\", \"_filename\" : \"testpj.txt\"}};type=application/json}", #"C:\\xampp\htdocs\glpi"];
print_r($post);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
the example in the api:
$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: 83af7e620c83a50a18d3eac2f6ed05a3ca0bea62" \
-H "App-Token: f7g3csp8mgatg5ebc5elnazakw20i9fyev1qopya7" \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \
-F 'filename[0]=#file.txt' \
'http://path/to/glpi/apirest.php/Document/'
< 201 OK
< Location: http://path/to/glpi/api/Document/1
< {"id": 1, "message": "Document move succeeded.", "upload_result": {...}}
update : I tried #hanshenrik but i have an error .
["ERROR_JSON_PAYLOAD_INVALID","JSON payload seems not valid"]
in the api.class.php :
if (strpos($content_type, "application/json") !== false) {
if ($body_params = json_decode($body)) {
foreach ($body_params as $param_name => $param_value) {
$parameters[$param_name] = $param_value;
}
} else if (strlen($body) > 0) {
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
$this->format = "json";
} else if (strpos($content_type, "multipart/form-data") !== false) {
if (count($_FILES) <= 0) {
// likely uploaded files is too big so $_REQUEST will be empty also.
// see http://us.php.net/manual/en/ini.core.php#ini.post-max-size
$this->returnError("The file seems too big!".print_r($_FILES), 400,
"ERROR_UPLOAD_FILE_TOO_BIG_POST_MAX_SIZE", false);
}
// with this content_type, php://input is empty... (see http://php.net/manual/en/wrappers.php.php)
if (!$uploadManifest = json_decode(stripcslashes($_REQUEST['uploadManifest']))) {
//print_r($_FILES);
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
I have no uploadManifest in $_REQUEST and if i put the the filename[0]file i have the curl error 26 (can't read file) .
Thank you

translating
-F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json"
is tricky because php doesn't really have native support for adding Content-Type headers (or any headers really) to members of a multipart request, with the only *exception* (known to me) being CURLFile's "Content-Type" and Content-Disposition's "filename" header... with that in mind, you can work around this by putting your data in a file and creating a CURLFile() around that dummy file, but it's.. tricky and stupid-looking (because PHP's curl api wrappers lacks proper support for it)
with the CURLFile workaround, it would look something like:
<?php
declare(strict_types = 1);
$ch = curl_init();
$stupid_workaround_file1h = tmpfile();
$stupid_workaround_file1f = stream_get_meta_data($stupid_workaround_file1h)['uri'];
fwrite($stupid_workaround_file1h, json_encode(array(
'input' => array(
'name' => 'Uploaded document',
'_filename' => 'test.txt'
)
)));
curl_setopt_array($ch, array(
CURLOPT_URL => "http://glpitest/glpi/apirest.php/Document",
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Session-Token:sessiontoken",
"App-Token:apptoken"
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => new CURLFile($stupid_workaround_file1f, 'application/json', ' '), // https://bugs.php.net/bug.php?id=79004
'filename[0]' => new CURLFile('test.txt', 'text/plain')
)
));
curl_exec($ch);
curl_close($ch);
fclose($stupid_workaround_file1h);

Thanks for the Help .
$document can be a $_FILES['whatever'] post .
Works on GLPI api .
<?php
declare (strict_types = 1);
session_start();
$document = array('name' => 'document', 'path' => 'C:\xampp\htdocs\glpi\document.pdf', 'type' => 'txt', 'name_ext' => 'document.pdf');
$url = $_SESSION['api_url'] . "/Document";
$uploadManifest = json_encode(array(
'input' => array(
'name' => $document['name'],
'_filename' => $document['name_ext'],
),
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => $uploadManifest,
'filename[0]' => new CURLFile($document['path'], $document['type'], $document['name_ext']),
),
));
print_r($_REQUEST);
echo $result = curl_exec($ch);
echo "erreur n° " . curl_errno($ch);
$header_info = curl_getinfo($ch, CURLINFO_HEADER_OUT) . "/";
print_r($header_info);
if ($result === false) {
$result = curl_error($ch);
echo stripslashes($result);
}
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
)
))
)
);

Pass Params in Curl Request

I have try curl request with terminal it's working but when i convert that curl request into php code that one passing param not working.
Terminal curl request :
curl --insecure "https://www.zohoapis.in/phonebridge/v3/clicktodial" -X POST -d "clicktodialuri=$clicktodialurl&clicktodialparam=[{'name':'fromnumber','value':'555'}]&zohouser=123456" -H "Authorization: Zoho-oauthtoken 1000.aedb399e2389cfacef60f965af052cbf" -H "Content-Type: application/x-www-form-urlencoded"
Response :
{"message":"ASTPP Clicktodial functionality has been enabled","status":"success","code":"SUCCESS"}
PHP Code :
$zohouser = '6000';
$access_token = '1000.c3c1107b635f1f5b257d831677e077d2';
$cURL = "https://www.zohoapis.in/phonebridge/v3/clicktodial?clicktodialuri=$click_to_dial&clicktodialparam=[{'name':'fromnumber','value':'555'}]&zohouser=$zohouser";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $cURL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Authorization: Zoho-oauthtoken " . $access_token,
"Content-Type: application/x-www-form-urlencoded",
"cache-control: no-cache"
),
));
$response = json_decode(curl_exec($curl));
$err = curl_error($curl);
print_r($err);
curl_close($curl);
print_r($response);exit;
Not getting any response or error during run this php curl request.
Can you please help me how to pass string as param in php curl request.
$strURL= "https://www.zohoapis.in/phonebridge/v3/clicktodial";
$arrHeader= array(
'Authorization:Zoho-oauthtoken 1000.aedb399e2389cfacef60f965af052cbf'
);
$params= array(
"clicktodialparam"=>"[{\"name\":\"fromnumber\",\"value\":\"555\"}]",
"authorizationparam"=>"{\"name\":\"X-Auth-Token\",\"value\":\"1000.aedb399e2389cfacef60f965af052cbf\"}",
"clicktodialuri" => "$click_to_dial",
"zohouser" => "123456"
);
$ch= curl_init();
curl_setopt_array($ch,array(
CURLOPT_URL =>$strURL,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $arrHeader,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_TIMEOUT => 0,
CURLOPT_POSTFIELDS => http_build_query($params)
));
$strResponse= curl_exec($ch);
print_r($strResponse);
echo curl_error($ch);
Referring to this post and using the linked tool we end up with the following code. Since I cannot test this myself I cannot guarantee my answer. It looks like you might be missing the curl post option "curl_setopt($ch, CURLOPT_POST, 1);" which you can use in lieu of the option you used "CURLOPT_CUSTOMREQUEST => "POST"".
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.zohoapis.in/phonebridge/v3/clicktodial');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "clicktodialuri=$clicktodialurl&clicktodialparam=[{'name':'fromnumber','value':'555'}]&zohouser=123456");
$headers = array();
$headers[] = 'Authorization: Zoho-oauthtoken 1000.aedb399e2389cfacef60f965af052cbf';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);

Consuming a Jira REST API

I would like to consume a Jira REST API, but have been unsuccessful.
The Jira site gives the following request URL:
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json" http://localhost:8090/rest/api/2/issue/
And this is the json array, which is located on a file called collector.json:
"fields": [
{
"project":
{
"key": "ATL"
},
"summary": "REST ye merry TEST.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Task"
}
}
]
}
The following is the code:
<?php
include_once "collector.php";
$jiraValues = jsonArray("collector.json");
$jira_url = "http://jira.howareyou.org:8091/rest/api/2/issue/createmeta";
$jiraString = json_encode($jiraValues);
$request = curl_init($jira_url); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($request, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($request, CURLOPT_ENCODING, "");
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $jiraString); // use HTTP POST to send form data
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
curl_setopt($request, CURLOPT_URL, $jira_url);
$json_raw = curl_exec($request); // execute curl post and store results in $json_raw
curl_close($request); // close curl object
// This line takes the response and breaks it into an array using the specified delimiting character
$jira_response = json_decode($json_raw, TRUE);
print_r($jira_response);
When I run it, Nothing happens. I get no feedback.
I found it here, and replaced the information with my valid information.
Firstly define some helpful globals to help :
define('JIRA_URL', 'http://jira.howareyou.org:8091');
define('USERNAME', '');
define('PASSWORD', '');
Then we need to define a post method :
function post_issue($data) {
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_URL => JIRA_URL . '/rest/api/2/issue/createmeta' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
Then how we want to use it is like so :
Create a new issue
$new_issue = array(
'fields' => array(
'project' => array('key' => 'TIS'),
'summary' => 'Test via REST',
'description' => 'Description of issue goes here.',
'priority' => array('name' => 'Blocker'),
'issuetype' => array('name' => 'Task'),
'labels' => array('a','b')
)
);
Call our previously made function passing in the new issue :
$result = post_issue($new_issue);
if (property_exists($result, 'errors')) {
echo "Error(s) creating issue:\n";
var_dump($result);
} else {
echo "New issue created at " . JIRA_URL ."/browse/{$result->key}\n";
}
A basic example of posting a new issue via REST
Note: The Jira API URL may need to be configured slightly

cURL request Spotify API Unexpected status: 415

Here is my script for an auth request to Spotify but it returns an error. I tried changing the Content-Type, but that doesn't seem to cut it. Here is my code:
$spot_api_client = 'client';
$spot_api_secret = 'secret';
$spot_api_redirect = 'myurl';
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "https://accounts.spotify.com/api/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'redirect_uri' => urlencode($spot_api_redirect),
),
CURLOPT_HTTPHEADER => array(
'Accept' => '*/*',
'User-Agent' => 'runscope/0.1',
'Authorization' => 'Basic '. base64_encode($spot_api_client.':'.$spot_api_secret),
'Content-Type'=>'application/json'
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
}
Well, seems I found the answer based on this question :
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$spot_api_redirect = 'myurl';
$credentials = "client:secret";
$headers = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: runscope/0.1",
"Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=authorization_code&code='.$_GET['code'].'&redirect_uri='.urlencode($spot_api_redirect);
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
unset($_COOKIE['stateKey']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($response);
}
Just in case of node.js / request use, point out "WTF" tag :)
request(
{
method : "POST",
url : "https://accounts.spotify.com/api/token",
json : true,
headers :
{
"Content-Type" : "application/x-www-form-urlencoded", // WTF!
"Authorization" : "Basic " + new Buffer(client_id+":"+client_secret).toString('base64')
},
body : "grant_type=client_credentials"
},
function (err, response, body)
{
if (err)
{
cb(err);
}
else
{
if (body.hasOwnProperty("access_token"))
{
access_token = body.access_token;
cb(null);
}
else
{
cb(body);
}
}
}
);

POST request with JSON body

I would like to add a post to a Blogger blog via PHP.
Google provided the example below. How to use that with PHP?
You can add a post for a blog by sending a POST request to the post
collection URI with a post JSON body:
POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json
{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
You need to use the cURL library to send this request.
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Close the cURL handler
curl_close($ch);
// Print the date from the response
echo $responseData['published'];
If, for some reason, you can't/don't want to use cURL, you can do this:
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => "Authorization: {$authToken}\r\n".
"Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...
I made API sending data via form on website to prosperworks based on #Rocket Hazmat, #dbau and #maraca code.
I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

Categories