Unable to fetch response from file_get_contents using PHP - php

Gurus,
I am trying to fetch tracking details using the austpost.com.au website for which I have written the below code however, it doesn't seem to fetch anything.
$austpost_url = 'https://digitalapi.auspost.com.au/shipmentsgatewayapi/watchlist/shipments/99702032243801004670904';
$options = array(
'method' => 'get',
'contentType' => 'application/json',
'muteHttpExceptions' => true,
'headers' => array ('Accept' => 'application/json, text/plain, */*',
'Accept-Encoding' => 'gzip, deflate, br',
'AP_CHANNEL_NAME' => 'WEB_DETAIL',
'api-key' => 'd11f9456-11c3-456d-9f6d-f7449cb9af8e',
'Connection' => 'keep-alive',
'Origin' => 'https://auspost.com.au',
'Referer' => 'https://auspost.com.au/mypost/track/'),
);
$context = stream_context_create($options);
$html = file_get_contents($austpost_url, false, $context);
echo $html;
Direct Tracking Link: https://auspost.com.au/mypost/track/#/details/99702032243801004670904
I found this by going to the NETWORK tab in Chrome and figured out which request is loading the tracking details. Basically I am just after getting the status of the shipment. Snapshot below:
Any help in this would be much appreciated as I am using PHP to drive my code where I want to update the WordPress posts statuses based on the shipment status (that I can handle) however, stuck here on how I can get this shipment status before I move on.

It is because you need a valid recaptcha token and proof that you are not a robot. Won't be that simple, as you think. The easiest, but paid method, would be to use some captcha solving companies, like https://2captcha.com (not a sponsor of that answer) and their PHP libs.
If you want to use their api, you need to auth with username and password via basic auth. More details in here: https://developers.auspost.com.au/apis/shipping-and-tracking/reference/track-items

First check the fopen is on or off , add the phpinfo(); code in main file and check this .
Otherwise use the Curl function instead of file_get_contents();

Related

Getting news from sharepoint sites through microsoft graph api

I have been stuck at getting the news from sharepoint sites through the microsoft graph api for a while now, and this is my last resort.
I have been going through the microsoft graph api multiple times and I have found out how to use a work microsoft account to get the sites I am part of, which works fine through this: https://learn.microsoft.com/en-us/graph/api/resources/site?view=graph-rest-1.0
But I cannot figure out where to go from here to get the news that has been created on sharepoint sites, and maybe someone can guide me in the right direction on where to get these?
I have tried going over the microsoft graph documentation multiple times, I have tried everythingg that has to do with sites and only got as far as getting the list of sites the account is part of.
I have tried searching for a solution with no luck.
this is what I have used to get the sharepoint sites list:
/sites?search=*&$select=id,displayName,description,webUrl,sharepointIds
I think I have figured it out, but I am not sure why it is not working if I do it in the same flow, so what I had to do was call the microsoft graph api (I do that through league.
$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => $this->clientId,
'clientSecret' => $this->clientSecret,
'redirectUri' => "<redirect url>",
'urlAuthorize' => "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/authorize",
'urlAccessToken' => "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token",
'urlResourceOwnerDetails' => '',
'scopes' => "openid profile User.Read offline_access Sites.Read.All",
]);
$accessToken = $oauthClient->getAccessToken("authorization_code", ['code' => $authorization_code]);
After I get the access_token and refresh_token I then use curl to get the sharepoint online access_token and refresh_token by using the frefresh_token from the previous step:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "client_id=<client id>&client_secret=<client secret>&refresh_token=<refresh token from the previous step>&grant_type=refresh_token&scope=https%3A%2F%<tenant name>.sharepoint.com%2FSites.Read.All",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded"
),
));
$SPOResponse = curl_exec($curl);
$SPOResponse = json_decode($SPOResponse);
$SPOHttpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
I tried making it all work in 1 step but I could not make it happen for some reason, if I find a way I will update this post.

Azure/Microsoft Identity Platform - Cannot Retrieve Access Token from Token Endpoint (PHP)

I'm trying to write a custom web app that utilizes the Microsoft Identity Platform to authenticate and authorize users. I'm able to successfully authenticate when calling the /authorize endpoint, and I have access to the "code" token that is returned.
I am now trying to retrieve my access token so that I can make calls to the APIs. Whenever I submit a POST request to the /token endpoint, the server returns a 400 Bad Request error. The header information that is provided contains no valuable information for troubleshooting and there is no JSON response returned so I have no idea where or what the issue is.
I'm making my call as follows:
$clientId = '00000000-0000-0000....'; // Omitted
$tenantId = '00000000-0000-0000....'; // Omitted
$grantType = 'authorization_code';
$scope = urlencode('User.Read');
$code = '......' // Obtained from authentication
$redirect_uri = 'http://localhost/smp/auth/handle';
$clientSecret = '...' // Omitted, set up in Azure App registrations under Certificates and secrets
$resource = 'api://00000000-0000-0000....'; // Omitted, set up in Azure App registrations under Overview -> App ID URI
$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$parameters = [
'client_id' => $clientId,
'grant_type' => $grantType,
'scope' => $scope,
'code' => $code,
'redirect_uri' => $redirectUri,
'client_secret' => $clientSecret,
'resource' => $resource
];
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($parameters)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if (!$result) {
exit('an error has occured');
}
PHP returns a warning that reads the following: (tenant id has been omitted):
Warning: file_get_contents(https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\smp\application\models\user-model.php on line 261
I've verified everything I can possibly think of.
The client and tenant ids are working (based on the successful authentication request).
The "code" is correctly retrieved from the authentication request.
Redirect Uri is the same as the one used for the authentication request.
I've tried with and without the client_secret variable. It is my understanding that this is actually required in my case.
I've tried with and without the resource variable, which is setup using the default Azure naming convention of "api://".
Please assist! I know I must be missing something but cannot figure it out. Perhaps permissions or additional setup within Azure? I'm not really sure what's wrong with my code/approach but Microsoft Identity Platform/OAuth isn't returning anything for me to work with and/or troubleshoot.
I've figured this out.
Firstly, I modified by $options variable to include the following:
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($parameters),
'ignore_errors' => true
]
];
Adding ignore_errors allowed me to see the returned JSON.
Next, it became apparent that my parameters were not being accepted because I was url-encoding all of them. My client secret, redirect uri, and client ids were all url encoded (this detail was hidden in my original post because it was just a small snippet of a much larger system). By undoing this encoding, my parameters all ended up being accepted. I suppose it makes sense because these values weren't being appended to a url but rather passed as POST values.
Lastly, the "resource" variable was not accepted (indeed, it wasn't required). Not sure if any of this is going to help anyone else but just in case, this was my fix.

Errors using MailChimp API adding email address to list

I am trying to add email addresses to my mailchimp mailing list but am getting an error saying
Access Denied
You don't have permission to access "http://us9.api.mailchimp.com/3.0/lists/######/members/" on this server.
Reference #18.1e89655f.1546511382.213522b5
I have just created the API key and haven't done much with MailChimp before. I think the list ID is correct, I just grabbed it from the URL of my actual list in a browser https://us9.admin.mailchimp.com/lists/members/?id=######
<?php
$email = '#########.##';
$authToken = '#######################-us9';
$email_list = '######';
$postData = array(
"email_address" => "$email",
"status" => "subscribed",
"merge_fields" => array(
"NAME"=> "",
"PHONE"=> "")
);
$ch = curl_init('https://us9.api.mailchimp.com/3.0/lists/'.$email_list.'/members/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: apikey '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
var_dump($response);
?>
The API list ID is not the same as the browser one. (Don't ask me why). To find out the API list ID, use the API Playground. https://developer.mailchimp.com/
I think the IP of your server is blacklisted for Mailchimp. You should contact Mailchimp and ask if the server IP is blacklisted for them.
It was a transient error for me, which went away after a couple of minutes. If it doesn't then somehow Akamai has probably blacklisted you and you need to contact Mailchimp (as Akamai does not handle Mailchimp specific requests directly).
If you look in the response headers, it says Server: AkamaiGHost, which I assume is the proxy Mailchimp is using. Also the response is text/html, which does not match Mailchimp's own documented error formats–another sign that it is the proxy blocking you and not Mailchimp itself.

GET works but POST doesn't for silent login

We have 2 systems one in PHP and one in asp.net which currently require separate logins even though both use the same username/password information.
As a quick (and temporary) fix I thought I might be able to amend the PHP login page to pass the login details to the asp.net page behind the scenes so the user could be logged in automatically to both systems rather than having to enter their credentials again when navigating to a different page.
This works fine when I use a GET to pass the parameters but of course the GET parameters including the password get stored in the server log which is not a good idea.
So I would like to use POST instead, but I can't get it to work. I used the CURL-less method in How do I send a POST request with PHP? (code below) and it appears to work but the asp.net login process creates secure cookies and while they are stored if I GET the page they are not being stored when I POST to it instead.
$url = 'https://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
I have tried something similar with CURL in the past so I know that CURL creates it's own browser context but I thought a straight POST request would work, however it seems to be behaving much the same as CURL.
Is there some way to get this to work or do I have a fundamental misunderstanding of how POST works? If so could somebody point me at a good explanation.

Update facebook status using php

I know it's a very old question.But i really bound to ask the same question again.How can i update my status using PHP?Because i find several solutions in google and stackoverflow but non of that currently works.May be the cause of facebook up gradation process or anything else.
I chk:
1) http://360percents.com/posts/php-curl-status-update-working-example-sep-2010/
2) http://www.barattalo.it/2010/03/01/php-curl-bot-to-update-facebook-status/
But unfortunately non of the solution is working.So, is their any kind heart who can help me to update the facebook status using php easily?i shall be very much glud if anybody pls give any working solution. Regards---riad
Well, I've wrote a tutorial about posting to the user's wall: How To: Post A Message On The User Wall Using Facebook Graph API.
$args = array(
'message' => 'Hello from my App!',
'link' => 'http://www.masteringapi.com/',
'caption' => 'Visit MasteringAPI.com For Facebook API Tutorials!'
);
$post_id = $facebook->api("/me/feed", "post", $args);
Notes:
I'm using the PHP-SDK
You need the publish_stream permission
Check out this answer
What about checking directly the Facebook API ?
http://developers.facebook.com/docs/
Check the "Graph API"
The Graph API is the core of Facebook Platform, enabling you to read and write data to Facebook. It provides a simple and consistent view of the social graph, uniformly representing objects (like people, photos, events, and pages) and the connections between them (friendships, likes, and photo tags).
I wrote this code im my blog completely pl check that in the following link
http://scriptime.blogspot.in/2012/12/facebook-status-updates-using-php-sdk.html
here i am giving samll code
$status = $_POST['status'];
$facebook_id = $userdata['id'];
$params = array(
'access_token' => $access_token,
'message' => $status
);
$url = "https://graph.facebook.com/$facebook_id/feed";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true
));

Categories