I have to try-catch block for stripe payment to handle error responses, Now I am using laravel to code.
But after catching it gives me 500 internal server error, instead of storing an exception message, it catches the error with 500 Internal Server?
Here is my code:
try {
$customer = \Stripe\Customer::create([
'email' => $email,
'source' => $token,
]);
$customer_id = $customer->id;
$subscription = \Stripe\Subscription::create([
'customer' => $customer_id,
'items' => [['plan' => 'plan_id']], //plan-id is static as there is single plan
]);
$chargeJson = $subscription->jsonSerialize();
}
catch(Stripe_CardError $e) {
$error = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
$error = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
$error = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
$error = $e->getMessage();
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error = $e->getMessage();
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error = $e->getMessage();
}
$resp = array();
if(isset($chargeJson) && !empty($chargeJson['id'])) {
$resp['status'] = 1;
$resp['transactions_log'] = $chargeJson;
$resp['current_period_end'] = $chargeJson['current_period_end'];
$resp['transaction_id'] = $chargeJson['id']; // which is actually subcsription id
} else {
$resp['status'] = 0;
$resp['error'] = $error;
}
return $resp;
I am not sure how to handle it and store it.
I am pretty much sure I have catched the exception but I can't store it and further use it.
Related
I'm workin on PayPal Payments in PHP. Now i am using paypal recurring payment option all proccess don but last operation not done propery and payment not received.
Everything was fine until i got this error: http://prntscr.com/gtz4xx
Here is code
public function create_plan(){
// Create a new billing plan
$plan = new Plan();
$plan->setName('App Name Monthly Billing')
->setDescription('Monthly Subscription to the App Name')
->setType('fixed');
// Set billing plan definitions
$paymentDefinition = new PaymentDefinition();
$paymentDefinition->setName('Regular Payments')
->setType('REGULAR')
->setFrequency('Month')
->setFrequencyInterval('1')
->setCycles('12')
->setAmount(new Currency(array('value' => 100, 'currency' => 'USD')));
// Set merchant preferences
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl(URL::route('paypal.return'))
->setCancelUrl(URL::route('paypal.return'))
->setAutoBillAmount('yes')
->setInitialFailAmountAction('CONTINUE')
->setMaxFailAttempts('0')
->setSetupFee(new Currency(array('value' => 1, 'currency' => 'USD')));
$plan->setPaymentDefinitions(array($paymentDefinition));
$plan->setMerchantPreferences($merchantPreferences);
//create the plan
try {
$createdPlan = $plan->create($this->apiContext);
try {
$patch = new Patch();
$value = new PayPalModel('{"state":"ACTIVE"}');
$patch->setOp('replace')
->setPath('/')
->setValue($value);
$patchRequest = new PatchRequest();
$patchRequest->addPatch($patch);
$createdPlan->update($patchRequest, $this->apiContext);
$plan = Plan::get($createdPlan->getId(), $this->apiContext);
// Output plan id
//echo 'Plan ID:' . $plan->getId();
return redirect('subscribe/paypal/'.$plan->getId());
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
}
public function paypalRedirect($plan_id){
// Create new agreement
$agreement = new Agreement();
$agreement->setName('App Name Monthly Subscription Agreement')
->setDescription('Basic Subscription')
->setStartDate(\Carbon\Carbon::now()->addMinutes(5)->toIso8601String());
// Set plan id
$plan = new Plan();
$plan->setId($plan_id);
$agreement->setPlan($plan);
// Add payer type
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$agreement->setPayer($payer);
try {
// Create agreement
$agreement = $agreement->create($this->apiContext);
// Extract approval URL to redirect user
$approvalUrl = $agreement->getApprovalLink();
return redirect($approvalUrl);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
}
public function paypalReturn(Request $request){
$token = $request->token;
$agreement = new \PayPal\Api\Agreement();
try {
// Execute agreement
$result = $agreement->execute($token, $this->apiContext);
/* $user = Auth::user();
$user->role = 'subscriber';
$user->paypal = 1;
if(isset($result->id)){
$user->paypal_agreement_id = $result->id;
}
$user->save();*/
echo 'New Subscriber Created and Billed';
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo 'You have either cancelled the request or your session has expired';
}
}
Why this is happening? How can I fix that?
Please help me.
Thanks
Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
the try/catch method is not working compared to my previous store function that is working
Read up further on findOrFail. You can catch the exception it throws when it fails to find.
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
Following my code webservice soap:
if (isset($_POST["action"]) && $_POST["action"] == "login") {
$soapClient = new SoapClient(WEST_SOAP_WSDL,
array("trace" => WEST_SOAP_TRACE, "login" => WEST_SOAP_LOGIN, "password" => WEST_SOAP_PASS));
try {
$clienteId = $soapClient->loginAuth($_POST["username"]);
} catch (Exception $e) {
print_r($e);
}
if ($clienteId) {
session_regenerate_id(TRUE);
$_SESSION["auth"]["id"] = $clienteId;
$_SESSION["auth"]["username"] = $_POST["username"];
try {
$_SESSION['cliente'] = serialize($soapClient->getClientDataById($clienteId));
} catch (Exception $e) {
print_r($e);
}
How could I Restrict access to my php in subscriber panel in status below ? :
inactive
canceled
I have an exception class that looks like this
<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.
How can I make in such a way that the error class will catch all types of errors ?
The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.
I M Using YII to develop web application
i want to check if query executed successfully or not
$data = Yii::app()->db->createCommand($SQL);
$result = $data->queryAll();
if(count($result) == 0)
{
throw new SoapFault('Sender', 'Unable to get display information.');
}
if code will execute if select query return no result-set. but i want to check if query executed successfully or not. based on that i want to throw exception. then if query executed successfully and returned no result-set then some other exception.
how to do this ? any suggestions ?
try {
$result = $data->queryAll();
} catch (Exception $ex) {
echo 'Query failed', $ex->getMessage();
}
try
{
$result = Yii::app()->db->createCommand($sqlQuery)->execute();
echo 'success';
}
catch (Exception $e)
{
echo 'fail';
}