Zend GData Calendar: I can't use setUpdatedMin in the query [duplicate] - php

I have a problem with Updating and Deleting events using signed requests. Inserting events works just fine. But when Updating and Deleting I receive an "Unknown authorization header" 401 error.
For ALL three operations I first generate the client like this:
$client = new Zend_Gdata_HttpClient();
$client->setAuthSubPrivateKeyFile('certificates/gcalkey.pem', null, true);
$client->setAuthSubToken($session_token);
$gdataCal = new Zend_Gdata_Calendar($client);
To Update an event I use this:
$eventOld = $gdataCal->getCalendarEventEntry($eventUri);
$eventOld->title = $gdataCal->newTitle('NEW NAME');
try {
$eventOld->save();
} catch (Zend_Gdata_App_Exception $e) { print_r($e); exit; }
And it gives me the "Unknown authorization header" error. But the same code, using unsigned requests, works.
Where might be the problem? I tried modifying $eventUri to both https and http, but it seems it does not have any effect.

I've been getting this 401 error message too, creating the client and service the same way. It can retrieve a list of calendars, but fails when retrieving an event feed.
Has this worked for you before? It might not be officially supported yet.

Related

How to use PayPal Express Payments (PHP)

I am using the PayPal PHP SDK found here: https://github.com/paypal/Checkout-PHP-SDK
And I am somewhat puzzled in terms of how to complete the process.
On the outset this seems quite simple:
Setup your credentials
Create the Order
Check the result, and re-direct to approval link
User makes a payment and is sent to the SUCCESS link that you would have set.
i.e. http://example.com/pay/complete/paypal?token=8UK32254ES097084V&PayerID=SEQNPLB2JR9LY
And this is where things get a bit shakey.
Conveniently, a token and a PayerID is returned.
And according to the documentation, you now need to "Capturing the Order" and the following code is provided:
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
// Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
// $response->result->id gives the orderId of the order created above
$request = new OrdersCaptureRequest("APPROVED-ORDER-ID");
$request->prefer('return=representation');
try {
// Call API with your client and get a response for your call
$response = $client->execute($request);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
print_r($response);
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
What is confusing is that the OrdersCaptureRequest requires an "APPROVED-ORDER-ID"
But all that has been returned is a "token" and a "PayerID".
So my question is, what is this APPROVED-ORDER-ID, and where do I get it?
Thank you!
what is this APPROVED-ORDER-ID, and where do I get it
At that moment, sourced from token= . It should correspond to an Order Id you received in the response to your step 2 ("Create the Order")
For step 3, it is better to use no redirects whatsoever. Instead, implement this front-end UI, which offers a far superior in-context experience that keeps your site loaded in the background: https://developer.paypal.com/demo/checkout/#/pattern/server
There is no reason for a modern website to be redirecting unnecessarily

Checking signature in WS* server implementation

I want to verify a signature for a soap request on a soap server implemented in php.
The server code:
$Server = new SoapServer();
$d = new DOMDocument();
$d->load('php://input');
$s = new WSSESoapServer($d);
try {
if($s->process()) {
// Valid signature
$Server->handle($s->saveXML());
} else {
throw new Exception('Invalid signature');
}
} catch (Exception $e) {
echo "server exception: " . $e;
}
The error:
exception 'Exception' with message 'Error loading key to handle Signature' in /<path>/wse/src/WSSESoapServer.php:146
I have implemented a Client to sign SOAP requests using this library: https://github.com/robrichards/wse-php. There are no examples of how to implement the server...
How do I load the public key to check the signature?
[Edit]
I have now been able to load the supplied key using
$key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public'));
$key->loadKey(CERT, true);
I am no longer getting an error message when validating the signature:
$x = new XMLSecurityDSig();
$d = $x->locateSignature($soapDoc);
$valid = $x->verify($key);
However, $valid is always false. I have no idea if it's because the key is loaded wrong or is actually invalid. I can find very little information on implementing a SOAP server with PHP and no information on implementing a SOAP server that relies on checking a signed request.
CLARIFICATION
My client talks to a remote web service and gets an acknowledgement.
Then the remote server takes some time to process my request.
A remote client (that I have no control over) then makes a request to
my service.
The last step is where I have trouble verifying the signature
Well anyways, your first approach looks fine to me, my server has the same structure. Unfortunately, WSSESoapServer does not inherit from SoapServer, thus is not really an SoapServer, but rather a SoapSignatureValidator and should be called like that. It would be easily possible to correct that behaviour, that one would not need a separate SoapServer instance (should be transparent and automatically).
<?php
require 'soap-server-wsse.php';
try {
// get soap message
$xmlSoap = DOMDocument::load('php://input');
// validate signature
$validateSignature = new WSSESoapServer($xmlSoap);
if(!$validateSignature->process())
file_put_contents("log.txt", "soapserver: SIGNATURE VALIDATION ERROR - CONTINUING WITHOUT SIGNATURE\n", FILE_APPEND);
//throw new Exception('Invalid Signature'); # this would cancel the execution and not send an answer
$sServer = new SoapServer($wsdl);
// actually process the soap message and create & send answer
//$sServer->setClass() or setObject() or set setFunction()
$sServer->handle($validateSignature->saveXML());
} catch (Exception $fault) {
file_put_contents("log.txt", "soapserver soapfault: ".print_r($fault, true), FILE_APPEND);
}
?>

FB Graph API query doesn't work in PHP SDK

Graph API: 2.4
PHP SDK: "facebook/php-sdk-v4": "~5.0"
I'd like to get details about a page via PHP and the PHP SDK.
Using the query:
$response = $fb->get('/' . $sPageID . '?fields=posts', $_SESSION['facebook_access_token']);
returns the posts with a good amount of data. But unfortunately wrong values:
The limit 25 for likes for instance applies here. So even if one post should have 150 likes, if I do an count ($post['likes']) I only get 25 as a result.
So I tried to change my query and according to the Graph Explorer
this seems to be working fine:
PAGE_ID/posts?fields=likes.limit(100),message,comments,shares,picture,link,type
Now I can't get this transformed into my PHP call.
I receive timeouts and
Fatal error: Uncaught exception 'Facebook\Exceptions\FacebookSDKException' with message 'Unable to convert response from Graph to a GraphNode because the response looks like a GraphEdge. Try using GraphNodeFactory::makeGraphEdge() instead.' in ...
Is this possible with one query in PHP or do I have to run multiple queries, one for each post?
I found this answer, and if because the end of point of this request is a GraphEdge, so try this:
// Get basic info on the user from Facebook.
try {
$response = $fb->get('/' . $sPageID . '?fields=posts', $_SESSION['facebook_access_token']);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
$getGraphEdge = $response->getGraphEdge();
I hope this help you.
Regards.
Newer PHP SDK versions have the getGraphList() method, getGraphEdge() is for the earlier, even though it wasn't documented.

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Dealing with Twitter's Ups and Downs - API

I make use of a great class made by Jaisen: http://github.com/jmathai/twitter-async/tree/master. Recently twitter has been up and down and I am sure it will continue to be the same in the future so I am trying to cut down on my dependency on twitter being actually working.
The following is what I have in my header.php and it is right at the top and it generates the login URL for each user. If twitter is down, my site hangs for as long as it needs to and it throws an exception. So I have to catch these expceptions which I have sort of done.
I now want to just cancel the request to the API after a few seconds and just load the page and keep trying behind the scenes. How can I best do this?
<?php include './twitter/EpiCurl.php'; include './twitter/EpiOAuth.php'; include './twitter/EpiTwitter.php';
$consumer_key = 'mykey';
$consumer_secret = 'mysecret';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
try{
$twiturl = $twitterObj->getAuthenticateUrl();
$url = "window.open('".$twiturl."','Login', 'left=20,top=20,width=500,height=500,toolbar=0,resizable=1'); startLoad();";
}catch(EpiOAuthBadRequestException $e){
// bad request exception do something
$statusMessage = 'Oops an error has occurred: ' . $e->getMessage();
}catch(EpiOAuthUnauthorizedException $e){
// bad authorization..probably bad tokens, do something different
$statusMessage = 'Oops an error has occurred: ' . $e->getMessage();
}catch(EpiOAuthException $e){
// uh oh, unknown oauth exception
$statusMessage = 'Oops, an unknown authorisation error has occurred! The mojo team have been notified! Please try again.';
}
if(isset($statusMessage)){
}
?>
Any improvement of the above code will also be appreciated.
Thanks all
The library supports a value to be passed into the curl timeout.
$twitterObj->setTimeout($secs_request_timeout);
I just added support for passing in a connection timeout as well. Unable to run unit tests because I'm being rate limited. Will commit this once I can verify that it works.
$twitterObj->setTimeout($secs_request_timeout, $secs_connection_timeout);
Use curl_setopt(CURLOPT_CONNECTTIMEOUT, 1 /* 1 second timeout */); to cause CURL to give up if a connection isn't established in 1 second. I use this when connecting to the facebook API, 'cause they've been pretty unreliable in the past as well.

Categories