I'm trying to use this reddit php api wrapper
https://github.com/jcleblanc/reddit-php-sdk
To submit a post to reddit.
The code seems very simple, and I know I have it configured correct.
When I load the page, it will go to reddit, verify my account, then send me back. But doesn't make the post. If I refresh, nothing happens. If I delete the session cookie, it does the verification confirmation again, but never submits a post.
I set up the api, got the right app id and secret, the redirect uri is right, it comes back to my page.
<?php
echo '<h1>Test</h1>';
require_once("reddit.php");
$reddit = new reddit();
$title = "Test submission Google";
$link = "http://google.com/";
$subreddit = "truepixelart";
$response = $reddit->createStory($title, $link, $subreddit);
var_dump($response);
?>
the dump just returns null, so I don't know where to look
I know it's kind of obscure, but any ideas?
A subreddit post will return null, based on my experience with the code from jcleblanc. His code is not working when i pulled it, but another person fixed it. Pull this
https://github.com/markdavison/reddit-php-sdk/commit/2c2eac7f2202720e3fbb80b1ef48c87a6a213ff6
Then run that code. Except you are missing the getuser function which is required at all calls to the reddit api.
Other calls will return data, such as getlisting, etc and you will see posts submitted and the commands working.
If you need code, please ask as I have all basic functions coded.
Here is my subreddit code call with the git hub changes
ioudas#centralmainedesigns:~/centmedes/wordpress/reddit-php-sdk$ cat submitstory.php
<?php
require_once("reddit.php");
$reddit = new reddit();
$userData = $reddit->getUser();
$title = "MakerBot test 3 Releases IPad App For Easy 3D Printing";
$link = "http://makezine.com/greg";
$subreddit = "cbtest";
$response = $reddit->createStory($title, $link, $subreddit);
var_dump($response);
?>
Related
I just started CS at University and wanted to create a little webdev project in my vacation. I created a simple contact form which asks the user for some data (text, dropdown choices). After pressing the submit button I would like to perform a POST api call to the UiPath Orchestrator to trigger a robot...
Since this is the very first time I'm dealing with PHP I'm not quite sure how to approach this problem.
I'm able to grab the data from the submitted form. But now I'm struggling with the API call. I've tested it in Swagger UI and Postman and it works.
Problem:
I have to authenticate via a batcher id which is also retrievable through an API call.
Question:
Does it make sense to create a new function which is responsible for the API call, since I might want to add other forms which trigger other bot processes?
From my research I'm quite sure that I have to use a cURL call (or is this wrong?).. If i need to authenticat every time the submit button is pressed, how can retrieve the token and pass it as a header (or handle idk) argument for the actual POST call?
If you cant understand my problem, I'm very sorry! I will try my best and reformulate it, but since I'm not experienced with this at all I hope you can forgive me.
Already looking forward for your help!
This is my code so far:
add_action('wpcf7_mail_sent','cf7_api_sender');
function cf7_api_sender($contact_form){
$title = $contact_form ->title;
if ($title === 'MA_Demo'){
$submission = WPCF7_Submission::get_instance();
if ($submission){
$posted_data = $submission->get_posted_data();
$firstname = $posted_data['Firstname'];
$lastname = $posted_data['Lastname'];
$department = $posted_data['Departement'][0];
$workload = $posted_data['Workload'][0];
/*
this is what I found so far but ofc it does not work at all.. do I have to put the body (itemData) into the args?
and where can i pull the beacon token and add it?
$url = '"https://cloud.uipath.com/..../..../orchestrator_/odata/Queues/UiPathODataSvc.AddQueueItem"
$args =[
accept: application/json
X-UIPATH-OrganizationUnitId: .....
{ \"itemData\": { \"Name\": \"...\", \"Priority\": \"...\", \"Reference\": \"...\", \"SpecificContent\": {\"key1\": \"Rick \", \"key2\": \"Roll\"} }}
]
*/
/* this was to test if it works to pull data
$myfile = fopen("data.txt", "w") or die("Unable to open file!");
$txt = $firstname.$lastname.$department.$workload;
fwrite($myfile, $txt);
fclose($myfile);
*/
}
}
}
First you'll need to make a call to /api/Account/Authenticate with your tenant, username, and password. It will return something like
{
"result": "HzptFsZpGMS64j5DTb4TqX-cHVv2AtC4noVCQrkHKr54r...",
"targetUrl": null,
"success": true,
"error": null,
"unAuthorizedRequest": false,
"__abp": true
}
Then you use that result in your Add Queue Item call by adding a header item
"Authorization":"Bearer " & result ("Bearer HzptFsZpGMS64...")
This is for Orchestrator on-prem 2019.10 so cloud may be a little different.
I just started playing D&D, and I'm working on a project for my group to help us play the game a littler easier. We all created Characters on D&D Beyond. They don't have an official API, but apparently, if you type in "your-character-sheet/json" - you can get some JSON output about your character.
I attempted to grab this data in php as I normally would
<?php
$request = "https://www.dndbeyond.com/profile/PixiiBomb/characters/9150025/json";
$url = file_get_contents($request);
$json = json_decode($url, true);
echo $json["character"]["id"];
?>
This should echo out: "9150025" - but I actually see nothing. It's totally blank. So I tried to echo $url, and this is what I see.
Which of course, it not what I should be seeing (because that is formatting from their website, minus the stylesheets)
I went back to the JSON view and manually saved the data as pixii.json This time using the following:
$request = "uploads/dndbeyond_sheets/pixii.json"; // Saved to my harddrive
$url = file_get_contents($request);
$json = json_decode($url, true);
echo $json["character"]["id"];
THIS WORKS if I manually save the file. But that would mean that every time we level up, I would have to manually save all of our JSON data, and run some code to read it and update it.
Is there something else I can try to allow me to use this URL instead of having to manually save the page?
Ideally, I would like to have all of my code written , and then when we level up, I press a button and grab the new data from the site (which I don't need help with, that's not part of the question). Instead of manually visiting each website, saving the data, and then parsing it.
This is a PHP script I use to get the referring website for each new visitor to my site.
If the visitor came from Google, I get the keyword they used to find the site.
This data is stored in the session then included along with the data from the contact form when an enquiry is sent. This allows clients with little knowledge of analytics to track converting keywords.
I need to convert this PHP to work on a site that uses .aspx pages. After researching asp.net for several hours, I feel like I still don't have a clue where to start!
<code>
<?php
session_start(); // start up your PHP session!
if (empty($_SESSION['google'])) {
// if session is empty, take the referer
$thereferer = strtolower($_SERVER['HTTP_REFERER']);
// see if it comes from google
if (strpos($thereferer,"google")) {
// delete all before q=
$a = substr($thereferer, strpos($thereferer,"q="));
// delete q=
$a = substr($a,2);
// delete all FROM the next & onwards
if (strpos($a,"&")) {
$a = substr($a, 0,strpos($a,"&"));
}
// we have the key phrase
$_SESSION['google'] = urldecode($a);
$_SESSION['referer'] = 'Google';
}
}
if (empty($_SESSION['referer'])) {
$_SESSION['referer'] = $_SERVER['HTTP_REFERER'];
}
?>
</code>
I'd really appreciate a point in the right direction with this.
Thanks.
You need to read up on the HttpRequest and HttpResponse classes. More specifically, the Request.ServerVariables collection, the Request.Cookies object, and the Response.Cookies object.
Hello I have all sorts of tutorials for authenticating with oAuth, but it seems like everyone else has one piece of the puzzle that I don't.
In my CMS I am editing the controller, where info gets processed on the submit button. $_POST contains this data and is simply evaluated for content
if(!empty($_POST))
{
$mingurl = 'http://www.myurl.com';
$mingmsg = "New tweet! Link: " . $mingurl;
//Connect to Twitter
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
$connection->getAuthorizeURL(OAUTH_TOKEN, true);
// Posten
$connection->post('statuses/update', array('status' => $mingmsg));
// Error afhandeling
$httpc = $connection->http_code;
if($httpc == 200) {
echo 'Tweet posted!';
} else {
echo "Failed!";
}
}
Now it seems that nothing happened, especially given that the twitter account is not updated. I notice that nowhere here do I call other twitteroauth functions, such as the one that should initially login and allow the twitter application to edit things, but NO tutorial details how this should work. What functions should I call, I am using Abraham Williams twitter oauth php object.
Also I'm not sure if I need to edit the model or view just to add these behind the scenes updating, but I wonder about the popup to add your twitter credentials the first time, would this need to be a feature of the view? How would I call that from the controller etc
I think you should first get the request token and then actually use the authorize URL for the authentication.
$request_token = $connection->getRequestToken($callback_url);
$url = $connection->getAuthorizeURL($token);
header('Location: '.$url);
I can't remember why exactly but for some reason I could use the library you are using right now and created my own: http://code.google.com/p/social-php/
You could also consider to use the 'standard' tweet button if that is more suitable:
http://twitter.com/about/resources/tweetbutton
I'm looking for a good, simple PHP function to get my latest Facebook status updates. Anyone know of one?
Thanks!
EDIT: I've added a half-solution below.
Or if anyone knows a good way to read in the RSS feed and spit out the recent status update?
A quick check on PEAR found Services_Facebook
This is an incomplete answer, but this is what I've gotten so far:
First: add the developer application on FB. Then create a new application. Call it whatever you want.
Second: Download the PHP client. Dump it somewhere on your webhost, i.e. /facebook/
Third: Copy the following beginner code to get yourself started into a php file:
<?php
require_once('facebook/php/facebook.php');
$facebook = new Facebook("YOUR_API_KEY","YOUR_SECRET_KEY");
$result = $facebook->api_client->fql_query("SELECT status FROM user WHERE uid = YOURIDNUMBER");
// OR --- they both get the same data
$result = $facebook->api_client->users_getInfo(YOURIDNUMBER,'status');
print_r($result);
echo "<pre>Debug:" . print_r($facebook,true) . "</pre>"; // debug info
?>
Other info:
You must be logged in and have the
application added. OR you give the
application offline_access
permissions and have the
aapplication added.
You can add offline_access by typing
in the following url:
http://www.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=offline_access
more info on permissions found here: http://wiki.developers.facebook.com/index.php/Extended_permissions
I'm at a stopping point: anything my
program calls the fql query or
users_getInfo, my page stops
executing the php? I'm guessing
there are a limited amount of calls
for new applications? I've never
done any FB development so I'm
completely new to it. Maybe make
the call and save your recent status
(or most recent statuses) in your
own DB to prevent excessive calls to
the API?
I hope this helps someone get started!
EDIT: It seems that FB won't let you access someones status, even if the offline_access is on, unless you are that person or their friend (depending on their privacy settings).
I did however, finally manage to find the RSS feed in the new profile version: http://www.new.facebook.com/minifeed.php?filter=11
I have found a way to fetch your latest facebook status. This is how you do it:
1) Create a facebook app, and copy your application secret and application id.
2) Grant the app read_stream and offline_access to your profile. (http://developers.facebook.com/docs/authentication/permissions) To fetch your latest status the app needs an access_token. With offline_access granted the access_token should "never" expire. The easiest way to do this is to click the button generated by this code: (be sure to fill in 'your app id' and set cookie to true!)
<fb:login-button perms="read_stream,offline_access"></fb:login-button>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});</script>
3) Now try to find out what access_token it is using. The access_token is saved in the fbs_appId cookie. Locate it using your browser or using $_COOKIE['fbs_appId']. Look for access_token=....
4) Now that you have a (hopefully) never expiring access_token you can use the following code:
$access_token='xxxxxxxxxxxxxxxxxxxx';
$appId='123456789132456789';
$appSecret='xxxxxxxxxxxxxxxxxxxx';
$profileId='123456789';
//http://github.com/facebook/php-sdk/blob/master/src/facebook.php
require 'facebook.php';
$facebook = new Facebook(array('appId' => $appId,'secret' => $appSecret));
$response = $facebook->api('/'.$profileId.'/feed?limit=1&access_token='.$access_token);
5) The message part should be located: $response['data'][0]['message']
I don't know HOW long the access token is valid. Facebook says:
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
Here is a REALLY simple function if you just want to get the latest status. It doesn't depend on the Facebook SDK or anything. You just need CURL and JSON support.
Simple PHP function to get facebook status
I never seem to get along with PEAR, but if you have better luck than I, then the PEAR solution seems the best route long term.
Another idea is to explore the Facebook Developer API library and see if that might give you anything you are looking for.
Lastly, there used to be a way to get an RSS feed... but I can't seem to find any instructions that work anymore, but you might poke around Facebook help if that interests you. Mine ends up looking something like this:
http://www.new.facebook.com/feeds/status.php?id=[idnumber]&viewer=[viewer]&key=[key]&format=rss20
I got it working using Jens' post to retrieve a valid access_token. Then, I extracted the status messages and the time of posting from the xml file using the following code (you can change $limit to display more or less status messages, or use a form to change it).
Be sure to put in your Facebook ID and the access token you got from the app you created (see Jens' post). You can check the output of this script here.
Have fun!
<?php
if(isset($_POST['limit'])) {
$limit = $_POST['limit'];
}
else {
$limit = 3; // number of status messages to display
}
$f = fopen ("https://api.facebook.com/method/status.get?uid=YOUR_FACEBOOK_ID&limit=".$limit."&access_token=YOUR_ACCESS_TOKEN", "r");
while ($line= htmlentities(fgets($f))) {
if ($line===FALSE) print ("FALSE\n");
else
{
$content = $content." ".$line;
}
}
fclose ($f);
$message = explode("<message>", $content); // search for the <message> tag
$message_cnt = count($message);
$msg_index = 0;
$time = explode("<time>", $content); // search for the <time> tag
for($i=1; $i<$message_cnt; $i++)
{
$tmp = explode("</message>", $message[$i]);
$msg[$msg_index] = $tmp[0]; // status message
$tmp2 = explode("</time>", $time[$i]);
$t[$msg_index++] = $tmp2[0]; // time of posting
}
for($i=0; $i<$msg_index; $i++)
{
echo("<span class=\"status\">".preg_replace('!\015\012|\015|\012!','<br>',$msg[$i])."</span><br>\n
<span class=\"date\">on ".date("d.m.Y", $t[$i])." at ".date("H:i",$t[$i])."</span><br><br>\n");
}
?>
I have tried loads of tutorials over the last few days and none of them have worked. I think it may be due to facebook changing their api requirements. This is the only one I found that works at the moment:
http://www.deanblog.co.uk/article/13/adding-a-facebook-status-feed-to-your-website-with-php
Just use PHPforFB framework (www.phpforfb.com/en/) for the fastest way.
The code looks like this:
require_once('phpforfb_framework.php');
$structInit = array('app_id' => APP_ID,'app_name' => APP_NAME,'sec_key' => APP_SECKEY);
$FacebookAPP = new PHPforFB($structInit);
if($FacebookAPP->lastErrorCode>0){
//Creation failed => Display error message and exit
echo "PHPforFB Error: ".$FacebookAPP->lastErrorCode." -> ".$FacebookAPP->lastError;
}else{
//PHPforFB framework established
if($FacebookAPP->userLoggedIn === TRUE){
//If the user is logged in at Facebook:
//Here you can determine if the user has at least once before
//granted basic permissions to your application.
if($FacebookAPP->userAuthenticated === FALSE){
//The user has not yet granted permissions
//**your code here**
}else{
//The user has already granted permissions, therefore his Facebook ID
//is known to us. It is always available in $FacebookAPP->userID:
$userID = $FacebookAPP->userID;
//**your code here**
}
}
}
Since I couldn't use the API route, I went with the RSS found at: http://www.new.facebook.com/minifeed.php?filter=11
And used the following PHP function, called StatusPress, with some of my own modifications, to parse the RSS feed for my Facebook status. Works great!
<?php
// see http://github.com/facebook/php-sdk/blob/master/facebook.php
require './facebook.php';
// Create our Application instance.
// see http://www.youtube.com/watch?v=jYqx-RtmkeU for how to get these numbers
$facebook = new Facebook(array('appId' => 'XXX','secret' => 'XXX'));
// This call will always work since we are fetching public data.
// this could be /username or /username/friends etc...
// see developer api for FQL for examples
$status = $facebook->api('/haanmc/feed?limit=1');
?>
<p><?php print $status['data'][0]['message']; ?></p>
<p>Likes: <?php print $status['data'][0]['likes']; ?> | Comments: <?php print count($status['data'][0]['comments']['data']); ?></p>
<textarea style="width: 95%; height: 600px;"><?php print_r($status); ?></textarea>