Adding Product with Variant & Image Shopify API PHP - 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()));
?>

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
]

PHP POST Data to HTTPS Fail with 404 error! Even with (CURL, fopen and file_get_contents)

All my efforts failed! I can't POST data to HTTPS Even by using CURL, fopen and file_get_contents!
I always getting a 404 error!
However, when I leech the page using GET method it open with no errors!
But when I using POST method for that page with its same URL it always fail with a 404 error!
My PHP code :
<?php
###########################################
function curl_fopen_getContents( $functionName='curl', $method='GET' )
{
$post_data = http_build_query(array( 'a' => '1' ));
$cookies = 'a=1';
$opts = array('http' => array(
'method' => strtoupper($method),
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n"
."Content-Length: " . strlen($post_data)."\r\n"
."Cookie: $cookies\r\n",
'content' => $post_data,
'timeout' => 60
));
$context = stream_context_create($opts);
///////////////////////////////////
// you can decode it
$https_url = 'my_url_here';
if( $functionName=='fopen' )
{
$result = fopen($https_url, 'r', false, $context); #fpassthru($result); #fclose($result);
}
elseif( $functionName=='file_get_contents' )
{
$result = file_get_contents($https_url, false, $context);
}else{
$result = curl_post($https_url, $method, $post_data, $cookies);
}
return $result;
}
###########################################
function curl_post( $https_url, $method='GET', $post_data='', $cookies='' )
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$https_url);
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_HEADER, 1);
if( strtoupper($method) !='GET' )
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
$data = curl_exec($ch); if(!$data){ $data=curl_error($ch); }
curl_close($ch);
return $data;
}
###########################################
/*
curl_fopen_getContents( $functionName, $method );
$functionName = curl/fopen/file_get_contents
$method = GET/POST
*/
echo curl_fopen_getContents( 'curl', 'GET' );
###########################################
?>
Can you help please? Thanks Alot.
The problem was that I forget to pass some cookies..

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

Post JSON encoded and normal string data using CURL in PHP

I typically send an array of strings using CURL in PHP, something like this:
$data = array(
"key1" => $value,
"key2" => $value,
"key3" => $value,
"key4" => $value
);
Then, among other curl_setop settings, post using:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
This all works fine. But now in addition to those strings, I have 1 dataset that is JSON encoded and I want to post it at the same time. JSON looks like this:
Array ( [ad_info] => {"MoPubAdUnitInteractions":"a","MoPubAdUnitConversations":"b","MoPubAdUnitGroups":"c"} )
I think I figured out how to do it by setting a header saying I'm going to be passing in JSON like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
But then, can I simply add another line for the post, but in this case the JSON encoded value like this:
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
I'm kinda shooting in the dark, any suggestions on how I should be thinking about this?
Ok, here is the full example:
From Processing The Form Post:
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
);
$json_data = array("ad_info" => $community_ad_info);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null, $json_data);
And the Function in PHP I'm calling to do the CURL:
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
if ($json_data)
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
Any help is greatly appreciated.
You use wrong approach. Setting CURLOPT_POSTFIELDS option twice doesn't lead to result you expected since each setting call discards effect of previous one.
Instead of this, you have to append extra data ($community_ad_info) to the main POST data ($data) before passing it to CURLOPT_POSTFIELDS option.
...
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
...
This is untested of course but it should do what you need.
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
And now the actualy logic
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
The things to note here are,
the new content tyoe header tells it to be processed as a form post.
removal of the $json_data array, the "ad_info" key is not just added into the $data array
When you process this on the other side you can access the ad_info like this
$ad_info = json_decode($_POST['ad_info']);
You can access the other fields with
$apns_name = $_POST['apns_name'];

Zend Http Client : Invalid URI Supplied Error for Urls that redirect

I want to get html of a URL. Basically I am doing this :
$client = new Zend_Http_Client($url);
$client->setConfig(array('strictredirects' => true, 'timeout'=> 100, 'storeresponse' => true));
$response = $client->request();
$html = $response->getBody();
For some urls that redirect, i am getting the following error
Invalid URI supplied
For example if you consider the following URL:
http://www.hiexpress.com/redirect?path=hd&brandCode=ex&hotelCode=housl&regionCode=1&localeCode=en&cm_mmc=mdpr--GoogleMaps--ex-_-housl
It redirects to another URL. When i try to get the lastResponse, it gives me nothing. HOw do i get the html for this URL??
I tried the config option strictredirects but still its giving the same error. HOw do i solve this??
Try this put this into your controller
// #$uri your url
$client = new Zend_Http_Client($uri, array(
'maxredirects' => 2,
'timeout' => 10,
));
// Try to mimic the requesting user's UA
$client->setHeaders(array(
'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
'X-Powered-By' => 'Zend Framework'
));
$response = $client->request();
$body = $response->getBody();
$body = trim($body);
// Get DOM
if( class_exists('DOMDocument') ) {
$dom = new Zend_Dom_Query($body);
} else {
$dom = null; // Maybe add b/c later
}
$title = null;
if( $dom ) {
$titleList = $dom->query('title');
if( count($titleList) > 0 ) {
$title = trim($titleList->current()->textContent);
$title = substr($title, 0, 255);
}
}
$this->view->title = $title;//Title of the page
$description = null;
if( $dom ) {
$descriptionList = $dom->queryXpath("//meta[#name='description']");
// Why are they using caps? -_-
if( count($descriptionList) == 0 ) {
$descriptionList = $dom->queryXpath("//meta[#name='Description']");
}
if( count($descriptionList) > 0 ) {
$description = trim($descriptionList->current()->getAttribute('content'));
$description = substr($description, 0, 255);
}
}
$this->view->description = $description;// Description of the page
For some reason Zend Http Client did not work, had to use CURL to get the work done.
To get HTML :
$headers = array( "User-Agent:MyAgent/1.0\r\n");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 50);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$html = curl_exec($curl);
curl_close($curl);
echo $html;
To get the Effective Url / redirected url :
$headers = array( "User-Agent:MyAgent/1.0\r\n");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 50);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$content = curl_exec($curl);
$redirectedUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
echo $redirectedUrl;

Categories