How to avoid fatal error: Uncaught OAuthException when using cron job - oauth

Hi hope somone can help with this one. Ive had a birthday reminder app built, that aquires the usual permissions including offline access etc.
The app requires a daily cron job to be run on my server.
When I run the cron file a recieve the below error
Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in blah/base_facebook.php on line 1140;
Is there a common reason for the error, am i doing anything wrong that stands out, and should i be displaying more code to get help from people?
below are the lines leading up to the error. My code ends on line 1140;
<?php
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
}
protected function getUrl($name, $path='', $params=array())
{
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
}
protected function getCurrentUrl() {
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
$query = '';
if (!empty($parts['query'])) {
// drop known fb params
$params = explode('&', $parts['query']);
$retained_params = array();
foreach ($params as $param) {
if ($this->shouldRetainParam($param)) {
$retained_params[] = $param;
}
}
if (!empty($retained_params)) {
$query = '?'.implode($retained_params, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
}
protected function shouldRetainParam($param) {
foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
if (strpos($param, $drop_query_param.'=') === 0) {
return false;
}
}
return true;
}
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
?>
CRON.php
<?php
require_once("src/facebook.php");
include("custom.php");
set_time_limit(0);
$config = array();
$config['array'] = $appID;
$config['secret'] = $appSecret;
$facebook = new Facebook($config);
$day = abs(date("j"));
$month = abs(date("n"));
$result = mysql_query("SELECT uid, uid2, name2 FROM birthdays WHERE birthmonth = '$month' AND birthday = '$day'");
while(($row = mysql_fetch_assoc($result)) && mysql_num_rows($result)) {
$link = $hostURL.'post.php?uid='.$row['uid'].'&uid2='.$row['uid2'];
$facebook->api('/'.$row['uid'].'/feed', 'POST',
array(
'link' => $link,
'from' => '299185790135651',
'picture' => $hostURL.'image.php?id='.$row['uid2'],
'name' => 'Send Cake',
'message' => 'It\'s '.$row['name2'].'\'s birthday today! Send them a virtual cake!',
'caption' => 'Sponsored by Intercake Ltd'
));
}
?>
also... what is 'from' => '299185790135651', ?
want to check my developer has put the right number here. Thanks

The best way to handle this is to use a try...catch statement. As follows:
try {
// some code that calls Facebook
} catch ( Exception $e ) {
// $e will contain the error - do what you want with it here
// e.g. log it or send an email alert etc.
}
The 'from' => '299185790135651' is a User / Page ID that publishes the message to the Feed. In this case, it's pointing to a Test Facebook Page.

Related

undefined index Razorpay_orderid

when I use webview my app is giving me err undefined index razoprpay_orderid.
and in web application it is working fine.
here are lines of code . on first line it gives err.
$razorpay_order = $_SESSION['razorpay_order_id'];
if (empty($_POST['razorpay_payment_id']) === false)
{
$api = new Api($keyId, $keySecret);
try
{
// Please note that the razorpay order ID must
// come from a trusted source (session here, but
// could be database or something else)
$attributes = array(
'razorpay_order_id' => $_SESSION['razorpay_order_id'],
'razorpay_payment_id' => $_POST['razorpay_payment_id'],
'razorpay_signature' => $_POST['razorpay_signature']
);
$api->utility->verifyPaymentSignature($attributes);
}
catch(SignatureVerificationError $e)
{
$success = false;
$error = 'Razorpay Error : ' . $e->getMessage();
}
}

Google Oauth2 API - No Refresh Token

I have attempted many solutions provided on Stack Exchange to obtain a refresh token, and they all fail. Below is my whole controller. As you can see, I have included $client->setAccessType('offline') and $client->setApprovalPrompt('force').
In addition, I have ran the revoke token many times, and I have gone into my Google Account here (https://myaccount.google.com/permissions), and removed access. None of these attempts provided me with a refresh token when I made a new authorization.
<?php
/**
* #file
* Contains \Drupal\hello\GAOauthController.
*/
namespace Drupal\ga_reports_per_user\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Google_Client;
use Google_Service_Analytics;
use Drupal\group\Context\GroupRouteContextTrait;
class GAOauthController extends ControllerBase {
use GroupRouteContextTrait;
public function authorize($group = NULL) {
$client = new Google_Client();
$credentials_file = \Drupal::service('file_system')->realpath("private://") . '/client_credentials.json';
$client->setAuthConfig($credentials_file);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = "https";
}
else {
$protocol = "http";
}
$redirect_uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/finish_google_oauth';
$client->setState($group);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$auth_url = $client->createAuthUrl();
return new TrustedRedirectResponse($auth_url);
}
public function finishOauth() {
if (isset($_GET['code'])) {
$client = new Google_Client();
$credentials_file = \Drupal::service('file_system')->realpath("private://") . '/client_credentials.json';
$client->setAuthConfig($credentials_file);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = "https";
}
else {
$protocol = "http";
}
$redirect_uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/finish_google_oauth';
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$refreshToken = $client->getRefreshToken();
$client->setAccessToken($token);
$group_entity = \Drupal::entityTypeManager()->getStorage('group')->load($_GET['state']);
$group_entity->field_google_oauth_token->value = $token['access_token'];
$group_entity->field_google_oauth_token_type->value = $token['token_type'];
$group_entity->field_google_oauth_token_created->value = $token['created'];
$group_entity->field_google_oauth_token_expire->value = $token['expires_in'];
$save_status = $group_entity->save();
return new RedirectResponse('/group/' . $_GET['state']);
}
}
public function revoke($group = NULL){
$client = new Google_Client();
$group_entity = \Drupal::entityTypeManager()->getStorage('group')->load($group);
$result = $client->revokeToken($group_entity->field_google_oauth_token->value);
$group_entity->field_google_oauth_token->value = '';
$group_entity->field_google_oauth_token_type->value = '';
$group_entity->field_google_oauth_token_created->value = '';
$group_entity->field_google_oauth_token_expire->value = '';
$group_entity->save();
return new RedirectResponse('/group/' . $group);
}
}
If you have already requested an access token for that login / dev. token combo, it won't return it again for you. You'll have to revoke access by going to https://myaccount.google.com/permissions. Find your app, revoke access, and try again.
Source: I had this exact same problem and after nearly pulling my hair out, I figured this out.

Change upload_dir folder at a certain cpt but cant change back

im try something with the upload_dir filter
I check the current CPT with this function
function get_current_post_type() {
global $post, $typenow, $current_screen;
//we have a post so we can just get the post type from that
if ( $post && $post->post_type ) {
return $post->post_type;
} //check the global $typenow - set in admin.php
elseif ( $typenow ) {
return $typenow;
} //check the global $current_screen object - set in sceen.php
elseif ( $current_screen && $current_screen->post_type ) {
return $current_screen->post_type;
} //lastly check the post_type querystring
elseif ( isset( $_REQUEST['post_type'] ) ) {
return sanitize_key( $_REQUEST['post_type'] );
}
//we do not know the post type!
return NULL;
}
now i want to change the 'upload_dir' on at a certain cpt called "rsg_download"
add_action( 'admin_init', 'call_from_admin' );
function call_from_admin() {
//Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads"
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
}
When i use only
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
The 'change_upload_dir' function is called twice dont know why also i call this from 'admin_init' with the function 'call_from_admin' and it calls only one time so far so good
i go to my CPT "rsg_download" and the uploade files are in the right place at wp-content/uploads/rsg-uploads/ this works so far
now i go to "Pages" and i upload a File but i want the files not in /rsg-upload but in the default path
Function to change the upload_dir this function should only be called when the custom post type is 'rsg_download':
function change_upload_dir( $param ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
return $param;
}
I found! this will only change the upload dir when upload in the "rsg_download" CPT
add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );
function rsg_pre_upload( $file ) {
add_filter( 'upload_dir', 'rsg_custom_upload_dir' );
return $file;
}
function rsg_custom_upload_dir( $param ) {
$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
}
return $param;
}

Hooking up OpenCart with an iOS App via web services

I need to develop an iOS app that fetches data from an OpenCart installation online. This includes ordering online, adding things to wish list, creating a user account. Logging in to an already existing user account and everything else that open cart offers. Basically, it is an iOS version of the OpenCart website that connects to the OpenCart's MySQL database.
I googled a little bit but couldn't find a proper API that I can use to hookup my app with OpenCart. What other options do I have? Does OpenCart offer any web service? (Like WordPress offers XML-RPC). Or is there a good API that I can use?
Unfortunately, OpenCart does not offer any API straight away. (that's for an answer).
There is an opensource OpenCart API project on GitHub that you can download (google it, I do not remember it's name) but this offers only the very limited and basic methods for just reading of data (if I remember correctly there were methods for getting the list of categories, list of products and product details and few more).
This could be your starting point: fork, add methods, share. Or create your own API from a scratch if you wish (again, sharing will be highly welcomed :-) - I believe you could even find users willing to pay for it - I would have created one if I had time - but sadly I have not...).
<?php
include_once 'functions.php';
class ControllerJsonJson extends Controller {
public function index() {
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
if ($child['image']) {
$childpopup = $this->model_tool_image->resize($child['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
$childthumb = $this->model_tool_image->resize($child['image'], 74,74);
} else {
$childthumb='';
$childpopup = '';
}
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'popup'=>$childpopup,
'thumb'=>$childthumb,
'id' => $child['category_id'],
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
if ($category['image']) {
$categorypopup = $this->model_tool_image->resize($category['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
$categorythumb = $this->model_tool_image->resize($category['image'], 74,74);
} else {
$categorypopup = '';
$categorythumb='';
}
// Level 1
$data['categories'][] = array(
'popup' => $categorypopup,
'thumb' => $categorythumb,
'id' => $category['category_id'],
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$obj=new functions();
echo $obj->json_pretty_encode($data);
}
}
<?php
class functions {
//put your code here
public function json_pretty_encode($obj){
header("Content-type: application/json");
$json = json_encode($obj);
if (!$json) return $json;
$f = '';
$len = strlen($json);
$depth = 0;
$newline = false;
for ($i = 0; $i < $len; ++$i)
{
if ($newline)
{
$f .= "\n";
$f .= str_repeat(' ', $depth);
$newline = false;
}
$c = $json[$i];
if ($c == '{' || $c == '[')
{
$f .= $c;
$depth++;
$newline = true;
}
else if ($c == '}' || $c == ']')
{
$depth--;
$f .= "\n";
$f .= str_repeat(' ', $depth);
$f .= $c;
}
else if ($c == '"')
{
$s = $i;
do {
$c = $json[++$i];
if ($c == '\\')
{
$i += 2;
$c = $json[$i];
}
} while ($c != '"');
$f .= substr($json, $s, $i-$s+1);
}
else if ($c == ':')
{
$f .= ': ';
}
else if ($c == ',')
{
$f .= ',';
$newline = true;
}
else
{
$f .= $c;
}
}
return $f;
}
}

Problems decoding JSON data from Twitter API (THM oauth)

I am using tmhOAuth.php / class to login into twitter. I have been successful in logging in and sending a tweet.
When I go to use the friends.php script, I am having some problems inserting into my database. I do believe that my problem lies some where with the $paging variable in the code. Because it is looping only seven times. I am following 626 people so my $ids is 626 and then $paging is 7.
When I run the php in a web browser, I am only able to extract 7 of the followers (ie following user #626,following user 526,following user 426...) It seem to be echoing the last user on each page request. This due in part to requesting 100 user ids at a time, via the PAGESIZE constant. When I adjust the $paging with different number such as the number 626 I get {"errors":[{"code":17,"message":"No user matches for specified terms"}]}
Unfortunately, I suspect this is fairly simple php looping problem, but after the amount of time I have spent trying to crack this I can no longer think straight.
Thanks in advance.
define('PAGESIZE', 100);
require 'tmhOAuth.php';
require 'tmhUtilities.php';
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$ids += $data['ids'];
$cursor = $data['next_cursor_str'];
} else {
echo $tmhOAuth->response['response'];
break;
}
endwhile;
// lookup users
$paging = ceil(count($ids) / PAGESIZE);
$users = array();
for ($i=0; $i < $paging ; $i++) {
$set = array_slice($ids, $i*PAGESIZE, PAGESIZE);
$tmhOAuth->request('GET', $tmhOAuth->url('1/users/lookup'), array(
'user_id' => implode(',', $set)
));
// check the rate limit
check_rate_limit($tmhOAuth->response);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$name = array();
foreach ($data as $val)
{
$name = $data[0]['screen_name'];
}
echo "this is the screen name " .$name. "\n";
$users += $data;
} else {
echo $tmhOAuth->response['response'];
break;
}
}
var_dump($users);
?>
The data I am trying to echo, then parse and insert into database is the standard twitter JSON data, so I won't include this in the message. Any help would be
Problem solved:
foreach ($data as $val)
{
$name = $val['screen_name'];
echo "this is the screen name " .$name. "\n";
$users[] = $name;
}

Resources