HybridAuth send tweet with image - image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo

Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !

I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Related

Amazon payment integeration in Laravel and Vue.js

I am facing issue in Amazon payment gateway while completing checkoutsession.
Error which I am facing:
status=422; response={"reasonCode":"InvalidCheckoutSessionStatus","message":"You tried to call an operation on a Checkout Session that is in a state where that operation is not allowed"}
My code:
public function completeCheckout(Request $request){
$amazonpay_config = array(
'public_key_id' => config('amazonkey.public_key_id'),
'private_key' => config('amazonkey.private_key'),
'region' => 'UK',
'sandbox' => true
);
$payload = array(
"chargeAmount" => array(
"amount" => "100",
"currencyCode"=> "USD"
),
);
$payload = json_encode($payload);
try {
$checkoutSessionId = $request->checkoutSessionId;
// dd($checkoutSessionId);
$client = new ApayAPI($amazonpay_config);
$result = $client->completeCheckoutSession($checkoutSessionId, $payload, $headers = null);
if ($result['status'] === 200) {
// dd($result);
$response = json_decode($result['response'], true);
return $response;
// $response = json_decode($result['response'], true);
// $amazonPayRedirectUrl = $response['webCheckoutDetails']['amazonPayRedirectUrl'];
// echo "amazonPayRedirectUrl=$amazonPayRedirectUrl\n";
} else {
// check the error
echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
}
} catch (\Exception $e) {
// handle the exception
echo $e . "\n";
}
}
Make sure that prior to sending a request to complete checkout session that 1/the buyer has been redirected to checkoutResultReturnUrl (returned in response to update checkout session) and 2/ there are no constraints in the constraint object returned from update checkout session. If both of these conditions have been satisfied, know that complete checkout session must be requested within 24 hours of a buyer's redirect to checkoutResultReturnUrl or the checkout session will automatically cancelled.

Guzzle POST request: required body when execute request

I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.

Add a new value to insert it

hello i have this function insertion works very well
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id')));
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
the function recovers a single value user_id,I want to get a new value send by post (name admin_id) and isert in user_coupan_scan table
If you are sure that your code is working well, You can receive posted admin_id in following way.
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id'))); // You may need to change $this->post('user_id') to $this->input->post('user_id')
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['admin_id'] = $this->input->post('admin_id'); // make sure that the column name in your table is admin_id
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
In above answer, I have added one line i.e. receiving admin_id in post data.
$data['column_name_in_your_table'] = $this->input->post('name_in_post_data');
To receive data from post method you can do it like this
$some_name = $this->input-post('name');
Hope it helps.

How fix Facebook login error in codeigniter

Facebook SDK returned an error:
Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
I use fblogin() and fbcallback() in same controller. But face this error. Also do all steps in developer.facebook.com. Session is also started. But error says, do not match.
public function fblogin(){
$this->load->library('session');
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID', // Replace {app-id} with your app id
'app_secret' => '{APP_SECRET}',
'default_graph_version' => 'v2.5',//v2.5
]);
$helper = $fb->getRedirectLoginHelper();
// if (isset($_GET['state'])) {
// $helper->getPersistentDataHandler()->set('state', $_GET['state']);
// }
// $sURL = $helper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://www.collegeprintsusa.com/maintenance/signin/fbcallback', $permissions);
// echo 'Log in with Facebook!';
header("location: ".$loginUrl);
}
public function fbcallback() {
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.5',//v2.5
]);
// $serializedFacebookApp = serialize($fb);
// $unserializedFacebookApp = unserialize($serializedFacebookApp);
// echo $unserializedFacebookApp->getAccessToken();
$helper = $fb->getRedirectLoginHelper(); //'https://www.collegeprintsusa.com/maintenance/signin/fblogin'
// $_SESSION['FBRLH_state'] = $_REQUEST['state'];
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$fbClient = $fb->getClient();
$accessToken = $helper->getAccessToken($fbClient);
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: collegeprintsusa.com');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email', $accessToken);
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
// echo $fbid.','.$fbfullname; die();
# save the user nformation in session variable
$get_user_email = $this->user_model->get_single_user(['email' => $fbemail]);
if($get_user_email){
$res_user_fbid_update = $this->user_model->update_users(['id' => $get_user_email['id']],['facebook_id' => $fbid]);
if($res_user_fbid_update){
$this->session->set_userdata(['username' => $get_user_email['usename'],
'name' => $get_user_email['name'],
'last' => $get_user_email['last_name'],
'email' => $get_user_email['email'],
'type' => $get_user_email['user_type'],
'uid' => $get_user_email['id'],
'phone' => $get_user_email['phone'],
'address' => $get_user_email['address'],
'profile_image' => $get_user_email['profile_image'],
'disable' => $get_user_email['sms_update']]);
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}else{
$res_user_reg = $this->user_model->add_users([
'name' => $fbfullname,
'email' => $fbemail,
'phone' => 0,
'user_type' => 'customer',
'username' => $fbemail,
'password' => SALT . sha1($fbemail),
'token' => SALT . sha1($fbemail),
'facebook_id' => $fbid
]);
if($res_user_reg){
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: index.php");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
echo 'Log in with Facebook!';
}
}
Here I would like to suggest a better solution to log in with Facebook. Please use JavaScript instead of PHP, because PHP will redirect on facebook page & JavaScript will not redirect, It will open facebook login popup on own website, and it`s very quick & easy process according to performance.
Please follow below code to login with facebook using JavaScript.
$(document).ready(function($) {
window.fbAsyncInit = function() {
FB.init({
appId : '186770818730407', // Set YOUR APP ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fbLogin()
{
FB.login(function(response) {
if (response.authResponse) {
getFBUserInfo();
}else {
showToaster('error','User cancelled login or did not fully authorize.');
return false;
}
},{scope: 'email,user_photos,user_videos'});
}
function getFBUserInfo() {
FB.api('/me',{fields: "id,picture,email,first_name,gender,middle_name,name"}, function(response) {
$.ajax({
url : "http://example.com/welcome/facebook_login",
type : "POST",
data : {response:response},
dataType : "JSON",
beforeSend:function(){
ajaxindicatorstart();
},
success: function(resp){
ajaxindicatorstop();
if(resp.type == "success"){
fbLogout();
showToaster('success',resp.msg);
setTimeout(function(){
window.location.href = base_url() + 'account-setting';
},1000);
}
else{
showToaster('error',resp.msg);
}
},
error:function(error)
{
ajaxindicatorstop();
}
});
});
}
function fbLogout()
{
FB.logout(function(){ console.log('facebook logout') });
}
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
});
Hope You will like it.
Thanks

laravel verify shopify webhook

How can I verify my shopify webhooks in laravel?
Currently I'm doing the following:
//Validate secret
if ( Request::header( 'X-Shopify-Hmac-Sha256' ) ) {
$hmac_header = Request::header( 'X-Shopify-Hmac-Sha256' );
$data = Request::json();
$calculated_hmac = base64_encode( hash_hmac( 'sha256', $data, Config::get( 'constants.SHOPIFY_APP_SECRET' ), true ) );
if ( $hmac_header != $calculated_hmac ) {
return Response::json( array(
'error' => true,
'message' => "invalid secret" ),
403 );
}
}else {
return Response::json( array(
'error' => true,
'message' => "no secret" ),
403 );
}
But it fails with the following message:
#0 [internal function]: Illuminate\Exception\Handler->handleError(2, 'hash_hmac() exp...', '/Users/JS/Sites...', 58, Array)
#1 /Users/JS/Sites/xxx/api/app/controllers/CustomerController.php(58): hash_hmac('sha256', Object(Symfony\Component\HttpFoundation\ParameterBag), 'xxxxxxxxxx...', true)
I suspect it has sth to do with the way I get the request data:
$data = Request::json();
Does anyone have a solution? Thx!
Follow the example given in the Shopify docs: https://docs.shopify.com/api/webhooks/using-webhooks#verify-webhook
Replace
$data = Request::json();
with
$data = file_get_contents('php://input');
You can still use Request::json() elsewhere to get a ParameterBag for processing data from the webhook.
Here's my handler, works good:
public function handle($request, Closure $next)
{
$data = file_get_contents('php://input');
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, [SECRET], true));
if (!$hmac_header = $request->header('X-Shopify-Hmac-Sha256') or
$hmac_header != $calculated_hmac or $request->email == 'jon#doe.ca') {
return Response::json(['error' => true], 403);
}
return $next($request);
}
note that:
$request->email == 'jon#doe.ca' for case if there is not received test hooks for some reason
[SECRET] is the code from the store notifications settings under the webhook callback URL (All your webhooks will be signed with [SECRET] so you can verify their integrity.)

Resources