PHP OpenWeather - php

Alright so I am having some troubles understanding how to use the open weather API.
I have tried using it as
<?php
$request = file_get_contents('http://api.openweathermap.org/data/2.5/forecast/city?id=myidblablabla'); //example ID
$jsonPHP = json_decode($request);
echo $jsonPHP->city;
?>
But I get an error saying
Catchable fatal error: Object of class stdClass could not be converted
to string in
Now there is 1 more question that I have to ask, how do I get certains City Temperature, humidity etc? From the code I received I get only Moscow

To simplify it, you can also transform the json into array instead.
$jsonPHP = json_decode($request,true);
Now let's discuss it briefly. According to the documentation (http://openweathermap.org/current),
Note also that I've never used this API before. I'm just trying to help here.
If you hit api.openweathermap.org/data/2.5/weather?lat=35&lon=139
It responds as
{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}
Now assuming you want to take the weather and humidity , it just :
weather :
echo $jsonPHP["weather"][0]["id"];
humidity:
echo $jsonPHP["main"]["humidity"];
Note also that, If you hit http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139 and get the responds as
{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}
For the case, they've explained here :
http://openweathermap.org/faq#error401 which is :
Q: API calls return an error 401
A: Starting from 9 October 2015 our
API requires a valid APPID for access. Note that this does not mean
that our API is subscription-only now - please take a minute to
register a free account to receive a key.
We are sorry for inconvenience but this is a necessary measure that
will help us deliver our services to you faster and more reliably.
For FOSS developers: we welcome free and open source software and are
willing to help you. If you want to use OWM data in your free software
application please register an API key and file a ticket describing
your application and API key registered. OWM will review your request
lift access limits for your key if used in open source application.

Related

How do we call fetchVerificationOptions in the Google Business Verification API with the Google API PHP SDK?

I am currently working with various Google APIs. I already have approved access to the Google Business API and am successfully making several calls to its endpoints with the PHP SDK; even calls to some of the endpoints in the Business Verification API. However, when I make a request to fetchVerificationOptions of a defined location, I get a 400 error.
Google\Service\Exception
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"errors": [
{
"message": "Request contains an invalid argument.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest"
}
]
}
}
I have verified the location being passed in is correct and in the format of "locations/<LOCATION_ID>". I am using this same key in many other successful calls.
I've read all the documentation I can find on this subject many many times. The error makes me think the data I am sending in is wrong, but the documentation is pretty clear on what is expected - a language code and, optionally, a context. In my current case, the location is a CUSTOMER_LOCATION_ONLY type of business and requires a PostalAddress object be provided in this request via the context. The SDK makes this seem even easier with objects for each piece of the puzzle.
Here is my relevant PHP code:
$options = new FetchVerificationOptionsRequest;
$options->languageCode = 'en-US';
$context = new ServiceBusinessContext;
$context->setAddress($postalAddress);
$options->setContext($context);
$verificationOptions = GoogleBusinessProfileApi::getVerificationService()->locations->fetchVerificationOptions($locationName, $options);
I have verified that $postalAddress in the code above is an instance of Google\Service\MyBusinessVerifications\PostalAddress holding valid address details.
I have verified that $locationName in the code above holds the correct value; my location ID in the format of "locations/<LOCATION_ID>".
GoogleBusinessProfileApi::getVerificationService() in the code above returns an instance of Google\Service\MyBusinessVerifications with my Google Client and all the authentication stuff taken care of. I use this method for all of my interactions and they work perfectly normal. Plus, the error doesn't indicate there is an issue with this part.
It is also worth noting that on my Google API Dev Console, I can see these requests coming in and ending with a 400 response. Though, that is as far as the metrics seem to go. I cannot find any deeper, more detailed information about the requests.
I am looking for anything - direction, ideas, thoughts. Anyone else deal with this before? Am I missing something obvious? Is this an issue with my code or the API itself? Anyone know how I can dig deeper on the Google console for these errors?
Thanks!
The Solution:
Set PostalAddress sublocality to null.
The Details:
With the help of a colleague, we figured out what was going on. I changed the code to call the older, deprecated version of the API. This returned a much more useful error message stating that the US doesn't use sublocalities in their addresses. I was setting that on my PostalAddress object, so I changed it to always be null and the request worked - on both the old and new API.
There were a lot of frustrating points around this problem.
Error messages. The response from the "new and improved" API should be telling me as much if not more than the older version.
Documentation. No where that I could find stated anything about the sublocalities in the US for this particular request.
Help Available. At the time of writing any of this, googling anything about this topic returned essentially nothing.
Sublocalities. The way my system is set up is we actually use Google's Place Lookup to get a valid PostalAddress to ensure the data we send them is valid. In this case, the address we used was returned to us from Google... with a sublocality. The sublocality held the county name; something we do use in the US. So there was even less of a reason to think that would have been the problem. While I disagree with the accuracy of the error message, I really needed that to understand what the issue was.
While this doesn't seem to be a big issue on the web right now, I do hope that this can help someone else avoid some wasted time someday.
~Cheers~

Google DFA (DoubleClick for Advertisers) APIs v1.20

As in the subject, I'm working with the Google DFA (DoubleClick for Advertisers) APIs v1.20 and I'm trying to get the list of all my Advertisers.
I didn't found any client library for PHP and DFA APIs v1.20.
The connection is established by SOAP, as requested by Google API docs (https://developers.google.com/doubleclick-advertisers/docs/getting_started)
The authentication process seems to work correctly but the list request return the following error:
WSDoAllReceiver: security processing failed; nested exception is: org.apache.ws.security.WSSecurityException: General security error (WSSecurityEngine: Callback supplied no password for: MyUsername)
To build the header I'm using the following code
$advertiserService = new SoapClient($advertiserWsdl, $options);
// Set headers.
$headers = array(DfaHeadersUtil::createWsseHeader($username, $authToken),
DfaHeadersUtil::createRequestHeader($namespace, $applicationName));
Where the DfaHeadersUtil is a class into the file DfaHeadersUtil.php provided by Google as "header creator".
Is there anybody could help me with this?
Thank you in advance,
Mauro
SOLVED:
The problem was given by not sufficient permissions assigned by the admin to my user..
Easy solution that made me waste half week.. :(
What I learnt:
Occam's razor: "the simplest explanation is usually the correct one"..
Next time.. check the permissions :)
Thank you

UPS API PHP - End point URL

I have downloaded a PHP SDK for the UPS API. I have the following code and have no idea what an end point URL is. The documentation does not provide any information on what this is.
//Configuration
$access = "0C81234564C2567";
$userid = "leannetest";
$passwd = "456hththd8hf";
$accessSchemaFile = "schemas/AccessRequest.xsd";
$requestSchemaFile = "schemas/RateRequest.xsd";
$responseSchemaFile = "schemas/RateResponse.xsd";
$endpointurl = 'add URL here';
$outputFileName = "XOLTResult.xml";
Can anyone help?
Endpoint url explaination in the UPS document. it consists of four parts which are explained below.
For example if we are going to use "Rate" service than our urls should be as below.
Testing and integration URL : https://wwwcie.ups.com/ups.app/xml/Rate
Production URL : https://onlinetools.ups.com/ups.app/xml/Rate
As per the documentation if we devide the url in four parts all of them are as listed below.
Protocol : https
Name of server : wwwcie.ups.com (testing) OR onlinetools.ups.com (production)
Path of service : ups.app/xml/Rate
name of the service : Rate OR Ship OR QVEvents
I just replied to explain UPS endpoint url in detail so it might help
An API endpoint "defines the address or connection point to a Web service. It is typically represented by a simple HTTP URL string". So basically, the endpoint URL is the URL of the web service that are you attempting to interact with.
SOURCE:
http://en.wikipedia.org/wiki/Web_Services_Description_Language#Objects_in_WSDL_1.1_.2F_WSDL_2.0
EDIT: It appears from the documentation that the Rate webservices endpoint URL is https://wwwcie.ups.com/webservices/Rate.
SOURCE:
UPS. (January 2, 2002). Rating Package Web Services Developers Guide. Section 1.9.3 Server Availability Check. Accessed in Rating API found on this page: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
The shipping endpoint url is:
https://wwwcie.ups.com/webservices/Ship
In case anyone needs it, since it's not documented in their developers kit.
Indeed the documentation is poor but with a little google trick I got the list of all the endpoint URLs
Type in google search:
site:https://onlinetools.ups.com/ups.app/xml/
In this way, it will show you all the endpoints.
Note: Do not use the sandbox URLs because they don't work at all :(
Anyway, here is the list:
https://onlinetools.ups.com/ups.app/xml/TimeInTransit
https://onlinetools.ups.com/ups.app/xml/License
https://onlinetools.ups.com/ups.app/xml/QVEvents
https://onlinetools.ups.com/ups.app/xml/Register
https://onlinetools.ups.com/ups.app/xml/AV
https://onlinetools.ups.com/ups.app/xml/ShipAccept
https://onlinetools.ups.com/ups.app/xml/Void
https://onlinetools.ups.com/ups.app/xml/XAV
https://onlinetools.ups.com/ups.app/xml/Track
https://onlinetools.ups.com/ups.app/xml/Rate
https://onlinetools.ups.com/ups.app/xml/ShipConfirm
https://onlinetools.ups.com/ups.app/xml/LabelRecovery
I hope this help

Problem in Google Translater API

I am doing Language translation using Google Translater API.
Sometimes I am getting following error.
Fatal error: Uncaught GTranslateException: [0]: Unable to perform Translation:Suspected Terms of Service Abuse. Please see http://code.google.com/apis/errors thrown in C:\xampp\htdocs\MyProjectName\public\function\GTranslate.php on line 263
Can anybody help me to fix this problem.
Thanks in advance.
Kanji.
Sign up for google API Key at https://code.google.com/apis/console/ as mentioned earlier.
require_once("GTranslate.php");
try{
$gt = new Gtranslate();
$gt->setApiKey('YOUR_GOOGLE_API_KEY');
$gt->setUserIp($_SERVER['REMOTE_ADDR']);
echo $gt->english_to_german("hello world");
} catch (GTranslateException $ge)
{
echo $ge->getMessage();
}
Also consider to provide user IP address. This also can increase your daily limit.
Sign up for a Google API key at https://code.google.com/apis/console/ and activate the Google Translate API. Use the provided key in your project.
From the Google API Console page, follow on the traffic controls link on the left, then click the Configure Traffic Controls button. Increase the characters/second/user for Google Translate to something much larger than the default 100. Keep in mind you have a limit of 100,000 characters total per day.
Edit: as mentioned in my comment, this is how you would set the API key.
$apikey = 'xyz123';
$gt = new Gtranslate();
$gt->setApiKey($apikey);

Can't get "Live Delegated Authentication" to work

I try to get the Live Delegated Authentication to work for the purpose of reading the email addresses.
I am doing this in PHP with the help of the windowslivelogin library. The problem is that I get an error.
I'm not sure what I'm doing wrong, i registered my application on the Azure webpage and got the appid and the secret into the code. This is what i use to initialize the Live Library :
$o = new WindowsLiveLogin();
$o->setAppId('000000004801B670');
$o->setSecret('secret');
$o->setSecurityAlgorithm('wsignin1.0');
$o->setDebug(true);
$o->setPolicyUrl('http://www.google.com/aides.html');
$o->setReturnUrl("http://michaelp.dev.gamepoint.net/framework/mainsite/contactimporter/?service=live");
return $o;
Then I call
$this->LiveLibrary->getLoginUrl()
And after I Login in to Live, it posts 2 things back, $_POST['stoken'] and $_POST['action'].
As soon as I call
$this->LiveLibrary->processLogin($_REQUEST);
It fails and gives back an error that the token is invalid.
I tried getting Consent straight away by making redirecting to
$this->LiveLibrary->getConsentUrl("Contacts.View");
But that gives an 3007 error and says that it cant share the information
According to MS this means the following :
3007
Consent Service API failed in the <method name> method. The application verifier is invalid.
The offer security level requires that a valid application verifier be passed with the request.
I am using the following URL, generated by the library
https://consent.live.com/Delegation.aspx?ps=Contacts.Invite&ru=http%3A%2F%2Fmichaelp.dev.gamepoint.net%2Fframework%2Fmainsite%2Fcontactimporter%2F%3Fservice%3Dlive&pl=http%3A%2F%2Fwww.google.com%2Faides.html&app=appid%3D000000004801B670%26ts%3D1251722931%26sig%3DD2gkM%252F%252FwlRXXfS64NMrV%252Bkt50v6dAOcESblfRk7j%252FUE%253D
I don't understand most of the documentation Microsoft has on this thing, I think its really unclear and chaotic. Also the Sample I tried doesn't work. I get an error message, it can't validate/decode the token. Same I get when I try the processLogin().
Thanks in Advance,
Michael

Categories