Update Values in Database after getting success message using curl - php

i am getting below message after passing values in url with curl:
{"AddManifestDetails":[{"AuthKey":"Valid","ReturnMessage":"successful",}]
If ReturnMessage is successful , than i want to update values in database, i tried below code :
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
foreach ($res->curl_response as $values)
{
if($values->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress', where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";die;
}
else
{
echo $values->ReturnMessage;die;
}
}
Here is full code : https://pastebin.com/EvcEY0xp
Result :
Notice: Undefined property: stdClass::$curl_response
Warning: Invalid argument supplied for foreach()

$res will already contain decoded response from curl request, which will have only 1 property - AddManifestDetails.
Try following:
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";
die;
}
else
{
echo $res->AddManifestDetails[0]->ReturnMessage;
die;
}

Related

Accessing object returned from GraphQL using curl

I have returned data using GraphQL / curl that looks like this:
{
"data" : {
"publisher" : {
"contracts" : {
"totalCount" : 11,
"count" : 1,
"resultList" : [
I want to get the resultList array and keep getting an error 'Warning: Attempt to read property "data" on string' when trying to do $result->data to move into the first object. What am I doing wrong?
My variable from the curl request is $result.
Update: I HAVE TRIED DECODING AND THE RETURNED DATA IS OF TYPE INT? How?
function getData($data_String){
$endpoint = "https://programs.api.cj.com/query";
$authToken = "pass";
$qry = '{"query":"{ publisher { contracts(publisherId: \"xxxxxxx\", limit: 1, filters: {advertiserId: \"'.$advertiser_id.'\"}) { totalCount count resultList { startTime endTime status advertiserId programTerms { id name specialTerms { name body } isDefault actionTerms { id actionTracker { id name description type } lockingMethod { type durationInDays } performanceIncentives { threshold { type value } reward { type commissionType value } currency } commissions { rank situation { id name } itemList { id name } promotionalProperties { id name } rate { type value currency } } } } } } } }","variables":null}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result);
return $data;
}
First, be sure to check if the result is a valid json.
Then use json_decode to get an object
$result = json_decode($result);
if (is_object($result)) {
if (!empty($result->data->publisher->contracts->resultList)) {
$resultList = $result->data->publisher->contracts->resultList;
}
} else {
// Log or something
error_log("json decode return: " . print_r($result, true))
}

kill sessions after payment and return to callback page

after user fill form of his or her information it create some sessions that i need kill all sessions in callback page but it dont work by destroy sessions or unset sessions.
after fill information page we have 3 pages as bellow.
payment.php
<?php session_start();
require_once('variables.php');
require_once('../includes/config.php');
$stmt = $db->prepare('SELECT * FROM order_main WHERE name = :name and phone=:phone');
if($stmt->execute(array(':name' => $_SESSION['post-data']['name'], ':phone' => $_SESSION['post-data']
['phone'] ) ));
while($row = $stmt->fetch()){
//if($code == $row['code']){
//if(!empty($_POST['code'])){
$_SESSION['order_id'] = $row['order_id'];
//}
// }
}
$order_id = $_SESSION['order_id'];
$amount = $_SESSION['total'];
echo $_SESSION['order_id'];
$_SESSION['order_id']=3;
echo $_SESSION['post-data']['name'];
echo $_SESSION['post-data']['order_desc'];
$name = $_SESSION['post-data']['name'];
$phone = $_SESSION['post-data']['phone'];
$order_desc = $_SESSION['post-data']['order_desc'];
$params = array(
'order_id' => $order_id ,
'amount' => 10000,
'phone' => $phone,
'name' => $name,
'desc' => $order_desc,
'callback' => URL_CALLBACK,
);
idpay_payment_create($params);
/**
* #param array $params
* #return bool
*/
function idpay_payment_create($params) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_PAYMENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) || empty($result->link)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
//.Redirect to payment form
header('Location:' . $result->link);
}
variables.php
<?php session_start();
define('URL_CALLBACK', 'http://www.siteaddress.org/blog/php-simple-master/callback.php');
define('URL_PAYMENT', 'https://api.idpay.ir/v1.1/payment');
define('URL_INQUIRY', 'https://api.idpay.ir/v1.1/payment/inquiry');
define('URL_VERIFY', 'https://api.idpay.ir/v1.1/payment/verify');
define('APIKEY', 'xxxxx...');
define('SANDBOX', 1);
callback.php(i want destroy some or all sessions here but cant)
<?php session_start();
require_once('variables.php');
require_once('config.php');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$response = $_POST;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$response = $_GET;
}
if (empty($response['status']) ||
empty($response['id']) ||
empty($response['track_id']) ||
empty($response['order_id'])) {
return FALSE;
}
if ($response['status'] != 10) {
print idpay_payment_get_message($response['status']);
}
// if $response['id'] was not in the database return FALSE
$inquiry = idpay_payment_get_inquiry($response);
if ($inquiry) {
$verify = idpay_payment_verify($response);
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_get_inquiry($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_INQUIRY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
if ($result->status == 10) {
return TRUE;
}
print idpay_payment_get_message($result->status);
return FALSE;
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_verify($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_VERIFY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
print idpay_payment_get_message($result->status);
//print '<pre>';
//print_r($result);
//print '</pre>';
$stmt = $db->prepare('UPDATE order_main SET track_id = :track_id, id = :id, order_date=:date
WHERE order_id = :order_id ') ;
$stmt->execute(array(
':track_id' => $_GET['track_id'],
':id' => $_GET['id'],
':date' => $_GET['date'],
':order_id' => $_GET['order_id']
));
}
/**
* #param int $status
* #return string
*/
function idpay_payment_get_message($status) {
switch ($status) {
case 1:
return 'پرداخت انجام نشده است';
case 2:
return 'پرداخت ناموفق بوده است';
case 3:
return 'خطا رخ داده است';
case 10:
return 'در انتظار تایید پرداخت';
case 100:
return 'پرداخت تایید شده است لطفا منتظر بمانید';
case 101:
return 'پرداخت قبلاً تایید شده است';
default:
return 'Error handeling';
}
}
unset ($_SESSION['post-data']['name']);
unset ($_SESSION['post-data']['phone']);
if($_GET['order_desc']){
unset ($_SESSION['post-data']['order_desc']);
}
unset ($_SESSION['order_id']);
unset ($_SESSION['shopping_cart']);
session_start();
session_destroy();
session_commit();
just add session_destroy($_SESSION["your_session]); at the end of your code and same for session_commit

Error in creating record in zohocrm contacts using php 7.1

I am trying to create a record in zohocrm. i am using API version2 code.
i recieve this following error which i stated below. I tried stackoverflow for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version
7.1
Here's the Code i used:
public function createRecord($module, $module_fields)
{
global $HelperObj;
$WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
$activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
$moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
$zohoapi = new SmackZohoApi();
$module_field['data'] = array($module_fields);
$module_field['Owner']['id'] = $module_fields['SMOWNERID'];
$fields_to_skip = ['Digital_Interaction_s', 'Solution'];
foreach ($module_fields as $fieldname => $fieldvalue) {
if (!in_array($fieldname, $fields_to_skip)) {
continue;
}
$module_fields[$fieldname] = array();
if (is_string($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
} else if (is_array($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
}
}
//$fields = json_encode($module_fields);
$attachments = $module_fields['attachments'];
$body_json = array();
$body_json["data"] = array();
array_push($body_json["data"], $module_fields);
$record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
$get_access_token = $zohoapi->refresh_token();
if (isset($get_access_token['error'])) {
if ($get_access_token['error'] == 'access_denied') {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "Access Denied to get the refresh token";
return $data;
}
}
$exist_config = get_option("wp_wpzohopro_settings");
$config['access_token'] = $get_access_token['access_token'];
$config['api_domain'] = $get_access_token['api_domain'];
$config['key'] = $exist_config['key'];
$config['secret'] = $exist_config['secret'];
$config['callback'] = $exist_config['callback'];
$config['refresh_token'] = $exist_config['refresh_token'];
update_option("wp_wpzohopro_settings", $config);
$this->createRecord($module, $module_fields);
} elseif ($record['data'][0]['code'] == 'SUCCESS') {
$data['result'] = "success";
$data['failure'] = 0;
} else {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "failed adding entry";
}
return $data;
}
API Call Code:
public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
try{
$apiUrl = "https://www.zohoapis.com/crm/v2/$module";
$fields = json_encode($data_array);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($result,true);
if($extraParams != "")
{
foreach($extraParams as $field => $path){
$this->insertattachment($result_array,$path,$module);
}
}
}catch(\Exception $exception){
// TODO - handle the error in log
}
return $result_array;
}
error i got:
Array
(
[data] => Array
(
[0] => Array
(
[code] => INVALID_DATA
[details] => Array
(
[expected_data_type] => jsonarray
[api_name] => Solution_Interest
)
[message] => invalid data
[status] => error
)
)
)
By the details which you gave ,
(1)you said you wish to create "Contacts" , but the url you are using to create contact doesn't seems to create "Contacts" either by
**converting leads to account and contact , or
**directly creating contact
(2)you mentioned module name as "Lead" , try changing it to "Leads".
(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.
(4)Here is a help doc. for you
Create Contact
If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here

Json data get from API URL (using curl)

The online service "eTermin" provides an API Url which outputs reviews of my service.
I tried it with this code but only got a bad request and an error:
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false); // DEBUGGING set to true
$curl_response = curl_exec($curl);
echo print_r($curl_response); // test the JSON array
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response, true);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
The eTermin FAQ did not provide all the information needed. In order to GET or POST you need to send a publickey, a salt and an encoded signature in the Header.
So this is the solution to GET the ratings of my eTermin account (the return is not formatted yet!):
$publicKey = "[publicKey]";
$secretKey = "[secretKey]";
// Generates a random string of ten digits
$salt = mt_rand();
// Computes the signature by hashing the salt with the secret key as the key
$signature = hash_hmac('sha256', $salt, $secretKey, true);
// base64 encode
$encodedSignature = base64_encode($signature);
// CURL GET REQUEST
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'publickey:'.$publicKey,
'salt:'.$salt,
'signature:'.$encodedSignature
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HEADER, true);
$curl_response = curl_exec($curl);
$curl_response = json_decode($curl_response);
echo print_r($curl_response);
This is what it returns:
Array ( [0] => stdClass Object ( [ID] => 60979 [AppointmentExternalID] => XXXXXXX [CustomerFeedback] => Sehr schöner Laden, sehr privat. Wir wurden von zwei Experten gleichzeitig beraten, Preise sind angemessen. Schöne Anzüge. Wir sind zufrieden. [Rating] => 5 [CustomerInfo] => Benjamin (email#something.at, ) [RatingDate] => 2018-01-24T17:21:20.793 [CalendarID] => 46499 [CalendarName] => Kalender [ServiceID] => 60347 [Publish] => 1 ) [1] => stdClass Object ( [ID] => 61014 [AppointmentExternalID] => XXXXXXXX [CustomerFeedback] => [Rating] => 5 .....
Now all I need to do is format this somehow and get the char encoding to work.
In order to parse the JSON for eTermin ratings use this foreach loop:
//Traverse array __standard_Obj
foreach ($decoded as $key => $value) {
$c_feeback = $value["CustomerFeedback"];
$c_name = $value["CustomerInfo"];
$c_name = before ('(',$c_name);
$c_rating = $value["Rating"];
$c_date = $value["RatingDate"];
if(!empty($c_feeback)):
echo '<h2>Feedback:'.$x.'</h2>';
$x++;
echo '<div>';
if(strlen($c_name)>3):
echo $c_name;
else:
echo "Anonym";
endif;
echo ': '.$c_feeback;
//positiv stars
//$c_rating = 4; //testvalue
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star checked"></span>';
}
//negative stars
$c_rating = 5 - $c_rating;
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star"></span>';
}
endif;
}

Recursive call until value is not more on response

I have a cURL call to this services/data/v28.0/query/?q=SELECT Id,Name,LastModifiedDate FROM Territory and the response looks like:
{
"totalSize": 6911,
"done": false,
"nextRecordsUrl": "/services/data/v28.0/query/01g8000002eI8dMAAS-2000",
"records": [ ... ]
}
That means complete set of records will have 6911 items but on first request just the first 2000 are return, now if I change a bit the cURL call into this /services/data/v28.0/query/01g8000002eI8dMAAS-2000 I will get the next 2000 items for the first 6911 and so on.
I should call the cURL recursive until done = true or nextRecordsUrl will be NULL or doesn't exists anymore on the response, how? I need some advice or pseudo-code that illustrate me how to achieve this since I am a bit stucked.
This shows the complete set of recursive calls I should perform (this could be dynamic so hard code won't work):
call:
/services/data/v28.0/query/?q=SELECT Id,Name,LastModifiedDate FROM Territory
response:
{
"totalSize": 6911,
"done": false,
"nextRecordsUrl": "/services/data/v28.0/query/01g8000002eI8dMAAS-2000",
"records": [ ... ]
}
call:
/services/data/v28.0/query/01g8000002eI8dMAAS-2000
response:
{
"totalSize": 6911,
"done": false,
"nextRecordsUrl": "/services/data/v28.0/query/01g8000002eI8dMAAS-4000",
"records": [ ... ]
}
call:
/services/data/v28.0/query/01g8000002eI8dMAAS-4000
response:
{
"totalSize": 6911,
"done": false,
"nextRecordsUrl": "/services/data/v28.0/query/01g8000002eI8dMAAS-6000",
"records": [ ... ]
}
call:
/services/data/v28.0/query/01g8000002eI8dMAAS-6000
response:
{
"totalSize": 6911,
"done": true,
"records": [ ... ]
}
UPDATE
I have figured out, more or less, how to achieve this but now the my problem turns in how to merge recursive the values from each response. See code below:
$soqlQuery2 = "SELECT Id,Name,LastModifiedDate FROM Territory";
$soqlUrl2 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery2);
$curl = curl_init($soqlUrl2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
curl_close($curl);
$soqlObj2 = json_decode($jsonResponse, true);
$this->performPaginateSOQLQuery($veevaToken, $instanceUrl, $tokenUrl, $soqlObj2['nextRecordsUrl']);
Above in $soqlObj2['done'] and $soqlObj2['nextRecordsUrl'] I will have the values I need for the second and recursive calls. So, I built this function:
public function performPaginateSOQLQuery($veevaToken, $instanceUrl, $tokenUrl, $nextRecordsUrl)
{
if (isset($nextRecordsUrl) && $nextRecordsUrl !== null && $nextRecordsUrl !== "") {
$nextRecordsUrlSOQLQuery = $instanceUrl.$nextRecordsUrl;
$curl = curl_init($nextRecordsUrlSOQLQuery);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $tokenUrl failed with status $status, response $jsonResponse, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$nextRecordsUrlObj = json_decode($jsonResponse, true);
while ($nextRecordsUrlObj['done'] !== true) {
$this->performPaginateSOQLQuery($veevaToken, $instanceUrl ,$tokenUrl, $nextRecordsUrlObj['nextRecordsUrl']);
}
return $nextRecordsUrlObj;
}
}
But I need to merge the whole $soqlObj2 with $nextRecordsUrlObj from each iteration on performPaginateSOQLQuery() call, how? Any help?
UPDATE 2: Losing values on 1st iteration
I've updated my code to this:
public function performPaginateSOQLQuery(
$veevaToken,
$instanceUrl,
$tokenUrl,
&$nextRecordsUrl,
&$dataToSave = array()
) {
if (isset($nextRecordsUrl) && $nextRecordsUrl !== null && $nextRecordsUrl !== "") {
$nextRecordsUrlSOQLQuery = $instanceUrl.$nextRecordsUrl;
$curl = curl_init($nextRecordsUrlSOQLQuery);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $tokenUrl failed with status $status, response $jsonResponse, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$nextRecordsUrlObj = json_decode($jsonResponse, true);
echo $nextRecordsUrlObj['nextRecordsUrl'] . "\n";
print_r($nextRecordsUrlObj);
$dataToSave[] = $nextRecordsUrlObj;
$i = 0;
while ($nextRecordsUrlObj['done'] !== true) {
echo "time ".$i;
$i++;
$this->performPaginateSOQLQuery(
$veevaToken,
$instanceUrl,
$tokenUrl,
$nextRecordsUrlObj['nextRecordsUrl'],
$dataToSave
);
}
return array('url' => $nextRecordsUrlObj, 'data' => $dataToSave);
}
}
But on iteration time 1 I am getting this error:
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined index: nextRecordsUrl
Why is that?
You can use a while loop with a boolean variable.
Once the response you get is the last one (done property is true) change the value of that boolean variable and the loop should stop.
<?php
//Assuming $response contains the response you're getting
//and that it's JSON-encoded.
$keepRequesting = true;
while($keepRequesting){
//Your curl code over here
// ...
$response = json_decode($response);
if($response->done == true) {
$keepRequesting = false;
}
}
Regarding your update:
While I don't think you should use recursive methods for this problem,
just add the data you want to "save" as a reference to the function and use array_merge. Something like that:
public function performPaginateSOQLQuery($veevaToken, $instanceUrl, $tokenUrl, $nextRecordsUrl, &$dataToSave = array()) { //1 new parameters.
//More code here...
$nextRecordsUrlObj = json_decode($jsonResponse, true);
$dataToSave[] = $nextRecordsUrlObj;
while ($nextRecordsUrlObj['done'] !== true) {
$this->performPaginateSOQLQuery($veevaToken, $instanceUrl ,$tokenUrl, $nextRecordsUrlObj['nextRecordsUrl'], $dataToSave);
}
return array('url' => $nextRecordsUrlObj, 'data' => $dataToSave);
The problem is that you should return it, otherwise it will get lost.
You'll have to change the function a bit so it would return the URL and the data you want.
Maybe this post would help you:
php recursion global variable?

Categories