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.
Related
I am using Hybridauth with Codeigniter to implement social login buttons in my app. I just require Google, Facebook & LinkedIn social login button. I have successfully implemented the Google sign & sign up method but the same code does not work for Facebook & LinkedIn, Here is the error I am getting always this exception,
ops, we ran into an issue! The authorization state
[state=HA-RBNC6FHJ54VZAM1KTD7EI3SPYG08U2OLWQ9X] of this page is either
invalid or has already been consumed.Unable to get your data!Try after
some time.
My config file for hybriduath.
<?php
$config['hybridauth'] = [
//Location where to redirect users once they authenticate with a provider
'callback' => 'http://localhost/insurance-experts/auth/social_auth',
//Providers specifics
'providers' => [
'Google' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
], //To populate in a similar way to Twitter
'Facebook' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
'LinkedIn' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
]
];
Here is the implementation of hybridauth
public function social_auth()
{
$user_profile = NULL;
$auth_provider = $this->input->get('auth_provider');
// Check if it is redirected url with code & state params
if (!isset($_GET['code'])) {
$user_role = $this->input->get('role');
// Save it in the session to reuse it after auth redirect
// We'll need it in case user does not exist
$_SESSION['temp_user_role'] = $user_role;
}
switch ($auth_provider) {
case GOOGLE:
$auth_provider = GOOGLE;
break;
case FACEBOOK:
$auth_provider = FACEBOOK;
break;
case LINKEDIN:
$auth_provider = LINKEDIN;
break;
default:
$auth_provider = GOOGLE;
break;
}
// Load the hybridauth config file
$this->config->load('hybridauth');
//First step is to build a configuration array to pass to `Hybridauth\Hybridauth`
$config = $this->config->item('hybridauth');
try {
//Feed configuration array to Hybridauth
$hybridauth = new Hybridauth($config);
//Attempt to authenticate users with a provider by name
$adapter = $hybridauth->authenticate($auth_provider);
//Retrieve the user's profile
$user_profile = $adapter->getUserProfile();
//Disconnect the adapter
$adapter->disconnect();
} catch (\Exception $e) {
echo 'Oops, we ran into an issue! ' . $e->getMessage();
}
if (!empty($user_profile)) {
$email = $user_profile->email;
// Check if email exist in DB then sign in the user
$user_data = $this->User_model->find(['email' => $email], USERS);
if (!empty($user_data) && count($user_data) > 0) {
$user = $user_data[0];
$user_role = "";
// Cross check the user role
$user_groups = $this->ion_auth->get_users_groups($user->id)->result();
if (!empty($user_groups)) {
$group = $user_groups[0];
switch ($group->id) {
case ROLE_INDIVIDUAL:
$user_role = ROLE_INDIVIDUAL_STRING;
break;
case ROLE_COMPANY:
$user_role = ROLE_COMPANY_STRING;
break;
}
} else {
// Something went wrong, Force logout user
redirect('auth/logout');
}
if (empty($user_role)) {
redirect('auth/logout');
}
// Explicitly set the user role here
// coz it required in header's menubar
$user->role = $user_role;
$login_done = $this->ion_auth->set_session($user);
if ($login_done == TRUE) {
// Everything is OK, redirect the user to home page
redirect('/');
} else {
echo "We could not logged you in this moment!Please try after some time.";
}
} else {
$this->create_user_via_social_sign_up($user_profile);
}
} else {
echo "Unable to get your data!Try after some time.";
}
}
private function create_user_via_social_sign_up($user_profile)
{
$user_role = check_group($_SESSION['temp_user_role']);
if (empty($user_profile) or empty($user_role)) {
// Something went wrong, Force logout user
redirect('auth/logout');
}
$email = $user_profile->email;
// Generate a random password,
$password = substr(md5(rand()), 0, 7);
$extra_data = [
'active' => 1,
'is_approved' => 1
];
$this->db->trans_start();
// Directly register user via Model method as no need to send the activation email
$id = $this->ion_auth_model->register($email, $password, $email, $extra_data, [$user_role]);
$user_data = $this->User_model->find(['id' => $id], USERS);
$user = $user_data[0];
// Add the role in user object
$user->role = $user_role;
$redirectProfileUrl = base_url('Profile_setting/');
if ($this->ion_auth->set_session($user)) {
// Create empty records in tables
$this->User_model->create_user_entries($user->id, $user_role);
if ($this->db->trans_status() !== false) {
$this->db->trans_commit();
redirect($redirectProfileUrl);
} else {
// Something went wrong rollback all the transactions & inform the user
$this->db->trans_rollback();
echo "Our system is down right now!Please try after some time.";
}
}
}
Codeigniter version: 3.x
Hybridauth Version: 3
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.
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
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.)
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();
}
?>