Google Maps API Key Error - php

I'm trying to connect my PHP script to the google maps API using CURL it connects fine but when i pass the API key it says that it is not valid, below is some of the code I'm using to get stats...
<?php
$url = 'https://maps.google.com/maps/api/geocode/json?address={ADDRESS}&sensor=false&key={MY_KEY}';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($cURL);
curl_close($cURL);
?>
I have tried configuring my API keys for both server (set by IP address) and browser (set by Domain Name) on the Google API page at https://code.google.com/apis/console/
The problem that I'm having is every time i send a request i get a return JSON message saying:
stdClass Object (
[error_message] => This site or IP is not authorized to use this API key.
[results] => Array (
)
[status] => REQUEST_DENIED
)
If i try to goto the url in a web browser on the computer in question
https://maps.google.com/maps/api/geocode/json?address=The%20White%20House,%20Washington&sensor=false&key={MY_KEY} i get the same problem:
{
"error_message" : "This site or IP is not authorized to use this API key.",
"results" : [],
"status" : "REQUEST_DENIED"
}
Server type:
O/S: Windows Server 2008 R2 x64
Server: UwAmp 2.2.1
PHP: 5.4.15
MySQL: 5.6.11
Thanks in advance for any help!

The API key is not required for your use of google map API. It is a confusing error message that google replies with in this case. Just remove from your URL the '&key={MY_KEY}', and you should be fine.

You could create table location in your mysql.every time you send a request .insert it to databse. after that you can count request by using count record in your database.i used this solution

Related

Spotify web API - 401 Permissions missing

I'm trying to build a spotify web player using the spotify web API.
I registered my Application on spotify and whitelist the callback URL.
Then the authorization process works fine. I receive the token for make others requests.
But when I try to make a simple currently-playing request,
https://developer.spotify.com/web-api/get-the-users-currently-playing-track/
I receive
Array ( [error] => Array ( [status] => 401 [message] => Permissions missing ) )
the PHP code is:
session_start();
$req = $_SESSION['token_type'] . " " . $_SESSION['token'];
$headers_after_token = array(
"Accept: */*",
"Authorization: " . $req);
$url="https://api.spotify.com/v1/me/player/currently-playing";
echo "<br>REQ-currently-playing: ".$req."<br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_after_token);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
echo "<br><br>";
print_r($response);
the $_SESSION['token_type'] contains "Bearer" as mentioned in the API endpoint-reference
https://developer.spotify.com/web-api/endpoint-reference/
the $_SESSION['token'] contains the token retrieved after the authentication process.
Both are well formed thanks to the echo "<br>REQ-currently-playing: ".$req."<br>"; I can see that the 2 variables are set.
I'm using XAMPP v3.2.2 for deploy php pages.
To be able to fetch the current playing, you need to add the scope user-read-currently-playing and/or user-read-playback-state when you authorize a user.
With this kind of authorization, a user needs to agree what your app can do on their behalf. Some things are included by default, but some things (just like this) needs extra permissions from the user.
If you see in the documentation that it says that a function needs "this and that" scope, you need to add it to the authorization.

Unable to connect to Microsoft Dynamics CRM with PHP and Curl

I am trying to use PHP and CURL to connect to Microsoft Dynamics API so I can read client data from the CRM. The API guide can be found here:
https://msdn.microsoft.com/en-gb/library/mt593051.aspx
I've been into the Azure portal and set up a new application, and it gives me the credentials to use (client id, secret, etc.) and the url end points. Using these credentials I am able to successfully connect to the CRM and retrieve a bearer access token, but I am unable to get any further.
When I attempt to use the token to return data I receive the below error message:
HTTP Error 401 - Unauthorized: Access is denied
My assumption would be that I must be passing the token correctly?
My code is below.
<?php
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay)
$credentials = array(
'grant_type'=>'client_credentials',
'username'=>'xxxxxxxx',
'password'=>'xxxxxxxx',
'client_id'=>'xxxxxxxxxxxx',
'client_secret'=>'xxxxxxxxxx',
);
$urlSafeCredentials = http_build_query($credentials);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);
// A BEARER access token is successfully returned
$token = $result->access_token;
// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied)
$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
print_r($response); // 401 Unauthorized ?!
?>
As far as I can tell there is nothing else to configure at the back end, any help would be much appreciated.
Based on the parameters to acquire the token, you were mixing the client credentials flow and resource owner password flow and lack of resource parameter.
The client credentials flow requires parameters grant_type,client_id,client_secret,resource and the value of grant_type is client_credentials.
The resource owner password credentials flow requires grant_type,client_id,client_secret,username,password,resource and the value of grant_type is password.
If you were using the client credentials flow, you can refer this blog for acquiring the token. And if you were using the resource owner password, you can refer this thread.
Details about difference of the flows in Oauth 2 please refer RFC 6749.
I wrote a lightweight PHP class for working with Dynamics 365 online Web API. You can find it here.
BTW in your code you should try "password" inside the grant_type instead of "client_credentials"

How to publish a post on Facebook Page using CURL and without using SDK in PHP

I am developing a PHP project that needs Facebook integration. So before I do it on code , I am testing it using Facebook Graph API explorer tool (https://developers.facebook.com/tools/explorer). What I am doing now is.
1st Step
Get the user access_token by using the button at the top left.
2nd Step
Make a GET request to "me/accounts" to get the page token and page id.
3rd Step
Make a POST request to "{page_id}/feed" with the fields message={message} and access_token={page_token}
It worked perfectly and posted on my Facebook Fan Page. But when I try to replace the "3rd Step" with PHP code like this
$data['message'] = "my message";
$data['access_token'] = $page_access_token; //page token from 2nd step
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://graph.facebook.com/{page_id}/feed');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
$resp = curl_exec($ch);
curl_close($ch);
$data_resp = json_decode($resp);
print_r($data_resp);
It show me this error.
stdClass Object ( [error] => stdClass Object ( [message] => (#200) Permissions error [type] => OAuthException [code] => 200 ) )
I set the permissions of manage_pages,publish_pages,publish_actions
Passing an array for CURLOPT_POSTFIELDS means cURL will send the request as Content-Type multipart/form-data – but you want application/x-www-form-urlencoded instead.
Use http_build_query on your $data array, and use the resulting string for CURLOPT_POSTFIELDS.
Have a look at the docs at
https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed#publish
Permissions
A user access token with publish_actions permission can be used to publish new posts on behalf of that person. Posts will appear in the voice of the user.
A page access token with publish_pages permission can be used to publish new posts on behalf of that page. Posts will appear in the voice of the page.
You should run the used access token through
https://developers.facebook.com/tools/debug/accesstoken/
to see whether it contains the appropriate permission(s).

LinkedIn oAuth 2 issue with client_id parameter

I'm trying to create an application on LinkedIn that's using OAuth2 for authentication and am running into some errors. The client runs on an iOS device and uses an oAuth library to make a call to LinkedIn's servers. My iOS client successfully gets the authorization_code. The client application then passes that authorization_code to my server, which attempts to connect to linkedIN again and get the access_token. This step consistently fails, I get the following error from LinkedIn: {"error":"invalid_request","error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : client_id"}
My POST method to LInkedIN does contain the client_id, it only contains it once, and I've triple checked the values for all the parameters, they are correct. I've also reset the access multiple times from https://www.linkedin.com/secure/settings and I've even created additional applications on LinkedIn, I keep getting the same result.
I've checked other responses, such as this one: unable to retrieve access token linkedin api and tried the suggestions: revoke keys, request new keys etc, nothing seems to be working.
Here is my server code:
$tokenURL = 'https://www.linkedin.com/uas/oauth2/accessToken';
$redirectURL = 'https://staging.textsuggestions.com';
$clientId = '75a4ezqh741sup';
$clientSecret = 'XXXXXXXX';
$tokenArguments = array("grant_type" => "authorization_code",
"code" => $code,
"redirect_uri" => $redirectURL,
"client_secret" => $clientSecret,
"client_id" => $clientId);
// send the request to the server getting data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $tokenArguments);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!empty($response["error"])) {
error_log("Error is: " . $response["error"]);
exit (0);
} else {
// no error, get the access_token and do stuff with it
$timeout = $response["expires_in"];
$access_token = $response["access_token"];
}
Ok I realized what I was doing wrong, the client application library that I was using was generating the full access token (not the auth code). So I was trying to pass in the access token in the place of the auth code. The error that I was getting from Linked In was certainly misleading and I should have checked the client library I was using more carefully.
Have you tried to check your code against this code sample?
https://developer.linkedin.com/documents/code-samples
Check that the POST headers include "Content-Type": "application/x-www-form-urlencoded".

GCM Push Server side, which API Key to use?

I'm a bit confused. I have a GCM PHP server side app server that uses a key from Google Developer Console. I can create Android key as per the instructions given in getting started guide here, or I can create a browser key, server key or OAuth key.
Can somebody tell which key I should use on the server side PHP when sending messages via GCM to Android devices?
This is the function that sends the message to GCM
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
Obviously the XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX string is replaced by my API_KEY in the original code.
p.s: My android is registering fine with the GCM, I have the registration id sent to server as well, it's the send message post request that always returns 401 Unauthorized, I'm afraid I'm using a wrong key?
p.s2: I've tried all 3 sort of API_KEYs without success.
Solved
I was concentrating on Android or Server API_KEY but I actually had to use browser key.
Moreover, to test initially I removed all IP addresses from white listing to make sure that's not the factor playing it's role.
Now I have the push service working with above code using Browser API Key and IP restriction in place for white listing.
Cheers :)
Be sure you include the 'Authorization' header with value 'key=APIKEY'.
ApiKey can be either server key or browser key.
If you define IP whitelist for server key, you can only send messages from the specified IPs.

Categories