example.com URL
I am calling this url but getting jsonCallback({"ERROR": "6"});. I cannot understand what this is. I have searched many times for the error but could not find out anything helpful.
This is a website by calling this url I will get price list. When I am calling this from the website itself I am getting the data properly. but whenever I a m going to copy the http request and paste it to url it is showing error.
Below are my CURL request :
<?php
class CURL {
var $callback = false;
function setCallback($func_name) {
$this->callback = $func_name;
}
function doRequest($method, $url, $vars) {
$headers=array();
$headerVar=0;
$headers[$headerVar]='Content-Type: text/javascript; charset=UTF-8';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
$data = curl_exec($ch);
curl_close($ch);
echo '<br><br>'.curl_error().'-----'.curl_error();
return $data;
if ($data) {
if ($this->callback)
{
$callback = $this->callback;
$this->callback = false;
return call_user_func($callback, $data);
} else {
return $data;
}
} else {
return curl_error($ch);
}
}
function get($url) {
return $this->doRequest('GET', $url, 'NULL');
}
function post($url, $vars) {
return $this->doRequest('POST', $url, $vars);
}
}
function stringParameter($array) {
$post_items=array();
foreach ( $array as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
return $post_string;
}
function build_http_query( $query ){
$query_array = array();
foreach( $query as $key => $key_value ){
if($key_value != ''){
$query_array[] = urlencode($key) . '=' . urlencode( $key_value );
}else {
$query_array[] = urlencode($key) . '=' . $key_value ;
}
}
return htmlspecialchars(implode( '&', $query_array ));
}
list($usec, $sec) = explode(" ", microtime());
$time13 = sprintf('%d%03d', $sec, $usec/1000);
$data =
array(
"brand" => "PERODUA",
"model" => "VIVA 1.0",
"gender" => "Male",
"md_age" => '35',
"marital_status" => "Married",
"car_age" => '8',
"ncd" => '0',
"data" =>
array(
"car_data" => array(
"make"=>"PERODUA",
"model"=>"VIVA 1.0",
"year_of_manufacture"=>"2004",
"offpeak"=>"yes"
),
"drivers_data" => array(
"driver_1"=> array(
"gender" => "Male",
"marital_status" => "Married",
"date_of_birth" => "22/3/1978",
"year_driving_license" => "1999",
"ncd" => "0",
"occupation" => "ZADM: Indoor Office/Exec/Admin Staff",
"relationship" => " "
)
),
"discount_data" => array(
"certificate_of_merit" => false
),
"claims_data" => array(
"have_claims" => "no",
"claims_number" => "0",
"claims_amount" => "0"
),
"product_data" => array(
"plan" => null,
"price" => null,
"policy_start"=> "1/5/2013",
"policy_end"=> "30/4/2014",
"ncd"=> false,
"excess"=> null
)
)
);
$encode = build_http_query($data);
$url = 'https://example.com/price?callback=jsonCallback&'.$encode;
$obj = new CURL();
echo $ppp = $obj->get($url);
?>
Am I am wrong in sending the data in the url as it is written in json?
Try to use build_http_query but http_build_query instead
The {"ERROR": "6"} message is a custom error message return by https://axasingaporemotor.appspot.com/price
You will need to contact the owner of that URL in order to understand what they mean by error 6.
Related
I am using instagram api to search specific hashtag getting top media and recent media but graphic shows 4 different calls, so the the 200 limit per hour are consumed really fast. I know about ig_hashtag_search , top_media and recent_media but what i dont know what is shadowIGHastag.
Is there a way to avoid overconsumption of my app?
This is how i use the api
function insthashtag()
{
include "../insta/define.php";
function makeApiCall($endpoint, $type, $params)
{
$ch = curl_init();
if ('POST' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
} elseif ('GET' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$hashtag = 'sedapal';
$hashtagId = '17843308429009249';
$hashtagSearchEndpoint = ENDPOINT_BASE . 'ig_hashtag_search';
$hashtagSearchParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,name',
'q' => $hashtag,
'access_token' => $accessToken
);
$hashtagSearch = makeApiCall($hashtagSearchEndpoint, 'GET', $hashtagSearchParams);
/* To get hashtagID */
/* echo '<pre>';
print_r($hashtagSearch);
die(); */
$hashtagDataEndpoint = ENDPOINT_BASE . $hashtagId;
$hashtagDataParams = array(
'fields' => 'id,name',
'access_token' => $accessToken
);
$hashtagData = makeApiCall($hashtagDataEndpoint, 'GET', $hashtagDataParams);
$hashtagTopMediaEndpoint = ENDPOINT_BASE . $hashtagId . '/top_media';
$hashtagTopMediaParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagTopMedia = makeApiCall($hashtagTopMediaEndpoint, 'GET', $hashtagTopMediaParams);
$topPost = $hashtagTopMedia['data'][0];
$topPost1 = $hashtagTopMedia['data'][1];
$topPost2 = $hashtagTopMedia['data'][3];
/* To get recent data
$hashtagRecentEndpoint = ENDPOINT_BASE . $hashtagId . '/recent_media';
$hashtagRecentParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagRecent = makeApiCall($hashtagRecentEndpoint, 'GET', $hashtagRecentParams);
$recentPost = $hashtagRecent['data'][0];
$recentPost2 = $hashtagRecent['data'][1]; */
/* $recentPost3 = $hashtagRecent['data'][2]; */
$return = [$topPost['media_type'], $topPost['media_url'], $topPost1['media_type'], $topPost1['media_url'], $topPost2['media_type'], $topPost2['media_url']];
$jsondata = json_encode($return, JSON_PRETTY_PRINT);
return $jsondata;
when I use function isPaymentComplete , and return the $result to get the payment information, the user session ended , how can solve this issue
paytabs is payment getway , i use laravel passport in my project and i use the visa payment by paytabs getway, after the payment process complete I use API function to get a transaction , but when i use this function the user session will expire and became logout
paytabs Controller
<?php
namespace App\Http\Controllers;
use App\Order;
use App\Product;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
define("AUTHENTICATION", "https://www.paytabs.com/apiv2/validate_secret_key");
define("PAYPAGE_URL", "https://www.paytabs.com/apiv2/create_pay_page");
define("VERIFY_URL", "https://www.paytabs.com/apiv2/verify_payment");
class PaytabsController extends Controller
{
private $merchant_email;
private $secret_key;
public function __construct() {
$this->merchant_email = "test#gmail.com";
$this->secret_key = "gIHQJSHpoZTj8QFyRcA7zYXfsBcZ0fAgXh6GaO6zO0SWQxuIK5Pj3NzvoMuo15FYmMFwBM5pNYlEwQmgVczZZ9vnVZMW5rVreAYP";
}
public static function getInstance($merchant_email, $merchant_secretKey)
{
static $inst = null;
if ($inst === null) {
$inst = new PaytabsController();
}
$inst->setMerchant($merchant_email, $merchant_secretKey);
return $inst;
}
public function go(){
$price = session()->get('prices')['price_sar'];
/*
if (!Auth::user()){
return redirect('login');
}
*/
$pt = \App\Http\Controllers\PaytabsController::getInstance("test#gmail.com", "gIHQJSHpoZTj8QFyRcA7zYXfsBcZ0fAgXh6GaO6zO0SWQxuIK5Pj3NzvoMuo15FYmMFwBM5pNYlEwQmgVczZZ9vnVZMW5rVreAYP");
$result = $pt->create_pay_page([
"merchant_email" => "test#gmail.com",
'secret_key' => "gIHQJSHpoZTj8QFyRcA7zYXfsBcZ0fAgXh6GaO6zO0SWQxuIK5Pj3NzvoMuo15FYmMFwBM5pNYlEwQmgVczZZ9vnVZMW5rVreAYP",
'title' => "العنوان",
'cc_first_name' => "الاسم الاول",
'cc_last_name' => "الاسم الاخير",
'email' => "example#email.com",
'cc_phone_number' => "966",
'phone_number' => "55555555555",
'billing_address' => "شارع ",
'city' => "الرياض",
'state' => "الرياض",
'postal_code' => "96600",
'country' => "SAU",
'address_shipping' => "شارع",
'city_shipping' => "الرياض",
'state_shipping' => "الرياض",
'postal_code_shipping' => "96600",
'country_shipping' => "SAU",
"products_per_title"=> "خدمات",
'currency' => "SAR",
"unit_price"=> $price,
'quantity' => "1",
'other_charges' => "0",
'amount' => $price,
'discount'=>"0",
"msg_lang" => "arabic",
"reference_no" => "1231231",
"site_url" => "http://127.0.0.1:8000/",
'return_url' => "http://127.0.0.1:8000/payment_reference",
"cms_with_version" => "Laravel",
]);
if($result->response_code == 4012){
return redirect($result->payment_url);
}
return $result->result;
}
function setMerchant($merchant_email, $merchant_secretKey) {
$this->merchant_email = $merchant_email;
$this->merchant_secretKey = $merchant_secretKey;
$this->api_key = "";
}
function authentication(){
$obj = json_decode($this->runPost(AUTHENTICATION, array("merchant_email"=> $this->merchant_email, "secret_key"=> $this->secret_key)),TRUE);
if($obj->response_code == "4000"){
return TRUE;
}
return FALSE;
}
function create_pay_page($values) {
$values['merchant_email'] = $this->merchant_email;
$values['secret_key'] = $this->secret_key;
$values['ip_customer'] = $_SERVER['REMOTE_ADDR'];
$values['ip_merchant'] = isset($_SERVER['SERVER_ADDR'])? $_SERVER['SERVER_ADDR'] : '::1';
return json_decode($this->runPost(PAYPAGE_URL, $values));
}
function verify_payment($payment_reference){
$values['merchant_email'] = $this->merchant_email;
$values['secret_key'] = $this->secret_key;
$values['payment_reference'] = $payment_reference;
return json_decode($this->runPost(VERIFY_URL, $values));
}
function runPost($url, $fields) {
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
$ip = $_SERVER['REMOTE_ADDR'];
$ip_address = array(
"REMOTE_ADDR" => $ip,
"HTTP_X_FORWARDED_FOR" => $ip
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
/*
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $ip_address);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 1);
*/
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
**public function isPaymentComplete(Request $request)
{
$pt = PaytabsController::getInstance("test#gmail.com", "gIHQJSHpoZTj8QFyRcA7zYXfsBcZ0fAgXh6GaO6zO0SWQxuIK5Pj3NzvoMuo15FYmMFwBM5pNYlEwQmgVczZZ9vnVZMW5rVreAYP");
$result = $pt->verify_payment($request->payment_reference);
if ($result->response_code == 100) {
return view('website.approved',[
'result' => $result
]);
}
return view('website.canceled');
}**
}
i am trying to get data using Curl
i was trying to get best result but i got
but my goal to get specific line NOT all the lines.
see my code and please help to get the result with
"routing" AND "tot_dist" Other variables NO
here is my code
<?php
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
echo httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
// I WANT TO GET THE RESULT WITH ROUTING AND tot_dist ONLY LIKE THIS
//OOMS DCT KASIN DCT OOSA
//459.5
?>
This result i got
{"rc":"100","rmsg":"OK","gc_dist":459.2,"routing":"OOMS DCT KASIN DCT OOSA","tot_dist":459.5,"legs":[{"wt":"A","id":"OOMS","lat":"23.6002","lon":"58.2836","freq":"","via":"","brg":"0.0","dist":"0.0","name":"MUSCAT INTERNATIONAL"},{"wt":"W","id":"KASIN","lat":"20.3147","lon":"55.9617","freq":"","via":"DCT","brg":"214.7","dist":"235.8","name":"KASIN"},{"wt":"A","id":"OOSA","lat":"17.0387","lon":"54.0913","freq":"","via":"DCT","brg":"209.6","dist":"223.6","name":"SALALAH"}]}
but i need only "Routing" and "tot_dist"
Once you make a request, you will get all the data. You can then select what you need. Here is what your code should look like to select only routing and tot_dist
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
array(
'Accept:application/json'
)
);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
$data = httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
echo $data['routing'] . "\n";
echo $data['tot_dist'] . "\n";
I got method in getting the access token and here it is
public $token; //I declare global var to read in every func
public function getToken(){
$key = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxx';
$data = array(
'key' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxx'
);
$payload = json_encode($data);
$ch = curl_init('https://cgi.singmap.com/token?key='.$key.'&secret='.$secret.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
$token = $trimmed['access_token'];
curl_close($ch);
$this->token = $token;
}
The token only lasts for 5 minutes to use. But in my other method like this which uses token
public function propertyUnitDetails(){
$unitId = \DB::table('property_unit_list')
->select('projectId','unitId')
->get();
foreach($unitId as $res){
$this->getToken();
$final_token = $this->token;
// dd($final_token);
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
$pageNo = 1;
$pageSize = 200;
$url = 'https://cgi.singmap.com/unit/queryUnitDetail?request_time='.$request_time.
'&token='.$final_token.'&sign='.$sign.'&projectId='.$res->projectId.'&unitId='.$res->unitId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
if(empty($trimmed)){
$this->getToken();
$final_token = $this->token;
}
foreach ($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'stack' => $data['stack'],
'floorPlanId' => $data['floorPlanId'],
'soldBy' => $data['soldBy'],
'transactionPrice' => $data['transactionPrice'],
'type' => $data['type'],
'unitId' => $data['unitId'],
'floorPlanName' => $data['floorPlanName'],
'price1' => $data['price1'],
'price2' => $data['price2'],
'price3' => $data['price3'],
'price4' => $data['price4'],
'custom1' => $data['custom1'],
'custom2' => $data['custom2'],
'custom3' => $data['custom3'],
'custom4' => $data['custom4'],
'direction' => $data['direction'],
'area' => $data['area'],
'buildName' => $data['buildName'],
'unitName' => $data['unitName'],
'buildId' => $data['buildId'],
'bathrooms' => $data['bathrooms'],
'transactionDate' => $data['transactionDate'],
'bedrooms' => $data['bedrooms'],
'purchaseStatus' => $data['purchaseStatus'],
];
}
}
$chuncked = array_chunk($inserts, 10);
foreach($chuncked as $inserts){
\DB::table('property_project_details')->insert($inserts);
}
dd('record inserted');
}
When the function is not completely excecuted or the data is not fully inserted, maybe because it has a large amount of data. It throws an error of datas index is not found or something from the curl response. It is because I can only get the datas based on the token i get manually or declared manually. What I want is that if the token expires, it will run the function getToken() and pass the token to the running function in order to avoid interrupting it.
EDIT:
I added
$this->getToken();
$final_token = $this->token;
in my foreach statement because #user001232 said that in every unitId result query I got, a new token would be generated. But I still got an error every 5 mins that is because i cant get a new token even if i add that function in there.
Here you go, this will work:
<?php
class NameOfYourClass {
public $token;
public function refreshToken()
{
$key = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxx';
$data = array(
'key' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxx'
);
$payload = json_encode($data);
$ch = curl_init('https://cgi.singmap.com/token?key='.$key.'&secret='.$secret.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Content-Length: ' . strlen($payload))
);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
$this->token = $trimmed['access_token'];
curl_close($ch);
}
private function getUnitDetails($res, $attempts = 1)
{
// We only allow 5 attempts to avoid getting into infinite loops
if ($attempts > 5) {
throw new \Exception('Signmap API Issue');
}
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($this->token.$request_time);
$pageNo = 1;
$pageSize = 200;
$url = 'https://cgi.singmap.com/unit/queryUnitDetail?request_time='.$request_time.
'&token='.$this->token.'&sign='.$sign.'&projectId='.$res->projectId.'&unitId='.$res->unitId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'] ?? null;
// If the response datas is empty, we're assuming it's because of a token error, so we retry
if(empty($trimmed)){
$attempts++;
$this->refreshToken();
return $this->getUnitDetails($res, $attempts);
}
return $trimmed;
}
public function propertyUnitDetails()
{
// Grab all of the units
$unitItds = \DB::table('property_unit_list')->select('projectId','unitId')->get();
foreach($unitId as $res) {
$trimmed = $this->getUnitDetails($res);
foreach ($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'stack' => $data['stack'],
'floorPlanId' => $data['floorPlanId'],
'soldBy' => $data['soldBy'],
'transactionPrice' => $data['transactionPrice'],
'type' => $data['type'],
'unitId' => $data['unitId'],
'floorPlanName' => $data['floorPlanName'],
'price1' => $data['price1'],
'price2' => $data['price2'],
'price3' => $data['price3'],
'price4' => $data['price4'],
'custom1' => $data['custom1'],
'custom2' => $data['custom2'],
'custom3' => $data['custom3'],
'custom4' => $data['custom4'],
'direction' => $data['direction'],
'area' => $data['area'],
'buildName' => $data['buildName'],
'unitName' => $data['unitName'],
'buildId' => $data['buildId'],
'bathrooms' => $data['bathrooms'],
'transactionDate' => $data['transactionDate'],
'bedrooms' => $data['bedrooms'],
'purchaseStatus' => $data['purchaseStatus'],
];
}
}
$chuncked = array_chunk($inserts, 10);
foreach($chuncked as $inserts){
\DB::table('property_project_details')->insert($inserts);
}
dd('record inserted');
}
}
What if you call the method getToken() everytime you got a projectId in your loop. Its like this
foreach($project_id as $res){
$this->getToken();
$final_token = $this->token;
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
//and so on ....
In that way. it will get a new token in every projectId. the only drawbacks is it will execute very slowly.
And if it is still got the error replace your code like this. Add a condition if empty
public function propertyBuildings(){
$project_id = \DB::table('project_list')
->select('projectId')
->get();
foreach($project_id as $res){
$this->getToken();
$final_token = $this->token;
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
$url = 'https://cgi.singmap.com/project/queryBuilding?request_time='.$request_time.
'&token='.$token.'&sign='.$sign.'&projectId='.$res->projectId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
if(empty($trimmed)){
$this->getToken();
$final_token = $this->token;
}
// return $trimmed;
foreach($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'buildId' => $data['buildId'],
'buildName' => $data['buildName'],
];
}
}
\DB::table('property_building')->insert($inserts);
dd('Data Inserted');
}
I'm currently trying to create an issue in Redmine via the REST API. I export the issues from Redmine in a CSV file. Then, I'm creating an xml file from the CSV, then send it to the API with cURL. I'm setting some options :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => URL_REDMINE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/xml; charset=utf-8',
'X-Redmine-API-Key: '.KEY_API),
CURLOPT_BINARYTRANSFER => TRUE,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataXML,
CURLOPT_SAFE_UPLOAD => TRUE,
CURLOPT_ENCODING => "utf-8"
));
curl_exec($curl);
echo json_encode(curl_getinfo($curl));
So, I'm clearly saying that the encoding should be UTF-8. But when I print the informations (with curl_getinfo), here's what I get :
{"url":"[URL I was targeting]",
"content_type":"text\/html; charset=iso-8859-1", [...]}
(I erased some irrelevant informations, but if someone wants it entirely, I can paste it.)
So, it says the content_type is text\/html; charset=iso-8859-1 when I set it as application/xml; charset=utf-8. Is there something I didn't understand with REST API?
Following is simple curl call for php with redmine.
**flie class file in redmine/redmine_curl.php**
<?php # Redmine Api
class class_redmine{
function get_upload_token($filecontent){
global $redmine_url , $redmine_key;
$upload_url = $redmine_url.'uploads.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/octet-stream';
//$filecontent = file_get_contents('test.php');
return $token = $this->curl_redmine($upload_url,$request,$filecontent);
//$token->upload->token;
}
#Issue
function create_issue($post_data){
global $redmine_url , $redmine_key;
$issue_url = $redmine_url.'issues.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/json';
return $this->curl_redmine($issue_url,$request,$post_data);
}
function get_issue($issue_id='',$project_id=''){
global $redmine_url , $redmine_key;
if($project_id!=''){
$issue_url = $redmine_url.'issues.json?key='.$redmine_key.'&project_id='.$project_id;
}else{ $issue_url = ($issue_id=='')?$redmine_url.'issues.json?key='.$redmine_key : $redmine_url.'issues/'.$issue_id.'.json?key='.$redmine_key;
}
return $this->curl_redmine($issue_url,'','');
}
#Projects
function get_projects($project_id=''){
global $redmine_url , $redmine_key;
$proj_url = ($project_id=='')?$redmine_url.'projects.json?key='.$redmine_key : $redmine_url.'projects/'.$project_id.'.json?key='.$redmine_key;
return $this->curl_redmine($proj_url,'','');
}
#Curl
function curl_redmine($redmine_url,$request='',$post_data=''){
if(!isset($request['type'])){ $request['type']=null; }
if(!isset($request['content_type'])){ $request['content_type']=null; }
//Create a curl object
$ch = curl_init();
//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $redmine_url );
if($request['type'] == 'post'){
//This is a POST query
curl_setopt($ch, CURLOPT_POST,1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: '.$request['content_type'],
'Content-Length: ' . strlen($post_data))
);
}
//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/
//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Execute the action to login
$postResult = curl_exec($ch);
//if($postResult == false){ return $info = curl_getinfo($ch);}
$response = json_decode($postResult);
//echo '<pre>'; print_r($response); echo '</pre>';
return $response;
}
}//class_redmine
?>
Example file example.php
<?php
//code for class_settting.php
function get_redmine($methodName='',$data=''){
global $redmine_url , $redmine_key;
//$query='select * from '.VIS_TABLE_PREFIX.'integration where integration_type=37 and is_enabled=1 and domain_id='.VIS_DOMAIN;
//$res = $this->database->query_exec($query);
//$login_integrate=$this->database->fetch_result_array($res);
/*if($login_integrate==-1){ return $login_integrate; }
if(count($login_integrate)>0 && $login_integrate!=-1){
$redmine_url = $login_integrate[0]['billing_url'];
$redmine_username = $login_integrate[0]['admin_user'];
$redmine_password = $login_integrate[0]['admin_password'];
$redmine_key = $login_integrate[0]['api_key'];
}*/
$redmine_url = 'http://localhost/redmine/';
$redmine_key = '41f132773cc29887bc2e4566863aedc01cde6e2b';
include_once('redmine/redmine_curl.php');
$obj_redmine = new class_redmine();
#check Auth
$res = $obj_redmine->get_projects();
if(!isset($res->projects) || (isset($res->total_count) && ($res->total_count)==0)){ return -1; }
switch($methodName){
case 'check_status' : return $login_integrate; ##check redmine integration in vision
break;
##Trackers
//
##Issue statuses
//
##Project
case 'projectAll' : return $obj_redmine->get_projects(); #used
break;
case 'projectById' : return $obj_redmine->get_projects($data['project_id']);
break;
##Users
//
##Issues
case 'showIssue' : return $obj_redmine->get_issue($data['issue_id']);
break;
case 'issueAll' : return $obj_redmine->get_issue();
break;
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']);
break;
case 'createIssue' : return $obj_redmine->create_issue($data);
break;
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data);
break;
default: return 0;
}
}
$filecontent = file_get_contents('test.php');
$token = get_redmine('uploadFileToIssue',$filecontent);
$filecontent = file_get_contents('Picture.jpg');
$token2 = get_redmine('uploadFileToIssue',$filecontent);
$uploads = array(
array(
'token' => $token->upload->token,
'filename' => 'MyFile.php',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/txt',
),
array(
'token' => $token2->upload->token,
'filename' => 'Picture.jpg',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/image',
),
);
$custom_fields = array(
array(
'id' => 1,
'name' => 'Phone',
'value' => '1234265689'
),
array(
'id' => 2,
'name' => 'Proj sub name',
'value' => 'Test'
),
);
$post_data = array('issue'=>array(
'project_id' => 4,
'subject' => 'ABCDEFG',
'description' => 'Test',
'uploads' => $uploads,
'custom_fields' => $custom_fields,
),);
$post_data = json_encode($post_data);
#all proj
//$res = get_redmine('projectAll');
#proj by id
//$res = get_redmine('projectById',array('project_id'=>'4'));
#get all issue
//$res = get_redmine('issueAll');
#get issue by id
//$res = get_redmine('showIssue',array('issue_id'=>'85'));
#get issue by project id
//$res = get_redmine('issueByProjectId',array('project_id'=>'5'));
#create issue
$res = get_redmine('createIssue',$post_data);
echo '<pre>';print_r($res);
?>