How to POST via Reddit API (addcomment) - php

I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!

If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.

Related

Getting the acess token from Guzzle Oauth authentication

I'm currently trying to develop a connection to the Reddit api through Oauth using Guzzle. I get to the point where I authenticate in Reddit, then I get to the authorization token, but I can't take the access token from the Guzzle response so I can set it as a cookie and using on subsequent requests. My current code looks like this:
public function __construct(){
if(isset($_COOKIE['reddit_token'])){
$token_info = explode(":", $_COOKIE['reddit_token']);
$this->token_type = $token_info[0];
$this->access_token = $token_info[1];
} else {
if (isset($_GET['code'])){
//capture code from auth
$code = $_GET["code"];
//construct POST object for access token fetch request
$postvals = sprintf("code=%s&redirect_uri=%s&grant_type=authorization_code",
$code,
redditConfig::$ENDPOINT_OAUTH_REDIRECT);
//get JSON access token object (with refresh_token parameter)
$token = self::runCurl(redditConfig::$ENDPOINT_OAUTH_TOKEN, $postvals, null, true);
//store token and type
if (isset($token->access_token)){
$this->access_token = $token->access_token;
$this->token_type = $token->token_type;
//set token cookie for later use
$cookie_time = 60 * 59 + time(); //seconds * minutes = 59 minutes (token expires in 1hr)
setcookie('reddit_token', "{$this->token_type}:{$this->access_token}", $cookie_time);
}
} else {
$state = rand();
$urlAuth = sprintf("%s?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&state=%s",
redditConfig::$ENDPOINT_OAUTH_AUTHORIZE,
redditConfig::$CLIENT_ID,
redditConfig::$ENDPOINT_OAUTH_REDIRECT,
redditConfig::$SCOPES,
$state);
//forward user to PayPal auth page
header("Location: $urlAuth");
}
}
This is my authentication flow. The I have the runCurl method that is going to make the guzzle requests:
private function runCurl($url, $postVals = null, $headers = null, $auth = false){
$options = array(
'timeout' => 10,
'verify' => false,
'headers' => ['User-Agent' => 'testing/1.0']
);
$requestType = 'GET';
if ($postVals != null){
$options['body'] = $postVals;
$requestType = "POST";
}
if ($this->auth_mode == 'oauth'){
$options['headers'] = [
'User-Agent' => 'testing/1.0',
'Authorization' => "{$this->token_type} {$this->access_token}"];
}
if ($auth){
$options['auth'] = [redditConfig::$CLIENT_ID, redditConfig::$CLIENT_SECRET];
}
$client = new \GuzzleHttp\Client();
$response = $client->request($requestType, $url, $options);
$body = $response->getBody();
return $body;
}
The problem resides here, the getBody() method returns a stream, and if I use getBody()->getContents() I get a string, none of which can help me.
Any idea on how can I get the access token so I can finish the authentication process?
To answer the question itself - you just need to cast $body to string. It should be a json, so you will also need to json_decode it to use it as an object in the code above. So instead of return $body; in your runCurl, you need to do:
return json_decode((string)$body);
I would recommend to use the official client tho. The code in the question has some unrelated issues, which will make it costy to maintain.

ExactOnline API en OData

I am struggling with the API of Exact Online.
Using this example code to retrieve information of the server:
$response = $exactApi->sendRequest("crm/Accounts?$filter=substringof('test', Name) eq true', 'get');
Above returns a Bad Request. Anyone got a clue how to fix this?
The function 'send request':
public function sendRequest($url, $method, $payload = NULL)
{
if ($payload && !is_array($payload)) {
throw new ErrorException('Payload is not valid.');
}
if (!$accessToken = $this->initAccessToken()) {
throw new ErrorException('Access token was not initialized');
}
$requestUrl = $this->getRequestUrl($url, array(
'access_token' => $accessToken
));
// Base cURL option
$curlOpt = array();
$curlOpt[CURLOPT_URL] = $requestUrl;
$curlOpt[CURLOPT_RETURNTRANSFER] = TRUE;
$curlOpt[CURLOPT_SSL_VERIFYPEER] = TRUE;
$curlOpt[CURLOPT_HEADER] = false;
if ($method == self::METHOD_POST) {
$curlOpt[CURLOPT_HTTPHEADER] = array(
'Content-Type:application/json',
'access_token:' . $accessToken,
'Content-length: ' . strlen(json_encode($payload))
);
$curlOpt[CURLOPT_POSTFIELDS] = json_encode($payload);
$curlOpt[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
}
$curlOpt[CURLOPT_ENCODING] = '';
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $curlOpt);
return curl_exec($curlHandle);
}
Tested this.
crm/Accounts?$select=Name&$filter=substringof('Lennert',Name) : OK
crm/Accounts?$select=Name&$filter=substringof('Lennert', Name) eq true : NOK, error 400
crm/Accounts?\$select=Name&$filter=substringof(Name, 'Lennert') eq true : NOK, error 400
First option works but is not according to OData v2 specifications which Exact Online uses. Will be discussed with development to see what can be done for this.

message send by twice while calling this function in codeigniter

When I call the function below, the field in my database gets the responses as send (only one time), but when I check the mobile it has sent two equal messages at a time.
public function sendverifymsg($phone, $verifycode) {
$user = "xx";
$password = "xx";
$api_id = "xx";
$baseurl = "http://promo.blastsms.in/sendsms.jsp?";
$text = urlencode("Thank you for registering with CARE MY KIDEE.. VERIFY CODE =" . $verifycode . "Please verify your mobile number immedi`enter code here`ately for our value added services.... ");
$version = "3";
//Define header array for cURL requestes
$header = array('Contect-Type:application/xml', 'Accept:application/xml');
// auth call
$url = "$baseurl/&user=$user&password=$password&mobiles=$phone&sms=$text&senderid=$api_id&version=$version";
//Define http request nouns
$ls = $url . "landscapes";
//Initialise cURL object
$ch = curl_init();
//Set cURL options
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => $header, //Set http header options
CURLOPT_URL => $ls, //URL sent as part of the request
CURLOPT_NOBODY => 1,
CURLOPT_FAILONERROR => TRUE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, //Set Authentication to BASIC
CURLOPT_USERPWD => $user . ":" . $password, //Set username and password options
CURLOPT_HTTPGET => TRUE //Set cURL to GET method
));
//Define variable to hold the returned data from the cURL request
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
if ($errorDescription) {
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
} else {
$errorDescription = 'verify';
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
}
return true;
} else {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
// $errorDescription = "failed";
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
return false;
}
//Close cURL connection
curl_close($ch);
}
Try it
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
Modify It
$data = curl_exec($ch);
if ($data !== FALSE) {
You are execute tow time CURL

How to get user email with google access token?

I followed all these steps.
https://developers.google.com/+/web/signin/
I have client id and client secret.
I got access token now, how can I get user profile and email with access token? And how to check whether user logged in or not?
Using OAuth2, you can request permissions through the scope parameter. (Documentation.) I imagine the scopes you want are https://www.googleapis.com/auth/userinfo.email and https://www.googleapis.com/auth/userinfo.profile.
Then, it's a simple matter to get the profile info once you've obtained your access token. (I assume you've been able to redeem the returned authorization code for an access token?) Just make a get request to https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}, which returns a JSON array of profile data, including email:
{
"id": "00000000000000",
"email": "fred.example#gmail.com",
"verified_email": true,
"name": "Fred Example",
"given_name": "Fred",
"family_name": "Example",
"picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
"gender": "male",
"locale": "en-US"
}
No guarantees, but try this:
$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));
if ((int)$request->getResponseHttpCode() == 200) {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
//process user info
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
}
}
try this
$accessToken = 'access token';
$userDetails = file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' . $accessToken);
$userData = json_decode($userDetails);
if (!empty($userData)) {
$googleUserId = '';
$googleEmail = '';
$googleVerified = '';
$googleName = '';
$googleUserName = '';
if (isset($userData->id)) {
$googleUserId = $userData->id;
}
if (isset($userData->email)) {
$googleEmail = $userData->email;
$googleEmailParts = explode("#", $googleEmail);
$googleUserName = $googleEmailParts[0];
}
if (isset($userData->verified_email)) {
$googleVerified = $userData->verified_email;
}
if (isset($userData->name)) {
$googleName = $userData->name;
}
} else {
echo "Not logged In";
}
You just add this line into your scope
Open your Application.cfc and then add this code
<cfset request.oauthSettings =
{scope = "https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile",
client_id = "Your-id",
client_secret = "your-secret",
redirect_uri = "redirect-page",
state = "optional"} />
Now you can get email from function that you can call like this
<cfscript>
public function getProfile(accesstoken) {
var h = new com.adobe.coldfusion.http();
h.setURL("https://www.googleapis.com/oauth2/v1/userinfo");
h.setMethod("get");
h.addParam(type="header",name="Authorization",value="OAuth #accesstoken#");
h.addParam(type="header",name="GData-Version",value="3");
h.setResolveURL(true);
var result = h.send().getPrefix();
return deserializeJSON(result.filecontent.toString());
}
</cfscript>
<cfoutput>
<cfset show = getProfile(session.ga_accessToken)>
<cfdump var="#show#">
</cfoutput>
Hope this can Help many of people to solve this . :)
$access_token = 'your access token';
$headers = array('Content-Type: Application/json');
$endpoint = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=".$access_token;
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, $endPoint);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
curl_setopt($soap_do, CURLOPT_FAILONERROR, true);
$result = curl_exec($soap_do);

What request does the PHP cURL function produce?

I am currently writing an C# windows service, which integrates with a PHP page. I have an example of code making the request in PHP which is below however I have never developed in PHP and don't understand how the cURL function performs the request.
Is there anyway to retrieve the request which is being sent? Or can anyone provide an example of how the request would look and how the request is sent so I can replicate the request in C#.
Thank you for any help.
public function api(/* polymorphic */) {
$args = func_get_args();
if (is_array($args[0])) {
$serviceId = $this->getApiServiceId($args[0]["method"]);
unset($args[0]["method"]);
$args[0]["serviceId"] = $serviceId;
$args[0]["dealerId"] = $this->dealerId;
$args[0]["username"] = $this->username;
$args[0]["password"] = $this->password;
$args[0]["baseDomain"] = $this->baseDomain;
return json_decode($this->makeRequest($args[0]));
} else {
throw Exception("API call failed. Improper call.");
}
}
protected function makeRequest($params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new WPSApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
Add the option CURLINFO_HEADER_OUT to curl handle, then call curl_getinfo on it after execing.
As in:
//...
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
//...
curl_exec($ch);
//...
$header = curl_getinfo(CURLINFO_HEADER_OUT);
echo $header;

Categories