Google Translate API returns 403 (PHP) - php

The question is about Google Translate API
I set a project and turn the billing on (with some money on the account)
I created a key for server app (also tryed to use a browser key) and added all 3 IPs I have (home and 2 servers)
What I see:
It does work in apis-explorer and in a browser address bar (https://www.googleapis.com/language/translate/v2/detect?q=an%20english%20text&key=MY_KEY)
It returns 403 error if I trying to get the same URL from PHP code:
$apiKey = 'MY_KEY';
$url = 'https://www.googleapis.com/language/translate/v2/detect?q=an%20english%20text&key=' . $apiKey . '';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
curl_close($handle);
print_r(json_decode($response, true));
thre result:
Array (
[error] => Array (
[errors] => Array (
[0] => Array (
[domain] => usageLimits
[reason] => ipRefererBlocked
[message] => There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.
[extendedHelp] => https://console.developers.google.com
))
[code] => 403
[message] => There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.
))
I checked the IPs dozens of times, tryed to use browser key with allowed URL as referer.
Out of ideas.

Thanks for admins, they helped to figure out.
By default - curl using our ipv6 address...
So we have three options here:
curl_setopt($handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
add ipv6 address to allowed list
Turn ipv6 off forthe server
I had to be more attentive and remember about ipv6 :-)

I am told that this is fixed by simply removing all Ip's from the edit allowed IP's option. This makes it so that it is less secure, but it will accept all IP's after that.

Related

Gettint 401 Error in Server Side gcm PHP Script [duplicate]

I am using GCM services to push information from server. If I use browser key it shows the sucess mesaage as : {"multicast_id":4849013215736515938,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1348742583011905%2adac3a0f9fd7ecd"}]}
but i did not get any notifications on device.
And if I use server key it shows Unauthorized Error 401. My code is shown below:
$apiKey = "xxxxx";
$registrationIDs = array("xxxxxxxx");
$message = "testing Process";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array("message"=>$message),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );
$result = curl_exec($ch);
if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); }
curl_close($ch);
echo $result;
Please help me for this issue. Thanks in advance.
Did you whitelist the IP of your server? This is not necessary by default for the browser key, but it is for the server key.
You can check it here:
https://code.google.com/apis/console/#project:[YOUR PROJECT NUMBER]:access
Another answer already suggested whitelisting the IP address, which seems kind of obvious. What fixed it for me was whitelisting my IPv6 address. That was the key! I hope this helps someone else.
I tried everything in this thread, and still no luck.
So I checked enabled APIs (APIs and Auth -> APIs, Enabled APIs), and realised that I had enabled Google Cloud Messaging for Chrome not Google Cloud Messaging for Android. As soon as I enabled the latter, it worked immediately.
Double check you have the right API enabled!
As many people wrote, you have to whitelist your server IPV4 and IPV6. If you want only IPV4, add this to your curl php init:
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
use browser key using option create new browser key and use this key in your code.
https://code.google.com/apis/console/?pli=1#project:42053154xxxx:access
I used to put to the
$apiKey = "xxxxx"
like project number (project id) which i put to Android Client app, but i have been wrong in server have to be appkey from google cloud console, (where you activate Google Cloud Messaging for Android)
ProjectXXX -> APIs & auth -> Registered Apps -> Web App -> Server Key
-> Api key
in my case i had there default project 'Service Account-project' on platform: 'Web' but there was just Hosted Application section and no evidence about any api key.
but when i create new Web Apps called 'My app' which contained 4 sections OAuth 2.0 Client ID, Certificate, Server Key, Browser Key i finaly find the api key;-)
may just me who don't know it but i believe this answer could also helps to some one
for me the problem was that you have to enable the api. Having an API set up is not enough. Check that Google Cloud Messaging for Android appears on the enabled APIs in APIs-> enabled APIs.
If its not click the API library tab in APIS and enable it.
\
If I am not mistake your APIKEY needs to be base64 encoded.
Also try var_dump($results) to see if you get information then.
Looking at the code, I recognise this is from a php-gcm sample posted somewhere online. Its quite nice and I can assure you that both browser keys and whitelisted ip's (not IPV6 or bas64 apikey) work.
The reason why no message is shown is because the send notification function you're using 'data' => array("message"=>$message)
targets a key of "message", this is what you must pass to your pending intent i.e
notification.setLatestEventInfo(context, title, message, intent);
This will enable the intent to read the message contained under this key..the message itself is obtained from the GCMIntentService method pasted below:
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("message");
Log.d(TAG, "The intent contains: " + intent.getExtras());
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
Here is the problem: I was using 2 servers, 1 staging and the other the production server. For my staging server, which was hosted using digital ocean, I entered the inet address in the Key for server applications allowed IP addresses, and it worked just fine.
However, it failed when I changed to my inet address from my production server. Instead, I had to use
inet6 addr: /64 Scope:Global for this to work. To get the value if you encounter the same issue, just enter ifconfig, and find the above entry. Enter that value in the allowed IP addresses and it will work fine.
You must have different project than the default one. Create a project & then create a key. Don't use default project.
Had this trouble, I was using GCM (Google cloud messaging). But after Sep 2016, the server key on the GCM will not work, you have to use FCM (firebase cloud messaging). Create new server keys only in the Firebase Console using the Cloud Messaging tab of the Settings panel. I went over to the firebase console console.firebase.google.com (I had not used it yet) and it asked me to import my project. Suddenly there was this new server key back on the GCM console. If using GCM, use the "legacy key" you see listed there.
Make sure you enabled your API Survery Key!
We are looking for solutions in days. More specifically, add this curl option: curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

YouTube Analytics API PHP: usageLimits accessNotConfigured

I am using the [Google Analytics API PHP] by wanze. I was able to set up authentication (using web auth only) and everything and I stored the token in a session. On another page, I use this code to find all the accounts the user logged in with.
session_start();
include('GoogleAnalyticsAPI.class.php');
$ga = new GoogleAnalyticsAPI();
$ga->auth->setClientId('replaces'); // From the APIs console
$ga->auth->setClientSecret('replaces'); // From the APIs console
$ga->auth->setRedirectUri('replaced'); // Url to your app, must match one in the APIs console
// Get the Auth-Url
$url = $ga->auth->buildAuthUrl();
// Set the accessToken and Account-Id
$ga->setAccessToken($_SESSION['accessToken']);
$ga->setAccountId('ga:xxxxxxx');
// Load profiles
$profiles = $ga->getProfiles();
print_r($profiles);
$accounts = array();
foreach ($profiles['items'] as $item) {
$id = "ga:{$item['id']}";
$name = $item['name'];
$accounts[$id] = $name;
}
// Print out the Accounts with Id => Name. Save the Id (array-key) of the account you want to query data.
// See next chapter how to set the account-id.
print_r($accounts);
I this returned:
Array
(
[http_code] => 403
[error] => Array
(
[errors] => Array
(
[0] => Array
(
[domain] => usageLimits
[reason] => accessNotConfigured
[message] => Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.
[extendedHelp] => https://console.developers.google.com
)
)
[code] => 403
[message] => Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.
)
)
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>/home3/chalzzy/public_html/dashboard/dashboard.php</b> on line <b>21</b><br />
Array
(
)
I see in a lot of places that I need to remove or set all refers in a "Referrals" section in the console but I can't seem to fins that in the new or old console. If it is there and I can't find it, can you please give me a url or a screenshot?
Also, these are all the APIs I have installed for this project:
Thanks in advance,
Ben
Also, let me know if you need more details!
Hey (I'm sorry it was a very stupid question),
What you have to do is add to your APIs list "Analytics API" in the Developers Console.

Google GCM server returns Unauthorized Error 401

I am using GCM services to push information from server. If I use browser key it shows the sucess mesaage as : {"multicast_id":4849013215736515938,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1348742583011905%2adac3a0f9fd7ecd"}]}
but i did not get any notifications on device.
And if I use server key it shows Unauthorized Error 401. My code is shown below:
$apiKey = "xxxxx";
$registrationIDs = array("xxxxxxxx");
$message = "testing Process";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array("message"=>$message),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );
$result = curl_exec($ch);
if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); }
curl_close($ch);
echo $result;
Please help me for this issue. Thanks in advance.
Did you whitelist the IP of your server? This is not necessary by default for the browser key, but it is for the server key.
You can check it here:
https://code.google.com/apis/console/#project:[YOUR PROJECT NUMBER]:access
Another answer already suggested whitelisting the IP address, which seems kind of obvious. What fixed it for me was whitelisting my IPv6 address. That was the key! I hope this helps someone else.
I tried everything in this thread, and still no luck.
So I checked enabled APIs (APIs and Auth -> APIs, Enabled APIs), and realised that I had enabled Google Cloud Messaging for Chrome not Google Cloud Messaging for Android. As soon as I enabled the latter, it worked immediately.
Double check you have the right API enabled!
As many people wrote, you have to whitelist your server IPV4 and IPV6. If you want only IPV4, add this to your curl php init:
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
use browser key using option create new browser key and use this key in your code.
https://code.google.com/apis/console/?pli=1#project:42053154xxxx:access
I used to put to the
$apiKey = "xxxxx"
like project number (project id) which i put to Android Client app, but i have been wrong in server have to be appkey from google cloud console, (where you activate Google Cloud Messaging for Android)
ProjectXXX -> APIs & auth -> Registered Apps -> Web App -> Server Key
-> Api key
in my case i had there default project 'Service Account-project' on platform: 'Web' but there was just Hosted Application section and no evidence about any api key.
but when i create new Web Apps called 'My app' which contained 4 sections OAuth 2.0 Client ID, Certificate, Server Key, Browser Key i finaly find the api key;-)
may just me who don't know it but i believe this answer could also helps to some one
for me the problem was that you have to enable the api. Having an API set up is not enough. Check that Google Cloud Messaging for Android appears on the enabled APIs in APIs-> enabled APIs.
If its not click the API library tab in APIS and enable it.
\
If I am not mistake your APIKEY needs to be base64 encoded.
Also try var_dump($results) to see if you get information then.
Looking at the code, I recognise this is from a php-gcm sample posted somewhere online. Its quite nice and I can assure you that both browser keys and whitelisted ip's (not IPV6 or bas64 apikey) work.
The reason why no message is shown is because the send notification function you're using 'data' => array("message"=>$message)
targets a key of "message", this is what you must pass to your pending intent i.e
notification.setLatestEventInfo(context, title, message, intent);
This will enable the intent to read the message contained under this key..the message itself is obtained from the GCMIntentService method pasted below:
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("message");
Log.d(TAG, "The intent contains: " + intent.getExtras());
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
Here is the problem: I was using 2 servers, 1 staging and the other the production server. For my staging server, which was hosted using digital ocean, I entered the inet address in the Key for server applications allowed IP addresses, and it worked just fine.
However, it failed when I changed to my inet address from my production server. Instead, I had to use
inet6 addr: /64 Scope:Global for this to work. To get the value if you encounter the same issue, just enter ifconfig, and find the above entry. Enter that value in the allowed IP addresses and it will work fine.
You must have different project than the default one. Create a project & then create a key. Don't use default project.
Had this trouble, I was using GCM (Google cloud messaging). But after Sep 2016, the server key on the GCM will not work, you have to use FCM (firebase cloud messaging). Create new server keys only in the Firebase Console using the Cloud Messaging tab of the Settings panel. I went over to the firebase console console.firebase.google.com (I had not used it yet) and it asked me to import my project. Suddenly there was this new server key back on the GCM console. If using GCM, use the "legacy key" you see listed there.
Make sure you enabled your API Survery Key!
We are looking for solutions in days. More specifically, add this curl option: curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

Windows Azure Authentication for Bing Search in PHP

I am trying to perform a Bing Search by using the Windows Azure Marketplace API, I have downloaded their guide and sample code. The code prepares a HTTPS request with basic authentication, however I am constantly getting the following error:
Warning: file_get_contents(https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query=%27washburn%27&Adult=%27Off%27&$top=50&$format=Atom): failed to open stream: Connection refused
The php code (from Microsoft's document):
$context = stream_context_create(array(
'http' => array(
'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey.":".$accountKey)
)
));
Does anyone know what is causing the error please? I have correctly set the $accountKey and I tested it in a browser. What puzzles me a little is 127.0.0.1:8888 and also base64_encode($accountKey.":".$accountKey) , how come you need the $accountKey both before and after the : while when using a browser you are supposed to leave the username blank and just input the account key into the password field?
I have solved it and here is what I have found for future people that would be doing the same thing:
I commented out the line where it says:
'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
and also set base64_encode("ignored:".$accountKey) instead
Base on what I read on MSDN, the username part is said to be ignored, so it shouldn't matter what value it is. I was thinking perhaps the length or the special characters in the key screwed things up so I replaces it with ignored (or anything really).
That did the trick and I can parse the returned JSON data. Good luck!

Domain API Loop

How can I perform the following with this API?
Form is setup in PHP for registered user to enter domain name
On submit..
Check if domain is available >
If NO > output to XML > run the loop again in 5 minutes
If YES > output to XML > go ahead and purchase (register) the domain > end loop
Thank you!
Sample API code
<?php /** * Set the API URL */ $sApiUrl = "https://www.apiurl.com/";
/** * Set POST Parameters */ $aParams = Array(
'uid' => "--USERNAME--", // Username
'pw' => "--APIKEY--", // API Key
'command' => "querydomain", // Command to Rum
'sld' => "sampledomain", // Main part of the Domain
'tld' => "com"); // Domain Extension
/** * Run the cURL command */
$oCurl = curl_init(); curl_setopt($oCurl, CURLOPT_URL, $sApiUrl);
curl_setopt($oCurl, CURLOPT_POST, 1);
curl_setopt($oCurl, CURLOPT_POSTFIELDS, $aParams);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
$sResponse = curl_exec($oCurl); curl_close($oCurl);
/** * Turn results into Simple XML Object */
$oOutput = new SimpleXmlElement($sResponse);
/** * Debugging output, so we can see what we just got */
print_r($oOutput);
?>
API Commands
check Checks whether a domain name is available for registration.
purchase Registers a new domain name.
transfer Requests a domain transfer to registrar.
extend Extends (renews) domain registration.
changepassword Changes the domain password.
sendpassword Send domain password to domain owner.
contacts Changes domains contacts.
querydomain Returns detailed information about the domain.
sendepp Sends gTLD epp key to domain owner.
refillaccount Refills your reseller account with funds.
changedomainns Changes domains name servers.
sendtransferemail Sends transfer authorisation request to domain owner.
addchildns Add child name server to domain.
updatechildns Update details for child name server.
removechildns Remove child name server from domain.
pushdomain Push domain to another registrar reseller.
getdnsrecords Get domain name server records for a domain.
enablednsdomain Create DNS domain service for domain.
adddnsrecord Add new DNS record to domain.
updatednsrecord Update DNS record for a domain.
removednsrecord Remove DNS record from a domain.
updatednssoa Update DNS SOA record for a domain.
disablednsdomain Destroy DNS domain service for a domain.
getmailrecords Get mail forwarding records for a domain.
addmailforwarder Add a mail forwarder to a domain.
removemailforwarder Remove a mail forwarder from a domain.
updatemailforwarder Update the details of a Mail Forwarder for a domain.
geturlrecords Get URL Forwarding records for a domain.
addurlforwarder Add a URL Forwarding record to a domain.
updateurlforwarder Update a URL Forwarding record for a domain.
removeurlforwarder Remove a URL Forwarding record for a domain.
getreglock Get registry lock details for a domain.
setreglock Set a registry lock for a domain.
updatecontact Update an address book entry.
getapiinfo Get information about the Domain System API.
transferout Push a domain name to another registrar, given their tag.
Outputted XML from example above
SimpleXMLElement Object
(
[results] => SimpleXMLElement Object
(
)
[errors] => SimpleXMLElement Object
(
[error] => SimpleXMLElement Object
(
[domain] => SimpleXMLElement Object
(
[name] => google.com
[status] => SimpleXMLElement Object
(
[code] => 211
[text] => Unavailable
[description] => The domain name you queried has been registered through another registrar.
)
)
)
)
[errorcount] => 1
[exectime] => 0.399 second(s)
[enviroment] => live
[version] => 2.3.9 beta
)
I can see what it is you are trying to do. However which part in particular are you having issues with? It looks as though you have the API already. Is it not functioning correctly?
Do you need help in writing the PHP to do your 'Yes'/'No' step above?
And why are you "checking again in 5 minutes"?

Categories