Class 'Stripe\StripeCharge' not found - php

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

Related

Laravel Stripe Payment Error Redirect Not Working

If the payment is successful, it redirects to the "success" page, but if the payment fails, it does not redirect to the "cancel" page, it looks like the photo below. I will be glad if you can help, thank you.
/* stripe code */ else if ($payment_method == 'stripe') {
$stripe = array(
"secret_key" => $stripe_secret_key,
"publishable_key" => $stripe_publish_key
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
$customer = \Stripe\Customer::create(array(
'email' => $order_email,
'source' => $token
));
$item_name = $item_names_data;
$item_price = $amount * 100;
$currency = $site_currency;
$order_id = $purchase_token;
try {
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $item_price,
'currency' => $currency,
'description' => $item_name,
'metadata' => array(
'order_id' => $order_id
)
));
$chargeResponse = $charge->jsonSerialize();
if ($chargeResponse['paid'] == 1 && $chargeResponse['captured'] == 1) {
return view('success')->with($data_record);
}
} catch (\Stripe\Exception\CardException $e) {
return view('cancel');
}
}
There are multiple things unclear and it's hard to help you with just this information.
You are using Charge API which is an old and legacy API. It's
better to go with Payment Intent API.
It looks like you haven't written a full error handling logic. You can debug by catching all possible Error types, including the ApiErrorException you are receiving. See example on Stripe API Reference.

Stripe payment SCA

My current Stripe code is as below: as I pass to stripe.
Had been using following Stripe Library:
https://github.com/stripe/stripe-php
Its working fine as of now. Now I need to change code according to SCA. But I am total lost with code update.
My controller
$this->stripe_->add_charge_array($stripe_user_id, $order_info, $price * 100, $currency, $metadata);
$this->stripe_->pay($currency_id, , $stripeToken, $card_id);
$data = $this->stripe_->get_charge_response($stripe_user_id, , $order_id);
$order->setStripeChargeId($data['charge_id']);//Here I save to db
And in stripe library:
public function pay($currency_id, $stripe_token = null, $card_id = null, $account_id = null){
$charge = $this->charge_card($cart['amount'], $cart['currency'], $stripe_token, $description, $cart['metadata'], $currency_id, $account_id);
}
And my charge_card method connecting to Stripe
public function charge_card(){
try {
\Stripe\Stripe::setApiKey($STRIPE_KEY);
$charge = \Stripe\Charge::create(array(
"amount" => intval($amount),
"currency" => $currency,
"source" => $stripe_token, // obtained with Stripe.js
"description" => $description,
"metadata" => $metadata
));
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$result = self::put_stripe_error($e);
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
self::put_stripe_error($e);
}
return $charge;
}
Stripe library:
https://js.stripe.com/v3/
From what I did understand from documentation is that I need to change my charge_card method like below.
$intent = \Stripe\PaymentIntent::create([
'payment_method' => '{{PAYMENT_METHOD_ID}}',
'customer' => '{{CUSTOMER_ID}}',
'amount' => 1099,
'currency' => 'gbp',
'confirmation_method' => 'manual',
'confirm' => true,
'setup_future_usage' => 'off_session',
]);
But then I get payment method Id in $intent . How to proceed from here.
Documentation misses this.

I'm using Stripe API in my code and I have an error : You cannot use a Stripe token more than once: tok_1EIw1gKIAV9zC39qQnFXKzi6

I got an error saying :
Customer cus_EmVoBWWrqnWw4W does not have a linked source with ID tok_1EIw1gKIAV9zC39qQnFXKzi6.
here is my code :
\Stripe\Stripe::setApiKey("sk_test_rUFQ9fpJoK9TlRVJs1nSYd6C");
$user = new User();
$email = $user->getEmail();
//creation du client
$customer = \Stripe\Customer::create(array(
"email" => $email,
));
$charge = \Stripe\Charge::create(array(
"amount" => 2000,
"currency" => "eur",
"source" => $request ->request->get('stripeToken'),
"description" => "Stripe connect - Order 36",
"customer" => $customer->id
));
\Stripe\Stripe::setApiKey("sk_test_rUFQ9fpJoK9TlRVJs1nSYd6C");
$refund = \Stripe\Refund::create([
'charge' => $charge,
'amount' => 1000,
]);
You need to save the card to the customer and then charge the customer. After that, unless the customer has multiple sources and you want to use a specific one, you won't need to pass source to Charge::create.

Is there a way to pass the metadata from Subscription API to Charge API?

I have two functions namely charge and subscription, when a successful charge
happens I insert some metadata there look below:
Same for the subscription function:
Then I have a separate file which I will not post here because it only calls to the Charge list API to get all the successful charges to check all the metadatas in there, however I noticed that once I created a subscription via API it's only available there the metadata1 and metadata2.
When I view on the charge created by the subscription nothing was attached to its metadata. How can I attach the metadatas from the subscription to the charge that corresponds to it?
<?php
require_once('stripe-php-master/init.php');
require 'apiKeys.php';
$data = $_REQUEST['data'];
if(isset($data['stripeToken'])){
create_customer($data);
}else{
printResponse($data,"No Token");
}
//Create Customer
function create_customer($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$customer = \Stripe\Customer::create(array(
"description" => 'Widget Create Customer',
"source" => $data['stripeToken'],
"email" => $data['stripeEmail']
));
$data['customerID'] = $customer->id;
//create_charge($data);
create_subscription($data);
}catch(Exception $e){
echo $e->getMessage();
exit;
}
}//create_customer
//Create charge
function create_charge($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$settings = [
'currency' => 'aud',
'amount'=>5500,
'description' => 'Widget Payment for ' .$data['widget_name'],
'customer' => $data['customerID'],
'metadata'=>["metadata1" => $data['metadata1'],"metadata2" => $data['metadata2']]
];
// Get the payment token ID submitted by the form:
$charge = \Stripe\Charge::create($settings);
printResponse($data, $charge->status);
}catch(Exception $e){
printResponse($data,$e->getMessage());
exit;
}
}//create_charge
//Create subscription
function create_subscription($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$settings = [
'customer' => $data['customerID'],
'metadata'=>["metadata1" => $data['metadata1'],"metadata2" => $data['metadata2']],
'items' => [
[
'plan' => $data['widget_class']
]
]
];
$subscription = \Stripe\Subscription::create($settings);
printResponse($data,$subscription->status);
}catch(Exception $e){
printResponse($data,$e->getMessage());
exit;
}
}
function printResponse($data,$status){
//CREATE Response JSON
print_r(json_encode([
'customer_name'=> $data['customer_name'],
'metadata1' => $data['metadata1'],
'metadata2'=> $data['metadata2'],
'payment_status'=>$status
]));
}
?>
I just want the when someone subscribes the charge from the subscription event has the metadata1 and metadata2 attached to it.

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