How to Integration Stripe Payment gateway in laravel? - php

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

Related

Stripe Payment Integration React Native + Laravel

I want to integrate stripe payment in react native. Application's back-end is in Laravel.
This is what I came to know. We send amount, currency to the back-end that Intents Stripe payment and return a client_secret that is used in react native to send it to stripe and made payment successful.
This was the controller code as provided
Stripe::setApiKey(env('STRIPE_SECRET'));
$intent = PaymentIntent::create([
'amount' => ($request->grand_total - $request->coupon_discount) * 100,
'currency' => $request->currency
]);
$client_secret = $intent->client_secret;
but at $intent error is returned
[Error: Request failed with status code 500]
then I tried reference: https://stripe.com/docs/payments/payment-intents
\Stripe\Stripe::setApiKey('KEY_HERE');
\Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'usd',
'payment_method_types' => ['card'],
'confirm' => true,
]);
but the same error
Then I tried reference: https://stripe.com/docs/api/payment_intents/object
$stripe = new \Stripe\StripeClient(
'KEY_HERE'
);
$stripe->paymentIntents->create([
'amount' => 2000,
'currency' => 'usd',
'payment_method_types' => ['card'],
]);
actually I don't have knowledge about Laravel. If any one can suggest me what's wrong.
In stripe logs page post request is now successful after removing
'confirm' => true,
but still error is same 500.

Stripe PHP 3D secure payment without Stripe.JS?

I'm not using Stripe.JS because I need custom UI.
I have collected card information from my customer. I'm using the PHP SDK.
My workflow is
create customer
add/attach payment method to customer
create payment intent
Every works fine. Now the issue that is if the end user uses a 3D secure card, I get a next_action in the response
"next_action": {
"type": "use_stripe_sdk",
"use_stripe_sdk": {
"type": "three_d_secure_redirect",
"stripe_js": "https://hooks.stripe.com/redirect/authenticate/xxxxxx?client_secret=src_client_secret_xxxxxxx",
"source": "src_xxxxxx"
}
},
"next_source_action": {
"type": "use_stripe_sdk",
"use_stripe_sdk": {
"type": "three_d_secure_redirect",
"stripe_js": "https://hooks.stripe.com/redirect/authenticate/src_xxxxxx?client_secret=src_client_secret_xxxxxx",
"source": "src_xxxxxx"
}
},
The documentation then relies on Stripe.JS for this step to open a verification popup. I'm not using Stripe.JS for the first part of the implementation due to custom UI. Can I use Stripe.JS for this part only? Or how do I do this part WITHOUT using Stripe.JS ? How do I know if this next step is successful so I can confirm the payment? I also see in my dev dashboard that the payment so successful (confusing). But the documentation says I still need to confirm that payment intent?
Stripe has documentation about handling 3D Secure manually without Stripe.js which will guide you through what you need to do.
That said, you can create your own custom payment form with Stripe.js using Stripe Elements, which is strongly recommended to increase security and reduce your PCI compliance burden.
check https://stripe.com/docs/payments/payment-intents/migration-synchronous#elements-step-3. You need to use stripe.js, just to handle 3D secure.
Also check this example:
pay.php:
<?php
require './../vendor/autoload.php';
// This is your test secret API key.
\Stripe\Stripe::setApiKey('sk_test_51M5C27LYhXp3iY7Hp8Oz2PRPoUpYXbkTzMcx4xuiEmqayIIJTbGe1uTE2gtPg3mhJJpmoOBnFzZna9eQYr3xmV6T006etitKBC');
header('Content-Type: application/json');
try {
$stripe = new \Stripe\StripeClient('sk_test_51M5C27LYhXp3iY7Hp8Oz2PRPoUpYXbkTzMcx4xuiEmqayIIJTbGe1uTE2gtPg3mhJJpmoOBnFzZna9eQYr3xmV6T006etitKBC');
$cardData = [
'number' => '4000000000003220',
'exp_month' => 12,
'exp_year' => 2029,
'cvc' => '314',
];
$paymentData = [
'amount' => 1400,
'currency' => 'usd',
];
$token = $stripe->tokens->create([
'card' => $cardData,
]);
$paymentMethod = $stripe->paymentMethods->create([
'type' => 'card',
'card' => $cardData,
]);
// Create a PaymentIntent with amount and currency
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $paymentData['amount'],
'currency' => $paymentData['currency'],
'payment_method' => $paymentMethod,
'confirmation_method' => 'manual' // required to make 3d secure work
]);
$payment = $stripe->paymentIntents->confirm(
$paymentIntent->id,
[
'return_url' => 'YOUR_URL'
]);
if($payment->status == 'succeeded' || $payment->status == 'pending') echo json_encode(['redirect' => './succeed.php']);
// check if the status === requires_action, it means that 3D secure is required
elseif ($payment->status == 'requires_action') {
// Tell the client to handle the action
echo json_encode([
'requiresAction' => true,
'clientSecret' => $paymentIntent->client_secret
]);
exit();
}
else echo json_encode(['unexpected_error' => true]);
$charge = $stripe->charges->create([
'source' => $token,
'currency' => $paymentData['currency'],
'amount' => $paymentData['amount'],
'description' => 'My First Test Charge (created for API docs at https://www.stripe.com/docs/api)',
]);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
pay.js:
// This is your test publishable API key.
const stripe = Stripe("pk_test_51M5C27LYhXp3iY7HJOk6mEZu6caLGHi8QzyaAgMK1Ek1X7W8yeSSkeMVTTg9tO0S8UPnGX4Qo0tSJQzjJuUavbaH00qAFwCPbw");
document
.querySelector("#payment-form")
.addEventListener("submit", handleSubmitBackend);
async function handleSubmitBackend(e) {
e.preventDefault();
let response = await fetch("./php/pay.php", {
method: "POST",
});
let result = await response.json();
console.log(result);
if (result.requiresAction) {
// Use Stripe.js to handle the required card action
const { error: errorAction, paymentIntent } = await stripe.handleCardAction(result.clientSecret);
if (errorAction) {
// Show error from Stripe.js in payment form
console.log(errorAction);
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
const serverResponse = await fetch('/pay.php', {
method: 'POST',
});
}
}
else if(result.redirect) {
window.location.href = result.redirect;
}
}

Setting application fee with Omnipay/Stripe

I am using Laravel Omnipay and Omnipay/Stripe. I am trying to set an application fee (Stripe resource) to be collected but after I fill in card data and post to my controller I get this error:
InvalidRequestException in AbstractRequest.php line 213: The source
parameter is required
According to Omnipay/Stripe I am allowed to pass the application_fee (AbstractRequest reference) as a transactionFee but it is not working
My controller:
$payment = $request->amount;
$gateway = Omnipay::create('Stripe');
$gateway->setApiKey($company->settings()->get('gateway_keys')['Stripe']['test_secret']);
// Send purchase request
$response = $gateway->purchase(
[
'amount' => $payment,
'currency' => 'USD',
'token' => $request->stripeToken,
'transactionFee' => 100,
'stripe_account' => $company->settings()->get('gateway_keys')['Stripe']['account_id']
//'card' => $formData
]
)->send();
How do I get it where I can charge an application fee?

Unauthorized request Mollie Laravel

I'm trying to use Mollie in Laravel, but I'm encountering problems.
This is my code (token from the Laravel/Mollie Github page):
public function payApi($amount, $email) {
$payment = Mollie::api()->payments()->create([
'amount' => $amount,
'description' => $email,
'redirectUrl' => 'http://google.com',
]);
$payment = Mollie::api()->payments()->get($payment->id);
if ($payment->isPaid()) {
echo "Payment received";
}
}
This is the error:
Mollie_API_Exception in Base.php line 353: Error executing API call (request): Unauthorized request
I guess this is because I need to set the API test-key, but I don't know how to do that in Laravel-Mollie, it is documented for standard Mollie though.
As explained in the README.md, you need to connect Mollie to Laravel Socialite first. If you intend on using Mollie Connect, update config/services.php by adding this to the array:
'mollie' => [
'client_id' => env('MOLLIE_CLIENT_ID', 'app_xxx'),
'client_secret' => env('MOLLIE_CLIENT_SECRET'),
'redirect' => env('MOLLIE_REDIRECT_URI'),
],
And add your test-key in config/mollie.php.

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
}
}

Categories