Stripe: can't create session - php

I want to implement a paiement in Stripe using Checkout in server side.
I followed their tutorial but I can't return the id.
I used the following code, just added echo 1,2,3... to check where there is a problem.
When I execute the following code I just return "1".
(of course I have created an account on Stripe)
<?php
echo "1";
\Stripe\Stripe::setApiKey('sk_test_XXXXXXXXXXXXXXXXXXXX');
echo "2";
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'name' => 'T-shirt',
'description' => 'Comfortable cotton t-shirt',
'images' => ['https://example.com/t-shirt.png'],
'amount' => 500,
'currency' => 'eur',
'quantity' => 1,
]],
'success_url' => 'https://example.com/success',
'cancel_url' => 'https://example.com/cancel',
]);
echo "3";
$session_id = $object->id;
echo "4";
if ($session_id) {
echo "sessionID OK";
} else {
echo "No Session ID!";
}
echo "5";
?>
Do you know what is wrong ?

I cant see that you import the stripe library.
The go to way to do this is via composer.
If you already have composer you run composer require stripe
If not: install composer from https://getcomposer.org
And then include the path to the generated autoload.php file like this: require "/path/to/vendor/autoload.php";
You could check here for offical stripe docs (referencing what i have said): https://stripe.com/docs/development#php

Related

How to pass auth0 access tokken in Wordpress url to login?

I have two apps one is develop in react and one is in Wordpress. Both the applications have login page and only login if user is valid in auth0. I am looking for some help like if users already logged in the react application and open wordpress application in new tab then it will not ask for login again or by pass login page and directly enters in the wordpress website. Anyyone have any idea on this. I used auth0 sdk to authenticate the users from auth0.
<?php
declare(strict_types=1);
use Auth0\Quickstart\Application;
use Auth0\SDK\API\Authentication;
use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;
use Auth0\SDK\Utility\HttpResponse;
use Auth0\SDK\Token;
// Import the Composer Autoloader to make the SDK classes accessible:
require 'vendor/autoload.php';
/**
* This file bootstraps our application.
*/
require __DIR__ . DIRECTORY_SEPARATOR . 'public/bootstrap.php';
// Import the files necessary for our Quickstart Application.
foreach ([
'vendor/autoload.php', // Composer autoloader, for our dependencies, such as the SDK
itself.
// These classes are application boilerplate and not directly relevant to SDK usage:
'src/ApplicationRouter.php',
'src/ApplicationTemplates.php',
'src/ApplicationErrorHandler.php',
// Import our Application class, where our app logic resides, and where we'll make our
SDK calls.
'src/Application.php',
] as $import) {
require_once join(DIRECTORY_SEPARATOR, [APP_ROOT, $import]);
}
// Load our environment variables from the .env file:
(Dotenv\Dotenv::createImmutable(__DIR__))->load();
try {
$configuration = new SdkConfiguration([
'domain' => $_ENV['AUTH0_DOMAIN'],
'cookieSecret' => uniqid(),
'clientId' => $_ENV['AUTH0_CLIENT_ID'],
'redirectUri' => 'http://127.0.0.1:3000/callback',
'audience' => [$_ENV['AUTH0_AUDIENCE']],
'scope' => ['openid profile', 'openid', 'profile', 'read'],
'clientSecret' => $_ENV['AUTH0_CLIENT_SECRET'],
'Issuer'=> 'https://m3techdevelop.us.auth0.com/',
'Realm' => 'Username-Password-Authentication',
'EnableAuth0' => true,
'connection' => 'con_y8vfupM7o6CN0fhn'
]);
$sdk = new Auth0($configuration);
header("Content-Type:application/json");
$inputData = file_get_contents('php://input');
$data = json_decode($inputData);
if(!$data){
return ;
}
$username = $data->user_login;
$password = $data->user_password;
$auth0 = new \Auth0\SDK\API\Authentication($configuration);
$request = $sdk->authentication()->login($username, $password,'Username-Password-
Authentication');
$decoded = HttpResponse::decodeContent($request);
if(isset($decoded['error'])){
echo json_encode(array('status' => 'ERROR', 'message' => $decoded['error'], 'data'
=> null)); exit();
}
// $access_token = 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9tM3RlY2hkZXZlbG9wLnVzLmF1dGgwLmNvbS8ifQ..Qow1fYemmnbuTth3.sS-MPCxSq1leLaiXDTqrvYIamFrUtbwos--Azfbl0HNCdmHTEnbqo6ANVUmwshthjUMsODWTYKxduaD55XyCOp-9perWheEumIA_QSm_E8Y-owb9ogGdWzuxNfX0sQHNk7iTgX1G9eabcoSTGDRmpaItIpbTo1STMv0S93WuEX5-qSWljNWMhImiWvALUst6MUqnJdTQdmwLjHevHmck8eBOxeDdywHEA0R_BBq2sb7wzPSQlynPIc2EdhPFBC_dKT_kDaCbul2sxIpdGhillveifPqvFE7kjan7M5RtUHQdvgVXa6TZ3LtdGLEmszOjC9aU95PS0izIvXBftJyhFg7l-vOy7OxC2dxQXB5_hfmcC2k.4-Fk7bzS6jnuKHR0sngcsA';
$access_token = $decoded['access_token'];
if($access_token){
$responseToken = $sdk->authentication()->userInfo($access_token);
$userData = HttpResponse::decodeContent($responseToken);
echo json_encode(array('status' => 'OK', 'message' => 'User successfully loggedIn' ,
'data' => $userData)); exit();
}
} catch (Exception $e) {
echo json_encode(array('status' => 'ERROR', 'message' => 'Something went wrong',
'data'
=> null)); exit();
}

Class "Stripe\Stripe" not found in codeigniter 4

i downloaded stripe php library by using Composer with this command
composer require stripe/stripe-php
then i added this in my app/config/autoload.php
public $psr4 = [ APP_NAMESPACE => APPPATH, // For custom app
namespace 'Config' => APPPATH . 'Config',
'Stripe' =>> ROOTPATH . 'vendor/stripe/stripe-php/init.php' // added here ];
then in controller i added this code but it giving me error Stripe/Stripe Not found
use Stripe;
\Stripe\Stripe::setApiKey(STRIPE_SECRET);
$paymentData = \Stripe\Charge::create ([
"amount" => $this->request->getPost('grandtotal'),
"currency" => "GBP",
"source" => $_REQUEST["stripeToken"],
"description" => "Test payment via Stripe From Rahul"
]);
$paymentData = array('success' => true, 'data'=> $stripe);
echo '<pre>' , var_dump($paymentData) , '</pre>';
i followed one tutorial but it giving me this error, please help me
You could use autoloader to actually include the Stripe classes...
require_once('vendor/autoload.php');

How to integrate eway payment gateway to a php website?

Does anyone know how to integrate eway payment gateway to a normal php website ?
I have conected but it is showing the error when I am writing the code in this link :https://www.eway.com.au/developers/sdk/php
Its showing the error which is given below :
Error: eWAY library has encountered a problem connecting to Rapid
<?php
require_once 'lib/eway-rapid-php-master/include_eway.php';
// eWAY Credentials
$apiKey = 'F9802AS8MHb/rAm6UyRbT2d5eHjOZWhff++jtFOtMU';
$apiPassword = 'V6E';
$apiEndpoint = 'Sandbox';
// Create the eWAY Client
$client = \Eway\Rapid::createClient($apiKey, $apiPassword, $apiEndpoint);
// Transaction details - these would usually come from the application
$transaction = [
'Customer' => [
'FirstName' => 'John',
'LastName' => 'Smith',
'Street1' => 'Level 5',
'Street2' => '369 Queen Street',
'City' => 'Sydney',
'State' => 'NSW',
'PostalCode' => '2000',
'Country' => 'au',
'Email' => 'demo#example.org',
],
// These should be set to your actual website (on HTTPS of course)
'RedirectUrl' => "http://$_SERVER[HTTP_HOST]" . dirname($_SERVER['REQUEST_URI']) . '/response.php',
'CancelUrl' => "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
'TransactionType' => \Eway\Rapid\Enum\TransactionType::PURCHASE,
'Payment' => [
'TotalAmount' => 1000,
]
];
// Submit data to eWAY to get a Shared Page URL
$response = $client->createTransaction(\Eway\Rapid\Enum\ApiMethod::RESPONSIVE_SHARED, $transaction);
// Check for any errors
if (!$response->getErrors()) {
$sharedURL = $response->SharedPaymentUrl;
} else {
foreach ($response->getErrors() as $error) {
echo "Error: ".\Eway\Rapid::getMessage($error)."<br>";
}
die();
}
echo 'Pay with our secure payment page';
?>
I have written the code as shown above.
I realize you've sorted it by now or given up Lena but please find code is like below
$apiEndpoint = '\Eway\Rapid\Client::MODE_SANDBOX';

Class 'Stripe\StripeCharge' not found

I've had a look at a few answer to this quesition on Stack Overflow, but there solutions didnt work for me. Im receiving the following error whilst testing the Stripe API
Class 'Stripe\StripeCharge' not found
This is the code that I am using:
require_once('app/init.php');
\Stripe\Stripe::setApiKey($stripe['private']);
if(isset($_POST['stripeToken'])){
$token = $_POST['stripeToken'];
try {
\Stripe\StripeCharge::create(array(
"amount" => 2000,
"currency" => "gbp",
"card" => "$token",
"description" => $Email
));
} catch(Stripe_CardError $e){
//Error Payment
}
}
echo $_POST['stripeToken'];
/* Stripe Vairables */
$stripe = [
'publishable' => 'hidden',
'private' => 'hidden'
];
I didn't use composer to pull this as it works with the include of the "init" file (supposedly). Any help would be great!
The correct name of the class is \Stripe\Charge, not \Stripe\StripeCharge. You can see an example of a charge creation request in the API documentation: https://stripe.com/docs/api/php#create_charge
Also, the card parameter was renamed to source in the 2015-02-18 API version.
Another problem is that you assign the $stripe array with your API keys at the end. You need to assign it before you can use it in the call to \Stripe\Stripe::setApiKey().
There were a few other minor mistakes. Here is a corrected version of your code:
require_once('app/init.php');
/* Stripe variables */
$stripe = [
'publishable' => 'hidden',
'private' => 'hidden'
];
\Stripe\Stripe::setApiKey($stripe['private']);
if(isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
try {
$charge = \Stripe\Charge::create(array(
"amount" => 2000,
"currency" => "gbp",
"source" => $token,
"description" => $email
));
// echo $charge->id;
} catch(\Stripe\Error\Card $e) {
// Card error
}
}

How to Integration Stripe Payment gateway in laravel?

I followed this link.
I did what it said, but its throwing some error:
FatalErrorException in routes.php line 29:
Class 'Stripe' not found
Line 29 Stripe::setApiKey('sk_test_bDgMM85Y8hWWaRRBrulWNeng');
A few things to check...
Did you install your stripe dependency? composer require stripe/stripe-php
Did you composer dump-auto
Your tutorial link runs stripe from the Routes file. Which is in the global namespace. Are you executing this code from a Controller or from the routes file? If from a controller, then you will need to add a use statement at the top use Stripe\Stripe;
Finally, which version of the https://github.com/stripe/stripe-php package are you using? According to the readme, there is a legacy version and a new version. The new version is has an extra level of nesting and is accessed via Stripe\Stripe and Stripe\Charge:
Legacy Version
Stripe::setApiKey('d8e8fca2dc0f896fd7cb4cb0031ba249');
$myCard = array('number' => '4242424242424242', 'exp_month' => 8, 'exp_year' => 2018);
$charge = Stripe_Charge::create(array('card' => $myCard, 'amount' => 2000, 'currency' => 'usd'));
echo $charge;
New Version
\Stripe\Stripe::setApiKey('d8e8fca2dc0f896fd7cb4cb0031ba249');
$myCard = array('number' => '4242424242424242', 'exp_month' => 8, 'exp_year' => 2018);
$charge = \Stripe\Charge::create(array('card' => $myCard, 'amount' => 2000, 'currency' => 'usd'));
echo $charge;
Here is the thing I did and its working. Hope its work is case of your:
try {
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$customer = \Stripe\Customer::create([
'name' => 'Jenny Rosen',
'email' => 'jenyy#hotmail.co.us',
'address' => [
'line1' => '510 Townsend St',
'postal_code' => '98140',
'city' => 'San Francisco',
'state' => 'CA',
'country' => 'US',
],
]);
\Stripe\Customer::createSource(
$customer->id,
['source' => $request->stripeToken]
);
Stripe\Charge::create ([
"customer" => $customer->id,
"amount" => 100 * 100,
"currency" => "usd",
"description" => "Test payment from stripe.test." ,
]);
Session::flash('success', 'Payment successful!');
} catch (\Exception $ex) {
return $ex->getMessage().' error occured';
Session::flash('error','Payment Failed.');
}
Charge Card
First of All create your stripe account
Stripe Register Page
if you already have Stripe account good to Go
Get API key from your Stripe and Add it to your project .env
Test API Key link : https://dashboard.stripe.com/test/apikeys
Live API Key link : https://dashboard.stripe.com/apikeys
NOTE : You can use API key directly in code but it is not good for security Install stripe-php via composer`
composer require stripe/stripe-php `
IF YOU ARE USING IN API
Setup client and API In code
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
Create token for Payment
$token = $stripe->tokens->create([
'card' => [
'number' => $card_number,
'exp_month' => $exp_month,
'exp_year' => $exp_year,
'cvc' => $cvc,
],
]);
Create Charge
$charge = Stripe\Charge::create ([
"amount" => $request->amount *100,
"currency" => $request->currency,
"source" => $token->id,
"description" => 'payment with credit/debit card'
]);
SECURITY RISK:
We should create token in front-end instead of sending card details on network we should send token
Add JS stripe to your blade file
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
Creating token On front-end using javaScript
Stripe.setPublishableKey($form.data('stripe-publishable-key'));
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
About stripeResponseHandler
This response handler will be a function where Stripe will redirect after success or failure of creating token
function stripeResponseHandler(status, response) {
if (response.error) {
/* token failed to create */
} else {
var token = response['id'];
/* you can send this token to back-end [Laravel Controller] then you need to charge function on backed */
}
}
Hope it will helpful for you

Categories