<?php
require_once __DIR__ . '/vendor/autoload.php';
$client_id = '*********.apps.googleusercontent.com';
$client_secret = '**************************';
$redirect_uri = 'https://{site}/wp-admin/plugins.php/oauth';
$client = new Google_Client();
$client->setClientId( $client_id );
$client->setClientSecret( $client_secret );
$client->setRedirectUri( $redirect_uri );
$client->setScopes( array('https://www.googleapis.com/auth/drive') );
if ( isset( $_GET['code'] ) ) {
$client->authenticate( $_GET['code'] );
$_SESSION['access_token'] = $client->getAccessToken();
header( 'Location: ' . filter_var( $redirect_uri, FILTER_SANITIZE_URL ) );
exit;
}
if ( ! isset( $_SESSION['access_token'] ) ) {
$auth_url = $client->createAuthUrl();
header( 'Location: ' . filter_var( $auth_url, FILTER_SANITIZE_URL ) );
exit;
}
$client->setAccessToken( $_SESSION['access_token'] );
$service = new Google_Service_Sheets($client);
$spreadsheet = new Google_Service_Sheets_Spreadsheet(array(
'properties' => array(
'title' => 'My New Spreadsheet'
),
'sheets' => array(
new Google_Service_Sheets_Sheet(array(
'properties' => array(
'title' => 'Sheet1',
'gridProperties' => array(
'rowCount' => 20,
'columnCount' => 12
)
)
))
)
));
$spreadsheet = $service->spreadsheets->create($spreadsheet, array('fields' => 'spreadsheetId'));
// Print the new spreadsheet's ID
echo 'Spreadsheet ID: ' . $spreadsheet->getSpreadsheetId();
}
I was creating googlesheet with help of php client library and google sheet API but Don't know !! What is wrong with this code my new google sheet is not even created and the error is also not returned.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client_id = '*********.apps.googleusercontent.com';
$client_secret = '**************************';
$redirect_uri = 'https://{site}/wp-admin/plugins.php/oauth';
$client = new Google_Client();
$client->setClientId( $client_id );
$client->setClientSecret( $client_secret );
$client->setRedirectUri( $redirect_uri );
$client->setScopes( array('https://www.googleapis.com/auth/drive') );
if ( isset( $_GET['code'] ) ) {
$client->authenticate( $_GET['code'] );
$_SESSION['access_token'] = $client->getAccessToken();
header( 'Location: ' . filter_var( $redirect_uri, FILTER_SANITIZE_URL ) );
exit;
}
if ( ! isset( $_SESSION['access_token'] ) ) {
$auth_url = $client->createAuthUrl();
header( 'Location: ' . filter_var( $auth_url, FILTER_SANITIZE_URL ) );
exit;
}
$client->setAccessToken( $_SESSION['access_token'] );
$service = new Google_Service_Sheets($client);
$spreadsheet = new Google_Service_Sheets_Spreadsheet(array(
'properties' => array(
'title' => 'My New Spreadsheet'
),
'sheets' => array(
new Google_Service_Sheets_Sheet(array(
'properties' => array(
'title' => 'Sheet1',
'gridProperties' => array(
'rowCount' => 20,
'columnCount' => 12
)
)
))
)
));
$spreadsheet = $service->spreadsheets->create($spreadsheet, array('fields' => 'spreadsheetId'));
// Print the new spreadsheet's ID
echo 'Spreadsheet ID: ' . $spreadsheet->getSpreadsheetId();
}
Related
I have tried to use jwt token and pass it to the custom end point to get the response from an third party url. should i register the route and use the jwt token or can be use like the following code.
add_action( 'rest_api_init', function () {
register_rest_route( 'v1', '/certificates/', array(
'methods' => 'POST',
'callback' => 'update_payment_history',
) );
} );
function update_payment_history( $data ) {
$args = array(
'body' => array(
'username' => 'xxxx',
'password' => 'xxxxx'
),
);
$request = wp_remote_post( get_rest_url(null,'jwt-auth/v1/token'), $args );
if (is_wp_error($request)) return $request;
$response = wp_remote_retrieve_body( $request );
if (is_wp_error($response)) return $response;
$response = json_decode($response, true);
print_r($response);exit;
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $response['token']
)
);
$trans_response = wp_remote_get( $url, $args );
if ( is_array( $trans_response ) ) {
$response_code = wp_remote_retrieve_response_code( $trans_response );
$body = wp_remote_retrieve_body( $trans_response );
$body_data = json_decode($body);
print_r($body_data);
}
}
I am trying to create a shortcode to connect to an API but there is a problem with the shortcode. I know that it is because a function is inside a functinon but I can't figure out how to fix. I tried something that didn't work.
// Add Shortcode
function api_test() {
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
$this->execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
Just create execute_request() outside of shortcode.
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
function api_test() {
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
I've got this basic function as below:
function buy()
{
$item_id = ( int )$this->uri->segment( 3 );
if ( $item_id > '0' )
{
$item = $this->db->where( 'shop_id', $item_id )->get( 'shop' )->row();
if ( $item )
{
$player = $this->user->info( $this->user->id() );
if ( $player->users_money >= $item->shop_req_money && $player->users_credits >= $item->shop_req_credits)
{
$this->db->update( 'users_items', array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ), array( 'users_items_id' => $item->users_items_id ) );
$this->db->update( 'users', array( 'users_money' => $player->users_money - $item->shop_req_money, 'users_credits' => $player->users_credits - $item->shop_req_credits ), array( 'users_id' => $this->user->id() ) );
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db->escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
else
$this->session->set_flashdata( 'error', true );
}
}
header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
}
and I edited it like that to add additional check if the reg ip isn't the same as the other one and if so to set an error message.
function buy()
{
$item_id = ( int )$this->uri->segment( 3 );
if ( $item_id > '0' )
{
$item = $this->db->where( 'shop_id', $item_id )->get( 'shop' )->row();
if ( $item )
{
$player = $this->user->info( $this->user->id() );
$players = $this->user->info( $item->shop_users_id );
if ( $players->users_reg_ip === $player->users_reg_ip )
{
$this->session->set_flashdata( 'errorip', true );
}
elseif ( $player->users_money >= $item->shop_req_money && $player->users_credits >= $item->shop_req_credits)
{
$this->db->update( 'users_items', array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ), array( 'users_items_id' => $item->users_items_id ) );
$this->db->update( 'users', array( 'users_money' => $player->users_money - $item->shop_req_money, 'users_credits' => $player->users_credits - $item->shop_req_credits ), array( 'users_id' => $this->user->id() ) );
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db->escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
else
$this->session->set_flashdata( 'error', true );
}
}
header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
}
It works the way it is BUT basically I am asking if thats the correct way of doing that or there should be something else I can do similiar to that but better? Would be really appreciated if there any comments on my question. Thanks in advance!
Yes you can include that on the condition block. Like this:
if ( $players->users_reg_ip === $player->users_reg_ip) {
// trying to buy from the same IP
$this->session->set_flashdata( 'errorip', true );
}
elseif ( $player->users_money < $item->shop_req_money && $player->users_credits < $item->shop_req_credits) {
// if user has not enough money and user credits is less than shop requirement credits
// or maybe you mean OR ||
$this->session->set_flashdata( 'error', true );
}
else {
$this->db->update('users_items',
array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ),
array( 'users_items_id' => $item->users_items_id )
);
$this->db->update( 'users',
array( 'users_money' => $player->users_money - $item->shop_req_money,
'users_credits' => $player->users_credits - $item->shop_req_credits
),
array( 'users_id' => $this->user->id() )
);
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db-> escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
// instead of using referrer why not
// redirect('controller/method'); ?
Below is my code for uploading images, creating posts and to fanpage. Auto posting works fine apart from one thing - when images are posted to album, nothing shows up on the fan page timeline. Could you help me resolve the problem or point to some documentation. I have tried to google it, but none of the results from stackoverflow or facebook developer helped me.
$function ips_fanpage_post( $id, $row = false, $force_type = 'post' )
{
require_once( ABS_PATH . '/connect/facebook/facebook.php');
if( !is_array( $row ) )
{
$row = PD::getInstance()->simpleSelect( IPS__FILES, "`id` = '$id'", 1);
if( empty($row) )
{
ips_log( "ips_fanpage_post($id)" );
return;
}
global ${IPS_LNG};
$row['type'] = 'post';
$row['caption'] = ${IPS_LNG}['meta_site_title'];
$row['description'] = 'เยี่ยมไหม แย่ไหม ชอบไหม';
$row['image'] = IMG_LINK . '/' . $row['img_url'];
$row['link'] = seoLink($row['id'], $row['title']);
$row['message'] = 'เยี่ยมไหม แย่ไหม ชอบไหม';
}
$image = null;
if( !empty( $_FILES["file"]["tmp_name"] ) )
{
$image = realpath($_FILES["file"]["tmp_name"]);
}
else
{
if( file_exists( IMG_PATH . '/' . basename( $row['image'] ) ) )
{
$image = IMG_PATH . '/' . basename( $row['image'] );
}
elseif( file_exists( ABS_PATH . '/upload/img_obrazki/' . basename( $row['image'] ) ) )
{
$image = ABS_PATH . '/upload/img_obrazki/' . basename( $row['image'] );
}
elseif( file_exists( ABS_PATH . '/upload/import/' . basename( $row['image'] ) ) )
{
$image = ABS_PATH . '/upload/import/' . basename( $row['image'] );
}
}
if( empty( $image ) )
{
return array('Nie można odnależć określonego obrazka.');
}
$fanpage_id = Config::GET('apps_facebook_fanpageid');
$facebook = new Facebook(array(
'appId' => Config::GET('apps_facebook_appid'),
'secret' => Config::GET('apps_facebook_appsecret'),
'cookie' => true,
'fileUpload' => true
));
if( $row['type'] == 'upload' || $force_type == 'upload' )
{
$params = array(
'access_token' => Config::GET('apps_facebook_token')
);
$accounts = $facebook->api('/me/accounts', 'GET', $params);
foreach($accounts['data'] as $account)
{
if( $account['id'] == $fanpage_id || (isset($account['name']) && $account['name'] == $fanpage_id) )
{
$fanpage_token = $account['access_token'];
}
}
$image = str_replace( '_middle', '', $image );
if( !isset( $fanpage_token ) )
{
ips_log( 'Pusty $fanpage_token, prawdopodobnie nie jest adminem.' );
return false;
}
$params = array(
'message' => 'เยี่ยมไหม แย่ไหม ชอบไหม',
'image' => '#' . $image,
'no_story' => 1,
'aid' => $row['album_id'],
'access_token' => $fanpage_token
);
try
{
$rest = $facebook->api( '$row['album_id']' . '/photos', 'post', $params );
if( $rest )
{
$data = array(
'id' => 'NULL',
'file_id' => $row['album_id'],
'post_id' => $rest['id'],
'title' => $row['title'],
'data' => date("Y-m-d H:i:s"),
'link_post' => 'https://www.facebook.com/photo.php?fbid=' . $rest['id'],
'type' => 'upload'
);
PD::getInstance()->insert("fanpage_post", $data);
return true;
}
ips_log( $rest );
return false;
} catch (FacebookApiException $e) {
ips_log($e);
return $e->getMessage();
}
}
else
{
$image = str_replace( ABS_PATH, substr( ABS_URL, 0 , -1 ), $image );
if( substr( $image, 0 , 4 ) != 'http' )
{
$image = substr( ABS_URL, 0 , -1 ) . $image;
}
$attachment = '{
"name":"คลิกที่นี่ ตอนนี้",
"href":"'. $row['link'] .'",
"caption":"'. $row['caption'] .'",
"description":"'. $row['description'] .'",
"properties":null,
"media":[{
"type":"image",
"src":"' . $image . '",
"href":"' . $row['link'] . '",
}],
"auto_publish":true
}';
try {
$rest = $facebook->api(array(
"uid" => $fanpage_id,
"method" => "stream.publish",
"access_token" => Config::GET('apps_facebook_token'),
"message" => $row['message'],
"attachment" => $attachment,
"caption" => $row['caption']
));
if( $rest )
{
$data = array(
'id' => 'NULL',
'file_id' => $id,
'post_id' => $rest,
'title' => $row['title'],
'data' => date("Y-m-d H:i:s"),
'link_post' => 'https://www.facebook.com/'. str_replace('_', '/posts/', $rest),
'type' => 'post'
);
PD::getInstance()->insert("fanpage_post", $data);
return true;
}
ips_log( $rest );
return false;
} catch (FacebookApiException $e) {
/**
* Błąd zapisany do pliku log
*/
ips_log($e);
return false;
}
}
}
https://developers.facebook.com/docs/reference/api/page/#photos:
no_story: If set to 1, optionally suppresses the feed story that is automatically generated on the page when you upload a photo.
I'm trying to use a class to made some search using the twitter api v1.1 but everytime I get and authentication error message:
This is the link to the original class: https://gist.github.com/tw2113/5468916
This is the code I'm using:
<?php
/**
* Class for connecting to Twitter's API 1.1 using WordPress APIs
*/
class TwitterAuth11 {
protected $consumer_key = 'MCQ8u3TMuBAidL4AKBtQ';
protected $consumer_secret = 'HIyZbh1FTDtpOK9qdX5yP3ZmNobnJcb2lKnhPONg6WI';
protected $access_token = '104977066-dLQj8ibcxlafcsGiwTOanw1buy0OIejhy51PzFsc';
protected $access_token_secret = 'nUkWIGX21LICgw8ZqoxwfasisB4ma3YpzwXr7EzY8';
protected $url = 'https://api.twitter.com/1.1/';
protected function authenticate( $user, $return = true ) {
$body = json_decode( $body );
if ( $body && !empty( $response['headers']['status'] ) && $response['headers']['status'] == '200 OK' ) {
if ( $return == false ) $body = null;
$noauth = '';
$badauth = 'good';
} else {
$body = null;
$badauth = 'error';
$noauth = true;
}
return array(
'response' => $body,
'badauth' => $badauth,
'noauth' => $noauth,
);
}
function get_tweets( $user = '', $count = 1 ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user, 'count' => $count ) );
$args = $this->header_args( array( 'screen_name' => $user, 'count' => $count ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function search_tweets( $user = '', $count = 1, $search = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'q' => urlencode( $search ) ), 'search/tweets.json' );
$args = $this->header_args( array( 'q' => urlencode( $search ) ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function authenticate_user( $user = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user ), 'users/lookup.json' );
$args = $this->header_args( array( 'screen_name' => $user ) );
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return false;
$error = 'Could not access Twitter user.';
return $this->returnData( $response, $error );
}
protected function returnData( $response, $error_message = '' ) {
$body = wp_remote_retrieve_body( $response );
$json = json_decode( $body );
if ( isset( $json->errors ) ) {
$errors = new WP_Error( 'twitter_auth_error', $error_message );
foreach ( $json->errors as $key => $error ) {
$errors->add( 'twitter_auth_error', '<strong>ERROR '. $error->code .':</strong> '. $error->message );
}
return $errors;
}
return $json;
}
protected function header_args( $args = array() ) {
if ( !isset( $this->user ) || ! $this->user )
return null;
// Set our oauth data
$defaults = array(
//'screen_name' => $this->user,
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => base64_encode( substr(md5(rand(0, 1000000)), 0, 32 ) ),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $this->access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$oauth = wp_parse_args( $defaults, $args );
//echo '<pre>'. htmlentities( print_r( $oauth, true ) ) .'</pre>';
//echo '<br><br><hr><br>';
$base_info = $this->build_base( $this->base_url(), $oauth );
$composite_key = $this->consumer_secret .'&'. $this->access_token_secret;
// create our oauth signature
$oauth['oauth_signature'] = base64_encode( hash_hmac( 'sha1', $base_info, $composite_key, true ) );
echo '<span>'.$base_info .'</span>';
echo '<br><br><hr><br>';
echo '<span>'. urldecode( $base_info ) .'</span>';
echo '<br><br><hr><br>';
$auth_args = array(
'sslverify' => false,
'headers' => array(
'Authorization' => 'OAuth '. $this->authorize_header( $oauth ),
'Expect' => false,
'Accept-Encoding' => false
),
);
return $auth_args;
}
protected function build_base( $baseURI, $params ) {
$base = array();
ksort( $params );
foreach( $params as $key => $value ){
$base[] = $key .'='. rawurlencode( $value );
}
return 'GET&'. rawurlencode( $baseURI ) .'&'. rawurlencode( implode( '&', $base ) );
}
protected function authorize_header( $oauth ) {
$header = '';
$values = array();
foreach( $oauth as $key => $value ) {
if ( $key == 'screen_name' || $key == 'count' )
continue;
$values[] = $key .'="'. rawurlencode( $value ) .'"';
}
$header .= implode( ', ', $values );
return $header;
}
protected function twAPIurl( $params = false, $trail = 'statuses/user_timeline.json' ) {
// append trailing path
$this->base_url = $this->url . $trail;
// append query args
return $params ? add_query_arg( $params, $this->base_url ) : $this->base_url;
}
protected function base_url() {
// set it up
if ( !isset( $this->base_url ) )
$this->twAPIurl();
return $this->base_url;
}
}
add_action( 'all_admin_notices', 'testing_twitter_api');
/**
* Test the api in the WordPress Dashboard
*/
function testing_twitter_api() {
echo '<div id="message" class="updated"><p>';
$twitter = new TwitterAuth11();
// Search api
$search = $twitter->search_tweets( 'ntrzacatecas', 3, '#ntr from:212Toga OR from:jasonbarkerm OR from:ntrzacatecas OR from:AlbertoChiu OR from:marcazac OR from:ortegasaul' );
// uses proper wp_error objects
if ( is_wp_error( $search ) )
echo implode( '<br/>', $search->get_error_messages( 'twitter_auth_error' ) );
else
echo '<pre>'. htmlentities( print_r( $search, true ) ) .'</pre>';
echo '</p></div>';
}
Any ideas?
Thanks for the help
Try using the Twitter API 1.1 Client for WordPress.
It's very easy to implement and all you need is your consumer_key and consumer_secret.
Example (from the README):
<?php
// Include Twitter API Client
require_once( 'class-wp-twitter-api.php' );
// Set your personal data retrieved at https://dev.twitter.com/apps
$credentials = array(
'consumer_key' => 'xxxxxxxxxxxxxxxx',
'consumer_secret' => 'xxxxxxxxxxxxxxxx'
);
// Let's instantiate Wp_Twitter_Api with your credentials
$twitter_api = new Wp_Twitter_Api( $credentials );
// Example a - Retrieve last 5 tweets from my timeline (default type statuses/user_timeline)
$query = 'count=5&include_entities=true&include_rts=true&screen_name=micc1983';
var_dump( $twitter_api->query( $query ) );