Is this code convertible to print it's results to a txt file, instead of to a JSON / curl object? We are trying to debug a specific sku and we want to see the output of the long query which precedes this snippet:
foreach($group_sets AS $group_set) {
$bulk_json .= '{ "index" : { "_id" : "'.$group_set['our_sku'].'" } }'.PHP_EOL;
$bulk_json .= json_encode($group_set).PHP_EOL;
}
foreach($remove_skus AS $sku) {
$bulk_json .= '{ "delete" : { "_id" : "'.$sku.'" } }'.PHP_EOL;
}
print "processing batch, batch count: ".$batch_cnt.PHP_EOL;
send_to_elastic($bulk_json);
$bulk_json = "";
$batch_cnt = 0;
$batch_sku_list = array();
}
}
if(!empty($bulk_json)) {
send_to_elastic($bulk_json);
$bulk_json = "";
}
print PHP_EOL.PHP_EOL."DONE".PHP_EOL.PHP_EOL;
function send_to_elastic($bulk_json) {
$url = "https://ada64ff1913a4b.us-east-1.aws.found.io:9243/us/product/_bulk";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, "MyName:MyPassword");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $bulk_json);
echo "uploading batch to elastic-cloud... ";
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$response = json_decode($json_response, true);
//if ( $status != 201 ) {
// print("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
//}
curl_close($curl);
echo "done".PHP_EOL;
Here is my modified code, it doesnt write to the file though so obviously I have something screwed up...
foreach($group_sets AS $group_set) {
$bulk_json .= '{ "index" : { "_id" : "'.$group_set['my_sku'].'" } }'.PHP_EOL;
$bulk_json .= json_encode($group_set).PHP_EOL;
}
foreach($remove_skus AS $sku) {
$bulk_json .= '{ "delete" : { "_id" : "'.$sku.'" } }'.PHP_EOL;
}
print "processing batch, batch count: ".$batch_cnt.PHP_EOL;
//send_to_elastic($bulk_json);
file_put_contents('searchresults.txt', $bulk_json);
$bulk_json = "";
$batch_cnt = 0;
$batch_sku_list = array();
}
}
if(!empty($bulk_json)) {
//send_to_elastic($bulk_json);
file_put_contents('searchresults.txt', $bulk_json);
$bulk_json = "";
}
print PHP_EOL.PHP_EOL."DONE".PHP_EOL.PHP_EOL;
//function send_to_elastic($bulk_json) {
//$url = "https://ada64ff1913a4b16us-east-1.aws.found.io:9243/qm/product/_bulk";
//$curl = curl_init($url);
//curl_setopt($curl, CURLOPT_HEADER, false);
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_USERPWD, "MyUser:MyPW");
//curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
//curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_POSTFIELDS, $bulk_json);
//echo "uploading batch to elastic-cloud... ";
//$json_response = curl_exec($curl);
//$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//$response = json_decode($json_response, true);
//if ( $status != 201 ) {
// print("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
//}
//curl_close($curl);
echo "done".PHP_EOL;
Use file_put_contents(). Replace the call to send_to_elastic() with:
file_put_contents('filename.txt', $bulk_json);
You should also generate the JSON correctly, something like:
$result = array();
foreach($group_sets AS $group_set) {
$result[] = ["index" => [ "_id" => $group_set['our_sku']]];
$result[] = $group_set;
}
foreach($remove_skus AS $sku) {
$result[] = [ "delete" => [ "_id" => $sku ]];
}
$bulk_json = json_encode($result);
Related
I need to make a graphql query using pure php, is this possible and how to do it?
graphql request:
{
getLastLowestProductPrices(
lastLowestPricesInput: [{date: "2023-01-01", productId: 14397, sizeId: "uniw"}]
) {
id
sizes {
id
price {
gross {
value
currency
}
}
}
}
endpoint: https://trening-dev1.iai-shop.com/graphql/v1/?docLang=pl
Please help me
Edit:
my php code:
function do_post_request($url, $data)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
)
);
return curl_exec($ch);
}
function get($endpoint)
{
$json = '{
getLastLowestProductPrices(
lastLowestPricesInput: [{date: "2023-01-01", productId: 14397, sizeId: "uniw"}]
) {
id
sizes {
id
price {
gross {
value
currency
}
}
}
}';
$result = do_post_request($endpoint, $json);
print_r($result);
}
$endpoint = 'https://trening-dev1.iai-shop.com/graphql/v1/?docLang=pl';
get($endpoint);
While checking the URL: https://i2.wp.com/jarek-kefir.org/wp-content/uploads/2019/04/pożar-katedry-notre-dame.jpg?ssl=1
I have result status code 400...
This is my function:
public function callAPI($url)
{
$curl = curl_init();
error_log('Checking url: ' . $url);
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//'APIKEY: 111111111111111111111',
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// EXECUTE:
$result = utf8_decode(curl_exec($curl));
$result = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result);
if (!$result) {
error_log('Connection Failure ' . $result . ' for url: ' . $url);
}
// Check if any error occurred
$error_msg = '';
$error_number = curl_errno($curl);
$error_info = curl_error($curl);
$info = curl_getinfo($curl);
$httpCode = $info['http_code'];
$request_ok = $httpCode == 200 || $httpCode == 201 || $httpCode == 204;
error_log('$httpCode: ' . $httpCode);
if (!$request_ok) {
$info = curl_error($curl);
$error_msg = $info ? $info : "Http code: " . $httpCode;
error_log('Error while checking url: ' . $url . ' : ' . $error_msg);
}
curl_close($curl);
return $error_msg;
}
but when I check it manually or even by curl from command line it works fine.
Probably I miss some configuration for curl here..
heh finally I found out that it is because one polish character.. :)
I am trying to implement payout request using CURL. But I am getting this error: "name":"REQUIRED_SCOPE_MISSING","message":"Access token does not have required scope.","information_link":"https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"
I have already checked on payouts scope in-app settings on developer dashboard.
Here is code:
$host = 'https://api.sandbox.paypal.com';
$clientId = 'id';
$secret = "secret";
$token = '';
function get_access_token($url, $postdata) {
global $clientId, $clientSecret;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$response = curl_exec( $curl );
if (empty($response)) {
die(curl_error($curl));
curl_close($curl);
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms\n";
curl_close($curl);
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
$jsonResponse = json_decode( $response );
return $jsonResponse->access_token;
}
function make_post_call($url, $postdata) {
global $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$token,
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$response = curl_exec( $curl );
if (empty($response)) {
die(curl_error($curl));
curl_close($curl);
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms\n";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
$jsonResponse = json_decode($response, TRUE);
print_r($jsonResponse); die;
return $jsonResponse;
}
echo "\n";
echo "###########################################\n";
echo "Obtaining OAuth2 Access Token.... \n";
$url = $host.'/v1/oauth2/token';
$postArgs = 'grant_type=client_credentials';
$token = get_access_token($url,$postArgs);
echo "Got OAuth Token: ".$token;
echo "\n \n";
echo "###########################################\n";
echo "Initiating a Payment with PayPal Account... \n";
$url = $host.'/v1/payments/payouts';
$member_email = "test#test.com";
$data = array(
"sender_batch_header" => array(
"sender_batch_id" => '2542'.time(),
'email_subject' => 'Withdraw',
'email_message' => 'You have withdraw from asfd! Thanks for using our service!'
),
"items" => array(
array(
"recipient_type" => 'EMAIL',
'amount' => array(
'value' => 10.99,
'currency' => 'USD',
),
'note' => 'Thank You',
'sender_item_id' => 'A25426',
'receiver' => $member_email,
),
),
);
$data = json_encode($data);
$json_resp = make_post_call($url, $data);
foreach ($json_resp['links'] as $link) {
if($link['rel'] == 'execute'){
$payment_execute_url = $link['href'];
$payment_execute_method = $link['method'];
} else if($link['rel'] == 'approval_url'){
$payment_approval_url = $link['href'];
$payment_approval_method = $link['method'];
}
}
echo "Payment Created successfully: " . $json_resp['id'] ." with state '". $json_resp['state']."'\n\n";
echo "Please goto <a href='".$payment_approval_url."'>link</a> in your browser and approve the payment with a PayPal Account.\n";
Please help
Thank You
I am fetching order details through Flipkar order Api.It is gives first 20(0-20) result at a time and for next records it gives next page url.
For fetching next 20 records(20-40) again we have to call curl with next page url and fetch orders .For this i am using code below:
$listingbulk=array();
$headers = array(
'Cache-Control: no-cache',
'Content-type: application/json',
'Authorization: Bearer '.$fkt
);
$bulkjson= '{
"filter": {
"orderDate": {
"fromDate": "'.$orderfrom.'",
"toDate": "'.$orderto.'"
}
}
}';
$urlbulk = "https://api.flipkart.net/sellers/v2/orders/search";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$urlbulk);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $bulkjson);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$resultbulksku = curl_exec($curl);
$listingbulk[] = json_decode($resultbulksku);
if (curl_errno($curl)) {
echo 'Error:' . curl_error($curl);
}
curl_close ($curl);
$nextPageUrl= $listingbulk[0]->nextPageUrl;
if ($nextPageUrl !=''){
$newpageurl= orderFk($nextPageUrl,$headers);
if ($newpageurl !='') {
$newpageurl2= orderFk($newpageurl,$headers);
if ($newpageurl2 !=''){
$newpageurl3= orderFk($newpageurl2,$headers);
}
}
}
Function is here :
function orderFk($nextPageUrl,$headers){
$fp = fopen('order/order'.$currenttime.'.csv',"a");
$urlbulk1 = "https://api.flipkart.net/sellers/v2/".$nextPageUrl;
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL,$urlbulk1);
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl1, CURLOPT_HTTPHEADER, $headers);
$resultbulksku1 = curl_exec($curl1);
$listingbulk1[] = json_decode($resultbulksku1);
if (curl_errno($curl1)) {
echo 'Error:' . curl_error($curl1);
}
curl_close ($curl1);
$listingbulk=$listingbulk1;
$newnextPageUrl= $listingbulk1[0]->nextPageUrl;
return $listingbulk;
}
I want to crate if else condition dynamically so if "next pageurl" is exist in response it should call again the same function with new url ( without calling function multiple times in if else condition).
If anyone has solution for this please reply.(answer with working example would be more helpful)
I suggest something like this, inside order function use while loop, exit on error or loop exceed the maxpage. In $list u have all responses.
function orderFk($nextPageUrl,$headers){
$page = 1;
$maxpage = 100;
$exit = 0;
$list = array();
while(strlen($nextPageUrl)){
$urlbulk = "https://api.flipkart.net/sellers/v2/".$nextPageUrl;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$urlbulk);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$resultbulk = curl_exec($curl);
$nextPageUrl = '';
if(curl_errno($curl)) {
$exit = 1;
}
curl_close($curl); // close before exit while loop
if($exit==1 || $page>$maxpage){
break;
}
$listingbulk = json_decode($resultbulk);
if(strlen($listingbulk[0]->nextPageUrl)>0){
$nextPageUrl = $listingbulk[0]->nextPageUrl;
}
$list[] = $listingbulk;
$page++;
}
return $list;
}
After reading documentation I have tried to write the following source:
$contents = array();
//$contents['badge'] = "+1";
$contents['alert'] = "Touchdown!";
//$contents['sound'] = "cat.caf";
$notification = array();
$notification= $contents;
$audience['tag'] = "49ers";
$scheduled['scheduled_time'] = "2013-04-01T18:45:30";
$push['push'] = array("audience"=> $audience, "notification"=>$notification, "device_types"=>"all");
$response = array();
array_push($response, array("name" => "My schedule", "schedule"=> $scheduled));
array_push($response, $push);
$json = json_encode($response);
//echo "Payload: " . $json . "\n"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
// echo "Response: " . $content . "\n";
print_r($content);
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
$error = "Got negative response from server: " . $response['http_code'] . "\n";
} else {
$success = "Message has been sent successfully";
}
I am getting error = 0.
Can anyone help me please?
Thanks.
I have figured out the problem with the help of #dperconti (thank you very much).
I am posting a solution to 'how to schedule push for urbanairship' so others may find it helpful.
Code is:
define('APPKEY','xxxx'); // Your App Key
define('PUSHSECRET', 'xxxx'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/schedules/');
$contents = array();
//$contents['badge'] = "+1";
$contents['alert'] = "Touchdown!";
//$contents['sound'] = "cat.caf";
$notification = array();
$notification= $contents;
$audience = "all";
$scheduled['scheduled_time'] = "2016-04-01T18:45:30";
// $push['push'] = array("audience"=> $audience, "notification"=>$notification, "device_types"=>"all");
$response = array();
array_push($response, array("name" => "My schedule", "schedule"=> $scheduled, "push" => array("audience"=> $audience, "notification"=>$notification, "device_types"=>"all")));
// array_push($response, $push);
$json = json_encode($response);
echo "Payload: " . $json . "<br><br><br>"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
// echo "Response: " . $content . "\n";
print_r($content);
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
$error = "Got negative response from server: " . $response['http_code'] . "\n";
} else {
$success = "Message has been sent successfully";
}
curl_close($session);