posting multi-part form data with php curl - php

(multipart/Form data)
Files - array
Answer - string
$postData = array();
$postData["Answer"] = $text;
foreach ($images as $index => $file) {
$postData['Files[' . $index . ']'] = curl_file_create(
$file,
$functions->mime_type($file),
pathinfo($file, PATHINFO_FILENAME)
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('merchantId:98765431'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch ,CURLOPT_URL ,"https://...");
$response = curl_exec($ch);
Trying to post a multi form data. Request fails and prints an error "post field "Answer" is invalid". Can you help?

Good answer
For posting multipart with curl you need to use header like this
$headers = array("Content-Type:multipart/form-data");
if (isset($_POST['btnUpload'])){
$url = "URL_PATH of upload.php"; // e.g. request URL http://localhost/myuploader/upload.php
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != ''){
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "#$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch)) {
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
} else {
$errmsg = curl_error($ch);
}
curl_close($ch);
} else {
$errmsg = "Please select the file";
}
}
For your case just add "Content-Type:multipart/form-data" to your function
$postData = array();
$postData["Answer"] = $text;
foreach ($images as $index => $file) {
$postData['Files[' . $index . ']'] = curl_file_create(
$file,
$functions->mime_type($file),
pathinfo($file, PATHINFO_FILENAME)
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data",'merchantId:98765431')); //HERE THE ADD
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch ,CURLOPT_URL ,"https://...");
$response = curl_exec($ch);

Related

Php curl Jira issue creation not working with custom field

All , I am using PHP to create jira issues , below code is working fine , only issue if I sends custom fields value it sending error. please let me know if I am doing it in wrong way.
function createJiraServiceDeskRequestWithAttachment($serviceDeskId,$requestTypeId,$summary,$description = '', array $files = [],
$url,$user, $token, $primaryCustomerRepId=10202, $isAttachmentPublic = true
): array {
$returnValue = ['ticket' => [], 'temporaryAttachmentIds' => [], 'attachments' => [], 'error' => null];
// make sure to remove additional forward slashes /
$url = rtrim($url, '/');
$endPoint = $url . '/rest/servicedeskapi/request';
$data = [
"serviceDeskId" => $serviceDeskId,
"requestTypeId" => $requestTypeId,
"requestFieldValues" => [
"summary" => $summary,
"description" => $description,
// "customfield_10100" => $primaryCustomerRepId
],
];
try {
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$jsonData = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$issueResult = curl_exec($ch);
$issueResult = json_decode($issueResult, true);
if (curl_errno($ch) || empty($issueResult))
return $returnValue;
curl_close($ch);
$returnValue['ticket'] = $issueResult;
// here add temporary attachment
if (! empty ($files)):
$uploadedAttachments = [];
$endPoint = $url . "/rest/servicedeskapi/servicedesk/{$serviceDeskId}/attachTemporaryFile";
foreach ($files as $index => $file) {
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => curl_file_create(
realpath($file),
mime_content_type($file),
basename($file)
)]);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data', 'X-Atlassian-Token: no-check']);
$tmpResult = curl_exec($ch);
if (! curl_errno($ch) && ! empty($tmpResult = json_decode($tmpResult, true))) {
if (isset($tmpResult['temporaryAttachments']) && isset($tmpResult['temporaryAttachments'][0]['temporaryAttachmentId']))
$uploadedAttachments[] = $tmpResult['temporaryAttachments'][0]['temporaryAttachmentId'];
}
curl_close($ch);
}
else:
return $returnValue;
endif;
// check if there are temporary attachments uploaded, then link them with the request
if (! empty($uploadedAttachments)):
$returnValue['temporaryAttachmentIds'] = $uploadedAttachments;
$endPoint = $url . "/rest/servicedeskapi/request/{$issueResult['issueId']}/attachment";
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$jsonData = json_encode(["temporaryAttachmentIds" => $uploadedAttachments, 'public' => $isAttachmentPublic]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$attachresult = curl_exec($ch);
$attachresult = json_decode($attachresult, true);
if (! curl_errno($ch) && ! empty($attachresult))
$returnValue['attachments'] = $attachresult;
curl_close($ch);
return $returnValue;
else:
return $returnValue;
endif;
} catch (\Exception $e) {
$returnValue['error'] = $e->getMessage();
return $returnValue;
}
}
If I uncomment this code customfield_10100, it doesn't work
I also tried to place it outside of requested values array
"fields" =>[
"customfield_10100" => $primaryCustomerRepId
]

Adding Product with Variant & Image Shopify API PHP

What is wrong with my array? Im trying to add product on shopify using the API. But it does not add the Price and Image of the product.
Here's the example array:
Array
(
[product] => Array
(
[title] => TITLE
[body_html] => <p><strong>DESCRIPTION</strong></p>
[vendor] => TESTSTORE
[product_type] =>
[tags] =>
[published] => 1
[variants] => Array
(
[0] => Array
(
[price] => 1160
)
)
[images] => Array
(
[0] => Array
(
[src] => urlofimage.jpg
)
[1] => Array
(
[src] => urlofimage.jpg
)
)
)
)
And here'is the code that i call to add it on shopify:
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
The array above is the value of $query variable. What do you think is the problem?
I am checking the same all thing are fine
Please check your token and endpoints
Please update your image url like : https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?201809210816
you can try my code it might be help you
<?php
$params = [];
$params['product'] = [
'title'=>'TITLEcus',
'body_html'=>'<p><strong>DESCRIPTION</strong></p>',
'vendor'=>'TESTSTORE',
'product_type'=>'',
'tags' =>'' ,
'published'=>1,
'variants'=> [
[
'price'=>1160
]
],
'images'=> [
[
'src'=>'urlofimage.jpg',
],
[
'src'=>'urlofimage.jpg',
]
]
];
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
$url = "https://" . $shop . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'ohShopify-php-api-client');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Setup headers
$request_headers[] = "";
$query = in_array($method, array('POST','PUT')) ? json_encode($query) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
var_dump(shopify_call($token, $shop, '/admin/api/2019-07/products.json', $params, 'POST', $request_headers = array()));
?>

CLIO return just on matter number by display number

Clio seems to have no solution but to ask it here.
So here I go.
I have the display number and I want to query the Matter ID.
This does not seem to be possible unless I do I x-bulk query the loop throw the results.
Does anyone have a simple query to do this?
here is what I have for PHP so far.
function matter_one ( $token,$refresh_toke ) {
$header = 'Authorization: bearer '.$token."\r\n";
//echo $header."\r\n";
$offset = 0;
$url = 'https://app.clio.com/api/v4/matters.json?&fields=id,description,display_number';
//echo $url."\r\n";
$ch = curl_init();
//curl_setopt($ch, CURLOPT_VERBOSE, true); //used for trouble shooting.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
print "curl response is:" . $resp;
die();
There is a better way, use
https://app.clio.com/api/v4/matters?fields=id,display_number&query=100140
you will need to loop and check the display number does actualy match as 100140 and 100140B and 10014000 would be returned also.
If the issue is you do not want to do the x-bulk here is code that will pull all the info, you can either modify the code to find the item in the data returned for each page or find in the final array.
function performListRequestAllMatters()
{
$header = 'Authorization: bearer ' . $this->token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->base . $this->API_version . 'matters' . '?fields=id,display_number');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if (!$response) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} elseif (200 != curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
echo "Bad Response Code!";
echo "\n";
echo "Response HTTP Status Code : " . curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "\n";
echo "Response HTTP Body : " . $response;
} else {
$json = json_decode($response, true);
$list = $json['data'];
while (isset($json['meta']['paging']['next'])) {
// process a new request until all pages have been retrieved
curl_setopt($ch, CURLOPT_URL, $json['meta']['paging']['next']);
$response = curl_exec($ch);
$json = json_decode($response, true);
$newList = $json['data'];
$list = array_merge($list, $newList);
}
}
curl_close($ch);
return $list;
}
if have 10,000 plus records you have to use bulk.
this function works great at getting all the records.
Then you can find what ever number you need.
function matter_ID_display ( $token,$refresh_toke ) {
// this returns all the matter ID and display name
//adding X-BULK
$header = 'Authorization: bearer '.$token."\r\n"."X-BULK: true";
//echo $header."\r\n";
$offset = 0;
$url = 'https://app.clio.com/api/v4/matters.json?offset='.$offset.'&fields=id,display_number';
$cookie_jar = 'C:\Sites\Project for simmons and flecter\PHP\tmp\cookies.txt';
$cookie_jar2 = 'C:\Sites\Project for simmons and flecter\PHP\tmp\cookies2.txt';
//echo $url."\r\n";
$ch = curl_init();
//curl_setopt($ch, CURLOPT_VERBOSE, true); //used for trouble shooting.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
//print "curl response is:" . $resp;
if( !$resp ) {
die('Error: "' . curl_error( $ch ) . '" - Code: ' . curl_errno( $ch ) );
}
else if ( 200 != curl_getinfo( $ch, CURLINFO_HTTP_CODE ) ) {
echo "Expected code 202";
echo "\n";
echo "Response HTTP Status Code : " . curl_getinfo( $ch, CURLINFO_HTTP_CODE );
echo "\n";
//echo "Response HTTP Body : " . $resp;
}
//$resp = json_encode($resp);
$headers = get_headers_from_curl_response($resp);
//$headers = json_encode($headers);
//print_r ($headers);
$url = $headers["Location"];
echo "url for getting the bulk data\r\n";
echo $url."\r\n";
echo "\n";
curl_close($ch);
//sleep for x seconds
//have to sleep due to processing at clio
$seconds = 20;
echo "Sleeping for ".$seconds." seconds\r\n";
sleep($seconds);
echo "\n";
// seperate curl_
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_COOKIEJAR => $cookie_jar2,
CURLOPT_COOKIEFILE=> $cookie_jar2,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array("authorization: Bearer ".$token),
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_RETURNTRANSFER => true, // return web page
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo 'Curled first time';
echo "\n";
// have to curl two times one without authorization
echo "\n";
Echo "cURL repeat";
echo "\n";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_COOKIEJAR => $cookie_jar2,
CURLOPT_COOKIEFILE=> $cookie_jar2,
CURLOPT_CUSTOMREQUEST => "GET",
//CURLOPT_HTTPHEADER => array("authorization: Bearer ".$token),
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_RETURNTRANSFER => true, // return web page
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else
{echo 'Good Reponse from Curl second time';
echo "\n";}
}
$response_Decode = json_decode($response);
//print_r ($response_Decode);
// got the data. Now just need to turn to a clean array and save to file.
//die('Before Array clean up');
//clean and make into an array
$response_Decode=$response_Decode->data;
$response_Decode=$response_Decode[0];
//print_r ($response_Decode);
//die(); //For testing
$matter_array = array();
if(!empty($response_Decode->data) && is_array($response_Decode->data)) {
foreach ($response_Decode->data as $info) {
$d = array();
$d[] = $info->display_number;
$d[] = $info->id;
$matter_array[] = $d;
}
}
print_r($matter_array); //For testing
die(); //For testing
//matter_array is a full array of all matter ID and Matter Display numbers
return $matter_array; }

Quickblox: User Image or Avatar is Uploaded succesfully via API but not previewing in quickblox admin panel?

Quickblox admin panel in content section images status is Uploaded but nethier image is previewing nor the AWS(amazons3) link is working.
Step 1- Created session using quickblox account(main account) and get session token from response.
Step 2- Log in API user using user credentials and session token.
Step 3- Created a blob and and from response extracted all the blob info param and made a json array.
Step 4- Uploaded user image / avatar and getting response
HTTP/1.1 100 Continue
HTTP/1.1 201 Created
x-amz-id-2: CaF37TJwdt0PZjGdquV4yQSeNqtDyWrZge1DfkBinhNdhHYb635nsWcECFhUoRgiYzuAAxf+z2Q=
x-amz-request-id: F24A002779D03E34
Date: Tue, 21 Mar 2017 13:15:17 GMT
ETag: "3b45dadd80ddb4019e129e1c8469ca40"
Location: http://qbprod.s3.amazonaws.com/2e5b9610a6ff4a8395ade21377def2f500
Content-Type: application/xml
Content-Length: 269
Server: AmazonS3
Step 5- Declared File uploaded.
Step 6- Connected blob id to API user.
Here is my all code, tell me what i am doing wrong:
note: login credentials are not real.
<?php
$quickblox_user_name = "quickblox_agicent"; //quickblox account
$quickblox_password = "quickblox#123";
$user_login = "quickblox_qb_130"; //API
$user_pwd = "21663496";
$profile_pic = "c.png"; // image path
$file_size = filesize($profile_pic);
//CREATE SESSION
$session = createSession($quickblox_user_name,$quickblox_password);
$token = $session->token;
//LOGIN USER
$login_user = loginUser($user_login,$user_pwd,$token);
$login_user_decode = json_decode($login_user);
$log_in = $login_user_decode->user;
$user_id = $log_in->id;
//CREATE A BLOB
$create_blob = createBlob($profile_pic, $token);
$res = json_decode($create_blob)->blob;
$blob_id = $res->id;
$name = $res->name;
$size = $res->size;
$res_en = json_encode($res->blob_object_access);
$rr = json_decode($res_en);
$get_params = $rr->params;
//EXTRACTING BLOB PARAMETER FROM QUERY STRING
$Query_String = explode("&", explode("?", $get_params)[1] );
$content_type = urldecode(substr($Query_String[0], strpos($Query_String[0], "=") + 1));
$expires = urldecode(substr($Query_String[1], strpos($Query_String[1], "=") + 1));
$acl = substr($Query_String[2], strpos($Query_String[2], "=") + 1);
$key = substr($Query_String[3], strpos($Query_String[3], "=") + 1);
$policy = substr($Query_String[4], strpos($Query_String[4], "=") + 1);
$success_action_status = substr($Query_String[5], strpos($Query_String[5], "=") + 1);
$x_amz_algorithm = substr($Query_String[6], strpos($Query_String[6], "=") + 1);
$x_amz_credential = urldecode(substr($Query_String[7], strpos($Query_String[7], "=") + 1));
$x_amz_date = substr($Query_String[8], strpos($Query_String[8], "=") + 1);
$x_amz_signature = substr($Query_String[9], strpos($Query_String[9], "=") + 1);
//CREATE JSON ARRAY OF EXTRATED PARAMETER
$fields = array
(
"Content-Type" => $content_type,
"Expires" => $expires,
"acl" => $acl,
"key" => $key,
"policy" => $policy,
"success_action_status" => $success_action_status,
"x-amz-algorithm" => $x_amz_algorithm,
"x-amz-credential" => $x_amz_credential,
"x-amz-date" => $x_amz_date,
"x-amz-signature" => $x_amz_signature,
"file" => "#".$profile_pic
);
//UPLOAD AVATAR / IMAGE
$upload_avatar = uploadAvatar($fields);
$resPP = json_decode($upload_avatar);
//DECLARE FILE UPLOAD
$declare_upload_avatar = declareUploadAvatar($file_size,$blob_id,$token);
//CONNECT BLOB ID TO API USER
$resultConnect = connectBlobToUser($blob_id,$user_id,$token);
//FUNCTIONS
function createSession($login,$pwd)
{
// Application credentials - change to yours (found in QB Dashboard)
DEFINE('APPLICATION_ID', 12345);
DEFINE('AUTH_KEY', "MDJ8979q328");
DEFINE('AUTH_SECRET', 'asDCE-JLDJCEU');
DEFINE("RESETPWD_BASE_URL", strtolower(stristr($_SERVER["SERVER_PROTOCOL"], "/", true)) . "://" . $_SERVER["HTTP_HOST"] ."/img");
// User credentials
DEFINE('USER_LOGIN', $login);
DEFINE('USER_PASSWORD', $pwd);
// Quickblox endpoints
DEFINE('QB_API_ENDPOINT', "https://api.quickblox.com");
DEFINE('QB_PATH_SESSION', "session.json");
// Generate signature
$nonce = rand();
$timestamp = time();
$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."&timestamp=".$timestamp."&user[login]=".USER_LOGIN."&user[password]=".USER_PASSWORD;
$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);
$post_body = "application_id=" . APPLICATION_ID . "&auth_key=" . AUTH_KEY . "&timestamp=" . $timestamp . "&nonce=" . $nonce . "&signature=" . $signature . "&user[login]=" . USER_LOGIN . "&user[password]=" . USER_PASSWORD;
// Configure cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_SESSION); // Full path is - https://api.quickblox.com/session.json
curl_setopt($curl, CURLOPT_POST, true); // Use POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_CAINFO,RESETPWD_BASE_URL."/quickblox.com.crt");
// Execute request and read response
$response = curl_exec($curl);
$responseJSON = json_decode($response);
// Check errors
if ($response)
{
$rs = json_decode($response)->session;
return $rs;
} else {
echo "0";
// $error = curl_error($curl). '(' .curl_errno($curl). ')';
// echo $error . "\n";
}
// Close connection
curl_close($curl);
}
function loginUser($login1,$pwd1,$token)
{
$requestCred = '{"login": "'.$login1.'", "password": "'.$pwd1.'"}';
$ch = curl_init('http://api.quickblox.com/login.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestCred);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.1',
'QB-Token: ' . $token
));
$res = curl_exec($ch);
curl_close( $ch );
return $res;
}
function createBlob($profile_pic,$token)
{
$ext = pathinfo($profile_pic, PATHINFO_EXTENSION);
if($ext == 'png' || $ext == "Png" || $ext == "PNG")
$request = '{"blob": {"content_type": "image/png", "name": "'.$profile_pic.'", "public": "true"}}';
else
$request = '{"blob": {"content_type": "image/jpeg", "name": "'.$profile_pic.'"}}';
$ch = curl_init('http://api.quickblox.com/blobs.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.1',
'QB-Token: ' . $token
));
$res = curl_exec($ch);
curl_close( $ch );
return $res;
}
function uploadAvatar($fields)
{
$ch = curl_init('http://qbprod.s3.amazonaws.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );
$res = curl_exec($ch);
curl_close( $ch );
return $res;
}
function declareUploadAvatar($file_size,$blob_id,$token)
{
$request_size = '{"blob": {"size": '.$file_size.'}}';
$ch = curl_init("http://api.quickblox.com/blobs/".$blob_id."/complete.json/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_size );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.1',
'QB-Token: ' . $token
));
$res = curl_exec($ch);
curl_close( $ch );
return $res;
}
function connectBlobToUser($blob_id,$user_id,$token)
{
$update_user = '{"user": {"blob_id": '.$blob_id.'}}';
$ch = curl_init("http://api.quickblox.com/users/$user_id.json/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $update_user );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.1',
'QB-Token: ' . $token
));
$res = curl_exec($ch);
curl_close( $ch );
return $res;
}
?>
Before curl request you should create new CURLFile object
and use it in $fields array.
$file_ext = mime_content_type($profile_pic);
$file_path = realpath($profile_pic);
$curl_file = new CURLFile($file_path, $file_ext, $profile_pic);
$fields = array
(
"Content-Type" => $content_type,
"Expires" => $expires,
"acl" => $acl,
"key" => $key,
"policy" => $policy,
"success_action_status" => $success_action_status,
"x-amz-algorithm" => $x_amz_algorithm,
"x-amz-credential" => $x_amz_credential,
"x-amz-date" => $x_amz_date,
"x-amz-signature" => $x_amz_signature,
"file" => $curl_file
);
You can read about CURLOPT_POSTFIELDS here: http://php.net/manual/en/class.curlfile.php

CoinBase "invalid signature" PHP Buy API Request

I have looked over the code many times but whenever I send request to API it returns "message":"invalid signature"
I am thinking it has to do with hashing the body, possibly. I'm new to PHP and its my first project. :)
Anyone see an error? Thanks.
<?php
$arr = array('size' => ".01", 'price' => '240', 'side' => 'sell',
'product_id' => 'BTC-USD');
$output = json_encode($arr);
echo json_encode($arr)."<br/>";
$key = "f23612b06cb4d020cda7e04b1ae6ef9a";
$secret = "RENqodtuTCn4v7g7Pn/FFdQAIKReVXGayNPrNN/Zb7AjATI0hP4R0MCDD5RqnDu60qTZ5Qry329fFu7kcObGBw==";
$passphrase = "tradebot";
$time = time();
$url = "https://api.gdax.com/orders";
$data = $time."POST"."/orders";
echo $data . "<br/>";
$hashinput = "$output"."$data";
$sign = base64_encode(hash_hmac("sha256", $hashinput, base64_decode($secret), true));
echo $sign . "<br/>";
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
var_dump($headers);
echo $url;
static $ch = null;
if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'local server');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $output);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
echo $res;
}
replace
$hashinput = "$output"."$data";
with
$hashinput = "$data"."$output";
and replace
curl_setopt($ch, CURLOPT_POST, $output);
with
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
(from Coinbase Community forum)

Categories