I use paypal php sdk with sandbox mode. I have had errors on every request invoice create, before it worked fine.
I get this error from paypal.
code: 500
{
"name":"BUSINESS_ERROR",
"message":"Internal error.",
"debug_id":"71e1394c58958"
}
I can't find description of this error.
UPDATE
php code
try {
$payPalInvoice = new Invoice();
$payPalInvoice
->setMerchantInfo($this->merchantInfo)
->setBillingInfo([
new BillingInfo(
['email' => $invoice->getPaymentOptions()['email']]
)
]);
$payPalInvoice->setItems([
new InvoiceItem(
[
'name' => 'Order #' . $invoice->getOrder()->getId(),
'quantity' => 1,
'unit_price' => [
'currency' => 'USD',
'value' => $invoice->getOrder()->getAmountFormatted()
]
]
)
]);
$payPalInvoice->create($this->apiContext);
$payPalInvoice->send($this->apiContext);
$invoice->setForeignId($payPalInvoice->getId());
$invoice->setStateMessage($payPalInvoice->getStatus());
} catch (\PayPal\Exception\PayPalConnectionException $e) {
$invoice->setNextState('failed');
$error = 'code: ' . $e->getCode() . 'data: ' . json_encode($e->getData()); // Prints the detailed error message
$invoice->setError($error);
} catch (\Exception $e) {
$invoice->setNextState('failed');
$invoice->setError($e->getMessage());
}
I catch \PayPal\Exception\PayPalConnectionException error
This is paypal error. It works now.
Related
I am valdating the fields sent through api and need to display the errors.
I tried using try and catch no errors thrown. I have already have a code validating the login
try {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
I found no errors return has json instead it is redirecting to the login page
How to handle rerros in API and sent the message as json?None of the example show the way to handle errors. I tried with everything
And also how to handle errors while creating the model
try {
$company = Company::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'country_code' => $data['country_code']]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
$request->validate() should automatically return a response to the browser with errors if it fails, it doesn't throw an exception.
If your request is json it should detect that and return the error in a json error response, you can catch this in your front-end javascript and interrogate the response to interpret the error message.
e.g. using axios:
this.$axios.post('your api url',{data})
.then(response=>{
// ALL Good
})
.error(error=>{
// Catch returned error and process as required
});
If as you say I found no errors return has json instead it is redirecting to the login page this probably means that Laravel thinks that the request is a standard request, in which case it will issue a response()->back()->withErrors() which is probably what's sending it back to your login.
Try checking the original request type and ensure it's json, it should have a header of Accept: application/json.
Alternatively you can define your own validator
https://laravel.com/docs/7.x/validation#manually-creating-validators, and process the validation on the server as you like.
If there is error into validation then it will automatilly handle by laravel. You don't need to catch exception for that. It doesn't through exception.
Look it sample function which I have used for store Region
public function createRegion(Request $request)
{
$data = $request->all();
// Create a new validator instance.
$request->validate([
'name' => 'required',
'details' => 'required'
]);
try {
$region = new Region();
$region->name = $data['name'];
$region->details = $data['details'];
$region->save();
$content = array(
'success' => true,
'data' => $region,
'message' => trans('messages.region_added')
);
return response($content)->setStatusCode(200);
} catch (\Exception $e) {
$content = array(
'success' => false,
'data' => 'something went wrong.',
'message' => 'There was an error while processing your request: ' .
$e->getMessage()
);
return response($content)->setStatusCode(500);
}
}
I'm trying to create a customer before i charge them. on my charge.php file i have this.
if (isset($_POST['stripeToken'])) {
\Stripe\Stripe::setApiKey('___stripe_secret_key_____');
$api_error = false;
$token = $_POST['stripeToken'];
try {
$customer = \Stripe\Customer::create(array(
"name" => $name,
"email" => $email,
"source" => $token,
"metadata" => ['id' => $uid]
));
$stripe_id = $customer->id;
//update stripe ID to DB
User::model()->updateByPk($uid, array('stripe_id' => $stripe_id));
} catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $stripe_id) {
try {
$charge = \Stripe\Charge::create(
array(
'customer' => $stripe_id, //customer id
'amount' => $_POST['stripe-amount'],
'currency' => strtolower($_POST['stripe-currency']),
'description' => 'US Report',
'metadata' => [
'Currency' => $_POST['stripe-currency'],
'Invoice' => $_POST['ref_id'],
],
'receipt_email' => $email,
), array (
'idempotency_key' => preg_replace('/[^a-z\d]/im', '', $_POST['idempotency']),
)
);
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
$api_error = 'Status is:' . $e->getHttpStatus() . '<br />';
$api_error .= 'Type is:' . $e->getError()->type . '<br />';
$api_error .= 'Code is:' . $e->getError()->code . '<br />';
// param is '' in this case
$api_error .= 'Param is:' . $e->getError()->param . '<br />';
$api_error .= 'Message is:' . $e->getError()->message . '<br />';
}
I'm using my own HTML form for the credit card , expiry and ccv. and included https://js.stripe.com/v3/ in my page.
When i submit my payment i get this error
Charge creation failed! Status is:402
Type is:card_error
Code is:missing
Param is:card
Message is:Cannot charge a customer that has no active card
Any idea what i'm missing here?
The only path that I see here that would cause that error is if $_POST['stripeToken'] is blank or null. I don't see that you're checking for that. If you look in your Stripe Dashboard logs, you should be able to see the exact parameters sent by your script to the "create customer" endpoint.
Beyond that, if you're still stuck I'd send the request ID (req_xxx) to Stripe Support along with your example code so that someone can take a closer look.
Try to pass Stripe token in source parameter when creating the charge as well.
$charge = \Stripe\Charge::create(
array(
'customer' => $stripe_id, //customer id
'source' => $token,
'amount' => $_POST['stripe-amount'],
'currency' => strtolower($_POST['stripe-currency']),
'description' => 'US Report',
'metadata' => [
'Currency' => $_POST['stripe-currency'],
'Invoice' => $_POST['ref_id'],
],
'receipt_email' => $email,
), array (
'idempotency_key' => preg_replace('/[^a-z\d]/im', '', $_POST['idempotency']),
)
);
Didn't need this before, but I added it and now my code works again.
No idea why :p
\Stripe\Customer::createSource(
$stripe_id,
array('source' => $token)
);
Added this before my $charge = \Stripe\Charge::create()
I'm having problem on this Laravel Cashier Stripe payment. I need to combine the charge and new subscription as one so that when there is an IncompletePayment exceptions I can still get the stripe webhooks.
try{
$user->charge(1000, $creditCard->id, [
'description' => 'Premium Registration',
])
$user->newSubscription('premium_member', $recurring)
->create($creditCard->id);
}
} catch (IncompletePayment $e) {
$intent = \Stripe\PaymentIntent::retrieve($e->payment->id);
$intent->confirm([
'return_url' => url('api/payments-3d-success'),
]);
return response()->json([
'e' => $intent,
]);
}
Another way is to catch the exception and build like laravel way of handling Incomplete exceptions.
try{
$subscription = \Stripe\Subscription::create([
'customer' => $customer->id,
'items' => [[
'price' => $recurring,
]],
'add_invoice_items' => [[
'price' => $oneTime,
]],
]);
}
//I need to catch the exception here from stripe and build like a laravel way like IncompletePayment exceptions
catch(Exception $e){
$intent = \Stripe\PaymentIntent::retrieve($e->payment->id);
$intent->confirm([
'return_url' => url('api/payments-3d-success'),
]);
return response()->json([
'e' => $intent,
]);
}
Please let me know how you handle this problem. Thanks
There is a way you can do this using Invoice Items: https://stripe.com/docs/billing/invoices/subscription#adding-upcoming-invoice-items
I just want to know if there is way to retrieve charges with multiples charges_id in stripe.
For example in the docs show how to get one charge. But we need get multiple charges. So, we don't want to made a multiple calls to the stripe method retrieve, this is to slow. We dont want to make this:
foreach ($result as $p_key => $payment) {
$charge = $this->CI->stripe_lib->retrieve_charge('ch_......', 'secret_key');
if (isset($charge['charge'])) {
$amount_charged = (float)$charge['charge']->amount / 100;
// echo "<pre>";
// print_r($amount_charged );
// echo "</pre>";
}
}
this is in Codeigniter. And this is the function on the library:
public function retrieve_charge($charge_id, $secret_key) {
$errors = array();
try {
\Stripe\Stripe::setApiKey($secret_key);
$charge = \Stripe\Charge::retrieve($charge_id);
return array('charge' => $charge);
} catch(Stripe_CardError $e) {
$errors = array('error' => false, 'message' => 'Card was declined.', 'e' => $e);
} catch (Stripe_InvalidRequestError $e) {
$errors = array('error' => false, 'message' => 'Invalid parameters were supplied to Stripe\'s API', 'e' => $e);
} catch (Stripe_AuthenticationError $e) {
$errors = array('error' => false, 'message' => 'Authentication with Stripe\'s API failed!', 'e' => $e);
} catch (Stripe_ApiConnectionError $e) {
$errors = array('error' => false, 'message' => 'Network communication with Stripe failed', 'e' => $e);
} catch (Stripe_Error $e) {
$errors = array('error' => false, 'message' => 'Stripe error. Something wrong just happened!', 'e' => $e);
} catch (Exception $e) {
if (isset($e->jsonBody['error']['type']) && $e->jsonBody['error']['type'] == 'idempotency_error') {
$errors = array('error' => false, 'message' => $e->getMessage(), 'e' => $e, 'type' => 'idempotency_error');
} else {
$errors = array('error' => false, 'message' => 'An error has occurred getting customer info.', 'e' => $e);
}
}
return $errors;
}
With this code: \Stripe\Charge::all(["limit" => 3]); returns all charge but in the docs I didn't see if this method returns me also a multiple charges id.
I appreciate all your help.
Thanks and I'm sorry for my english.
Thanks for your question. It seems you have already identified the right method to retrieve multiple charges using the PHP library!
You are correct in that \Stripe\Charge::all(["limit" => 3]) call [0] will return you multiple charges, up to the limit specified in the arguments [1].
In the response to the above request, you will receive an array of charge objects [2], each having an id field [3] that would be the charge ID.
Hope that helps! Please let me know if you have any questions.
Cheers,
Heath
[0] https://stripe.com/docs/api/charges/list?lang=php
[1] https://stripe.com/docs/api/charges/list?lang=php#list_charges-limit
[2] https://stripe.com/docs/api/charges/object?lang=php
[3] https://stripe.com/docs/api/charges/object?lang=php#charge_object-id
I am trying to create an ad creative but getting an invalid parameter error. The exception even does not specify which parameter is wrong.
try {
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'try it out',
AdCreativeLinkDataFields::LINK => 'http://www.google.com',
AdCreativeLinkDataFields::IMAGE_HASH => '704e55dbf724243acfb8457a4f68a92a',
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, 'act_576834712392068');
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative Suite CRM',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
}
catch (Exception $e) {
echo 'Caught exception: ', $e, "\n";
}
Caught exception: exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'Invalid parameter'
It seems you have not added the Page where the creative has to be posted. I think adding AdCreativeObjectStorySpecFields::PAGE_ID => 'your published page id here' in object_story_spec array will resolve your problem.
Don't forget to set your app's status to active from development. It was the reason of the same failure. You can check your error in more detail with
catch (Exception $e) {
var_dump($e)
}