CookieMonster's avatar

URL concatenate variable into string

I made an external API call to generate airbill. I have to pass in a tracking number into the URL. It's like:

//generate airway bill for order created
                        $url = "https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=".$response['tracking_number']."&h=0";
                        
                        $airwaybill_response = Http::withToken($token)->get($url); 

The response tracking number is my response from order creation API which returns as a json as string value. When I dd($url), it returns the URL correctly like $url = "https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=MKS321&h=0"; but it couldn't receive response when I call the API as it says order could not be found.

I tried using the tracking number directly(without variable/concatenate) :

 $url = "https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=MKS321&h=0";

and it works. To sum it up, using url with the actual tracking number can work but concatenate it with variable(with same tracking number) could not work.

Did I overlook something?

0 likes
5 replies
Sinnbeck's avatar

Try cleaning it up

$url = sprintf('https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=%s&h=0', $response['tracking_number']);
CookieMonster's avatar

@Sinnbeck Apparently, still couldn't work. It only works if I hardcode the tracking number into the string.

Sinnbeck's avatar

@nickywan123

What about this

$url = sprintf('https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=%s&h=0', $response['tracking_number']);
$real_url = 'https://api-sandbox.xxxxxx.co/SG/2.0/reports/waybill?tids=%s&h=0'; //replace this with the manually typed url

dd($url, $real_url, $url === $real_url);

What is the output?

CookieMonster's avatar

@Sinnbeck My code:

$data = "MYKPS890554196962775040";
                        //$url = "https://api-sandbox.ninjavan.co/SG/2.0/reports/waybill?tids=MYKPS890554196962775040&h=0";
                        $url = sprintf('https://api-sandbox.xxx.co/SG/2.0/reports/waybill?tids=%s&h=0', $data);
                        $real_url = 'https://api-sandbox.xxx.co/SG/2.0/reports/waybill?tids=MYKPS890554196962775040&h=0';
                        
                        $airwaybill_response = Http::withToken($token)->get($url);                    
          
                        file_put_contents(''.$response['tracking_number'].''.'.pdf', $airwaybill_response->getBody()->getContents());
                        
                        dd($url, $real_url, $url === $real_url);

Output: Returns true.

It means my initial way of concatenating is correct but somehow it could not "read" the url.

Please or to participate in this conversation.