Login with PayPal (PHP) -> 'Credential not found for default user.' - javascript

I always get the following error when I want to login with PayPal:
Fatal error: Uncaught exception 'PayPal\Exception\PayPalInvalidCredentialException' with message 'Credential not found for default user. Please make sure your configuration/APIContext has credential information' in /home/.sites/137/site1611/web/Website/PayPal-PHP-SDK/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalCredentialManager.php:154
I implemented the PayPal PHP SDK correctly and I already created a Sandbox User account in my PayPal developer dashboard. I also retrieve a correct refresh_token and access_token but I'm not able to retrieve the user information like email, name, etc. What am I doing wrong?
My JS on the 'Login with PayPal' page looks like that:
<span id="myContainer" style="position: absolute;top: 0;left: 0;z-index: 1000;"></span>
<script src="https://www.paypalobjects.com/js/external/api.js"></script>
<script>
paypal.use( ["login"], function(login) {
login.render ({
"appid": "ATAoL...nifIi",
"authend": "sandbox",
"scopes": "profile email address https://uri.paypal.com/services/paypalattributes",
"containerid": "myContainer",
"locale": "en-us",
"returnurl": "http://www.url.com/return.php"
});
});
</script>
And my PHP script at the returnurl looks like that:
error_reporting(E_ALL);
require __DIR__ . '/PayPal-PHP-SDK/autoload.php';
use PayPal\Rest\ApiContext;
use PayPal\Api\OpenIdTokeninfo;
use PayPal\Api\OpenIdUserinfo;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
$code = $_GET['code'];
$clientId = 'ATAoLjBG....AbL4vWj89y89nifIi';
$clientSecret = 'EKoaU4uh....YXwCjlCj6FadrRXAdx';
$apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret));
try {
$accessToken = OpenIdTokeninfo::createFromAuthorizationCode(array('code' => $code), null, null, $apiContext);
}
catch (PayPalConnectionException $ex) {
print_r('###################### Error'); exit(1);
}
print_r('###################### Success: ' . $accessToken);
$user = OpenIdUserinfo::getUserinfo(array('access_token' => $accessToken, $apiContext));
print_r($user);

In your last line, you are passing apicontext inside array by mistake ! Fix that and you should be fine.
You can see the sample code here: http://paypal.github.io/PayPal-PHP-SDK/sample/doc/lipp/GetUserInfo.html
This is how it should be :
$user = OpenIdUserinfo::getUserinfo(array('access_token' => $accessToken), $apiContext);
print_r($user);

Related

Stripe Checkout Integration

I'm trying to do the simplest possible thing: sending the user to Stripe's hosted checkout page with 1 product.
None of Stripe's examples seem to work, so far what I've got is:
PHP create-checkout-session.php
require_once 'shared.php';
// ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain . '/canceled.html',
'payment_method_types' => ['card'], //, 'alipay'
'mode' => 'payment',
'line_items' => [[
'amount' => $price,
'currency' => 'usd',
'name' => $product,
'quantity' => 1,
]]
]);
echo json_encode(['sessionId' => $checkout_session['id']]);
That PHP page correctly returns a session ID.
HTML
<html>
<head>
<title>Buy cool new product</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<button id="checkout-button">Checkout</button>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_key'); // removed for Stackoverflow post
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
// Create a new Checkout Session using the server-side endpoint you
// created in step 3.
fetch('create-checkout-session.php', {
method: 'POST',
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
</script>
</body>
</html>
When I click the button nothing happens and I get this error on Chrome devtools:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new t (https://js.stripe.com/v3/:1:11100)
at Lu (https://js.stripe.com/v3/:1:152624)
at qu (https://js.stripe.com/v3/:1:152923)
at Fu (https://js.stripe.com/v3/:1:153599)
at Bu (https://js.stripe.com/v3/:1:153713)
at e.redirectToCheckout (https://js.stripe.com/v3/:1:154128)
at https://emu.net/stripetest/test.html:24:25
I don't understand this error. It seems like the sessionId is not being passed correctly. The HTML code came directly from the Stripe doc at:
https://stripe.com/docs/payments/checkout/accept-a-payment
To be honest at this point I don't know where I'm supposed to look. None of the Stripe examples seem to work. Anyone have any idea what I'm doing wrong?
Judging by the structure of session you need to pass
{ sessionId: session.sessionId }
not
{ sessionId: session.id }
take a look at the error message:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new t (https://js.stripe.com/v3/:1:11100)
enter code here
You need to send back "sessionId: session.sessionId".

Verify existence of an element in a database table in a web site based with restful service

I have a web site based with restful service, my problem is the verify of existence of the user autentication token situated in the localstorage of the browser using html5.
I use jQuery to pass the token from client to server to verify if the token exist, but if the token exist or not, the http status code returned is ever 200, I don't understand why.
My code for this work is divided in two page: one for the client and one for the server.
Home.html
<script type="text/javascript">
//other code
$(document).ready(function(){
localStorage.getItem("tokenMyWebSite");
document.getElementById("tokenhtml").innerHTML = localStorage.getItem("tokenMyWebSite");
if (localStorage.getItem("tokenMyWebSite") === null) {
window.location.replace("index.html");
} else {
var token = localStorage.getItem("tokenMyWebSite");
$.ajax( {
url: 'verify.php',
method: 'GET',
data: {
token: token, /* (backend): (frontend)*/
},
error:function(response){
// Simulate an HTTP redirect:
alert("Token is not present in database");
//localStorage.removeItem("tokenListenMe");
//window.location.replace("index.html");
}
});
}
});
//other code
</script>
verify.php
<?php
require ("debug.php");
$conn = new mysqli('localhost', 'root', '', 'MyWebSite');
$token = $conn->real_escape_string($_GET["token"]);
$sql = $conn->query("SELECT token FROM credenziali where token = '$token' LIMIT 1");
if (!$sql) {
http_response_code(404);
die(mysqli_error());
}
if(mysql_fetch_array($sql) !== false) {
http_response_code(200);
} else {
http_response_code(404);
}
mysqli_close($conn);
?>
You're mixing mysqli with mysql (deprecated). Note the lack of i here:
if(mysql_fetch_array($sql) !== false) {
Change that to mysqli_fetch_array and !== false to !== null (becuase mysqli_fetch_array() returns null, not false, on failure) and you should be good.

Page not redirecting after stripe checkout

I'm trying to add a stripe checkout button to my Leadpages landing page and after somebody completes a successful payment they're supposed to be redirected...but that redirect is not happening and I have no idea why.
Here's my page: http://snapstories.leadpages.co/test/... it's using test keys right now so you can test the checkout with Stripe's demo Visa number: 4242424242424242 and any expiry / security code...you'll see that you don't get redirected anywhere.
The demo-stripe.php script is supposed to send a 'success' response to my front-end code which triggers the redirect but that 'success' response is not being sent.
Here's the demo-stripe.php code:
<?php
require_once('./stripe/init.php');
$stripe = array(
"secret_key" => "sk_test_******",
"publishable_key" => "pk_test_******"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
// Get the credit card details submitted by the form
$token = $_GET['stripeToken'];
$email = $_GET['stripeEmail'];
$callback = $_GET['callback'];
try {
$customer = \Stripe\Customer::create(array(
"source" => $token,
"email" => $email
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => 100,
'currency' => 'usd'
));
header('Content-type: application/json');
$response_array['status'] = 'success';
echo $callback.'('.json_encode($response_array).')';
return 1;
}
catch ( \Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
}
?>
Here's the front-end code:
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_*****',
image: 'imagefile.png',
locale: 'auto',
token: function(token) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://snapstories.co/demo-stripe.php",
data: { stripeToken: token.id, stripeEmail: token.email},
success: function(data) {
window.location.href = "http//www.google.com";
},
});
}
});
document.getElementsByClassName('w-f73e4cf1-859d-e3e4-97af-8efccae7644a')[0].addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Testing',
description: 'testing',
amount: 100
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
I'm guessing your front-end code doesn't get to the success function.
Web console returns:
ReferenceError: $ is not defined
It looks like you're using the jQuery command $.ajax(), but I can't see where you've loaded the jQuery library. Try and load it above the script that uses it and see what happens
Be sure to double check the Stripe Checkout requirements. It seems, based on the link you posted, that you're using the HTTP protocol. Stripe Checkout requires you use the HTTPS protocol. That means if you're not using an ssl certificate on your page using Checkout, your page isn't going to return a token nor will it execute any further.

Passing Access Token from Facebook JS sdk to PHP session or cookie

I am working by this Facebook example: Getting Access Token From The JavaScript SDK Example
I am able to get the Facebook login part with JS just right.
But I want to get the user ID and Access Token from PHP for the server side actions such as Adding, Removing etc.
This is my JS part which works fine:
function fb_login() {
FB.login(function(response) {
if (response.authResponse) {
$.post("actions.php?js-login").done(function(data){
console.log(data);
});
init_app();
} else {
alert('User cancelled login or did not fully authorize.');
}
});
}
And this is the PHP side which can't seem to recognize the cookie or session that the JS is supposed to transfer:
if (isset($_GET['js-login'])) {
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} 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)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
exit;
}
I get the
No cookie set or no OAuth data could be obtained from cookie.
Message, but the user is logged in by JS.
You need to make sure to initialize the JavaScript SDK with the
{cookie: true}
option set. For example:
window.fbAsyncInit = function() {
FB.init({
appId: 'your-app-id',
cookie: true, // This is important, it's not enabled by default
version: 'v2.2'
});
};
If you do not set this option, the Facebook cookie will not be set and the PHP SDK will not be able to obtain an access token from the signed request that exists in the cookie.
Reference: https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript

Facebook javascript login to PHP SDK

I am using the FB facebook-php-sdk-v4-5.0-dev.zip API files.
I'm attempting to make the Facebook javascript and php SDKs work together. I have FB.login working find, I can make Graph requests, etc. Now I want to pass off the access token to my PHP code, and continue from there. I am initializing FB in javascript:
window.fbAsyncInit = function() {
FB.init({
appId : appId, //my appId
cookie : true, // enable cookies for session access
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
And now that FB in initialized, I do some other work using the API, after which I push out to my php code with:
window.location.replace(<my url>.php);
Inside my PHP application, I have the following:
$fb = new Facebook\Facebook([ 'app_id' => <my app_id>,
'app_secret' => <my app_secret>
'default_graph_version' => 'v2.2',
]);
$jsHelper = $fb->getJavaScriptHelper();
try
{
$accessToken = $jsHelper->getAccessToken();
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
// When Graph returns an error
print('Graph returned an error: ' . $e->getMessage() );
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
// When validation fails or other local issues
print( 'Facebook SDK returned an error: ' . $e->getMessage() );
exit;
}
if (isset($accessToken))
{
print("Logged in already");
}
else
{
print("Not logged in");
}
What I see is "Not logged in". From what I can tell, no cookie is generated (I dumped out $_COOKIE at the top of my PHP file). I have also monitored the network calls, and can see no cookie coming down from Facebook on my oauth requests... which is where I would assume that such a cookie would come from.
Thanks,
Andy
You need to set cookie to true while initializing the javascript object. Otherwise FB Javascript Api won't store a cookie.
FB.init({
appId : '{app-id}',
cookie : true,
version : 'v2.5'
});
I'd recommend that you update to the v5.0.0 of the PHP SDK, or is there a specific reason you're using this outdated one?
Furthermore, have a look at the example at
https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript/5.0.0
Copied sample code:
# /js-login.php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} 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)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in!
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');

Categories