Pubsubhubbub subscriber callback implementation in PHP - php

I am trying to use the PSHB protocol to be notified of my Google alerts. I am using the code found here. However, it is not clear to me how to implement the callback (or endpoint).
Can someone provide a trivial example that shows how I can access the data that has been POSTed to my endpoint?
A (slightly modified) snippet of the google code follows below:
<?php
// simple example for the PHP pubsubhubbub Subscriber
// as defined at http://code.google.com/p/pubsubhubbub/
// written by Josh Fraser | joshfraser.com | josh#eventvue.com
// Released under Apache License 2.0
include("subscriber.php");
$hub_url = "http://pubsubhubbub.appspot.com";
$callback_url = "http://www.example.com/mycallback.php"; // <- how to implement this ?
[[Edit]]
I have added some pseudocode below, to help clarify the question further ...
// Implementation of mycallback.php
<?php
$pubsub_post_vars = $_POST[WHAT_NAME_AM_I_LOOKING_FOR]; //what's the name of the POST var?
// How do I get to the 'good stuff?
$feed_id = $pubsub_post_vars[SOME_VARIABLE]
$feed_title = $pubsub_post_vars[ANOTHER_VARIABLE]
$contents = $pubsub_post_vars[YET_ANOTHER_VARIABLE]
$author = $pubsub_post_vars[YET_ANOTHER_VARIABLE_1]
$perma_link = $pubsub_post_vars[YET_ANOTHER_VARIABLE_2]
$pub_date = $pubsub_post_vars[YET_ANOTHER_VARIABLE_3]
?>
I realize that approach (above) may be complete wrong, as I suspect that it is an RSS/ATOM document that is POSTed. However, some skeleton code like the one above should be enough to get me started, so that I can extract things like the feed id, title and published content ... etc.

Well, the way to implement it really depends on what you want to achieve with it.
But generally, there are 2 things your callback needs to handle:
Verification of intent
Handling of notifications
For the Verification of Intent, your callback needs to echo the hub.challenge parameter, if you really want the subscription for that specific feed.
For the handling of the notification, your callback probably needs to check the validity (signature), if you'v used a secret when susbribing and, later it needs to read and save the content of the body.
[UPDATE] Beware, the notification will not be included in any POST variable, it will be the full body itself (Accessible thru $request_body = #file_get_contents('php://input');). POST vars are usually parsed by PHP from the body. In this context, you do want to access the raw body. You will then be able to extract all the vars you're looking from the XML (RSS or Atom) posted to you.

Related

Get PHP response into Zapier webhook

I am connecting PipeDrive with Post Affiliate Pro (with it's API) and am using Zapier webhooks (POST). Therefore I use PHP scripts on my server in which I talk to Post Affiliate Pro. So I have variables in my PHP script which I need to return in order to use them in another webhook/or general action step. In Zapier the only variable I get when testing the step is a String with my response message (and whatever variable I put in there). But I need to get all variables on their own (I guess all in a JSON).
So my question is: How can I return variables in an HTTP POST request to make them available (in the dropdown list?) in Zapier to use them in the next webhook?
At the moment I have something like this:
if ($result->isError()) {
echo 'Error: '.$result->getErrorMessage();
} else {
//echo 'Ok: '.$result->getInfoMessage();
echo json_encode($orderID);
I am using 'echo' but I've also tried to use 'return' which didn't lead to any results. I've also tried to use json_encode to return a JSON but without luck. Or do I even need to use another Zapier step? Or am I not able to return values with a POST webhook at all? Do I need to use a "Catch Hook" webhook? I am completely new to Zapier and PHP.
Image shows just two Strings ('Text' & 'Text Transaktion') available in Zapier but no other variables
Thanks for your help!
I finally found it out by myself. I have to return one JSON, which includes everything. It's also not possible to echo anything at the same time as this would result in the output of just one string with all the values in it (like I had it before).
So something like this does the job:
if (!isset($returnValue)) {
$returnValue = new stdClass();
$returnValue->order_id = $orderID;
$returnValue->result_message = $resultMessage;
}
print_r(json_encode($returnValue));

Azure Functions with PHP

I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>

Posting Data to REST API using JSON and PHP

I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);

HTML content extraction using Diffbot

Can someone help me I want to extract html data from http://www.quranexplorer.com/Hadith/English/Index.html. I have found a service that does exactly that http://diffbot.com/dev/docs/ they support data extraction via a simple api, the problem it that I have a large number of url that needs that needs to be processed. The link below http://test.deen-ul-islam.org/html/h.js
I need to create a script that that follows the url then using the api generate the json format of the html data (the apis from the site allows batch requests check website docs)
Please note diffbot only allows 10000 free request per month so I need a way to save the progress and be able to pick up where I left off.
Here is an example I created using php.
$token = "dfoidjhku";// example token
$url = "http://www.quranexplorer.com/Hadith/English/Hadith/bukhari/001.001.006.html";
$geturl="http://www.diffbot.com/api/article?tags=1&token=".$token."&url=".$url;
$json = file_get_contents($geturl);
$data = json_decode($json, TRUE);
echo $article_title=$data['title'];
echo $article_author=$data['author'];
echo $article_date=$data['date'];
echo nl2br($article_text=$data['text']);
$article_tags=$data['tags'];
foreach($article_tags as $result) {
echo $result, '<br>';
}
I don't mind if the tool is in javascript or php I just need a way to get the html data in json format.
John from Diffbot here. Note: not a developer, but know enough to write hacky code to do simple things.
You have a list of links -- it should be straightforward to iterate through those, making a call to us for each.
Here's a Python script that does such: https://gist.github.com/johndavi/5545375
I used a quick search regex in Sublime Text to pull out the links from the JS file.
To truncate this, just cut out some of the links, then run it. It will take a while as I'm not using the Batch API.
If you need to improve or change this, best seek out a stronger developer directly. Diffbot is a dev-friendly tool.

translate from ASP to PHP

I am being forced to work with a database company that only support ASP.NET, despite my employers being well aware that I only code in PHP and the project doesn't have the time to learn the new syntax.
Documentation is scant, and meaning in thin on the ground. Can someone help translate what is happening in this script, so that I can think about doing it in PHP
<%
QES.ContentServer cs = new QES.ContentServer();
string state = "";
state = Request.Url.AbsoluteUri.ToString();
Response.Write(cs.GetXhtml(state));
%>
QES.ContentServer cs = new QES.ContentServer();
the code instantiates the class method ContentServer()
string state = "";
Explicit the type var state as string
state = Request.Url.AbsoluteUri.ToString();
here you get the REQUEST URI (as in php) the path and convert it to one line string and put in the before mentioned string statte var
Response.Write(cs.GetXhtml(state));
and here return the message without refresh the page (ajax).
The Request object wraps a bunch of information regarding the request from the client i.e. Browser capabilities, form or querystring parameters, cookies etc. In this case it is being used to retrieve the absolute URI using Request.Url.AbsoluteUri.ToString(). This will be the full request path including domain, path, querystring values.
The Response object wraps the response stream sent from the server back to the client. In this case it is being used to write the return of the cs.GetXhtml(state) call to the client as part of the body of the response.
QES.ContentServer appears to be a third party class and is not part of the standard .NET framework so you would have to get access to the specific API documention to find out what is for and what the GetXhtml method does exactly.
So, in a nutshell, this script is taking the full URI of the request from the client and returning the output from the GetXhtml back in the response.
It would look like this in PHP:
<?php
$cs = new QES_ContentServer(); //Not a real php class, but doesn't look like a native ASP.NET class either, still, it's a class instantiation, little Google shows it's a class for Qwam E-Content Server.
$state = ""; //Superfluous in PHP, don't need to define variables before use except in certain logic related circumstances, of course, the ASP.NET could have been done in one line like "string state = Request.Url.AbsoluteUri.ToString();"
$state = $_SERVER['REQUEST_URI']; //REQUEST_URI actually isn't the best, but it's pretty close. Request.Url.AbsoluteUri is the absolute uri used to call the page. REQUEST_URI would return something like /index.php while Request.Url.AbsoluteUri would give http://www.domain.com/index.php
//$state = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; or something similar might be better in this case given the above
echo $cs->GetXhtml($state); //GetXhtml would be a method of QES.ContentServer, Response.Write is like echo or print.
?>

Categories