PayPal response code 400 - php

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

Related

Handle Try catch block in laravel

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.

Try Catch method in destroy function laravel

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);

PHP soap login auth

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

Simple slim session manager not read session in a different function

I am using the following slim session manager(https://github.com/bryanjhv/slim-session). I have separate functions for login, logout and user_data.
$app->post("/login", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try
{
if ($input->username && $input->password)
{
$user = Model::factory('Users')->where("username",$input->username)->where("password",md5($input->password))->find_one();
$session = new \SlimSession\Helper;
//set session
$session->set('userid', $user->id);
$status = 'success';
$message = 'Logged in successfully.';
}
else
{
$status = 'danger';
$message = 'Could not log you in. Please try again.';
}
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message,
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->post("/logout",function() use ($app)
{
try {
$session = new \SlimSession\Helper;
$session::destroy();
$status = 'success';
$message = 'You have been logged out successfully';
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->get("/user_data", function() use ($app)
{
try
{
$session = new \SlimSession\Helper;
//get session
$userid = $session->get('userid');
$_SESSION['userid'] = $userid;
if ($_SESSION['userid'])
{
$users = Model::factory('Users')->where('id',$_SESSION['userid'])->find_one();
$response = array(
'id'=>$users->id,
'username'=>$users->username,
'email'=>$users->email,
'phone_number'=>$users->phone_number,
'password'=>$users->password,
'type'=>$users->type,
'credits'=>$users->credits,
'profile_picture'=>$users->profile_picture,
);
}
else
{
$status = "danger";
$message = 'You need to be logged in to do that.';
$response = array(
'status' => $status,
'message' => $message
);
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
$response = array(
'status' => $status,
'message' => $message
);
}
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
The problem I am having is that when the user logs in I set a session variable in the /login function. But when the session variable i set in login function isn't being retrieved in the /user_data function.
Anyone knows whats going on?
Have you started session with session_start() ?
Correct logic to check session is as follows:
if (isset($_SESSION['userid']))
{
// session exists
// do further work
}

My Stripe payment is working perfect. But now i want to catch from Database

I am using Stripe Payment. I have integrated the Stripe checkout system in my Php website.
With Static prices it works good. But not I want to get Prices from My Database. And it shows on screen that it is charged. But in my strip account it is not sending money..
$charge = Stripe_Charge::create(array(
"amount" => 999999, // I want here $price from my database.
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
When i Add $price instead of static price 99999 it not sends money to my stripe payments. But when i add 99999 again , it start working. My Database is Okay All veriables and database connections are okay. Issue is only here.. How i can get it fixed..
If you want my full code..
include 'header.php'; //Connection File is in header.php
error_reporting(0);
try {
require_once('Stripe/lib/Stripe.php');
Stripe::setApiKey("sk_test_GkvxX3TWD6juGRLhZwP2LQ1x");
$req_id = $_REQUEST['order_id'];
$get_req = "SELECT * FROM `requests` WHERE `req_id` = '$req_id'";
$result = mysqli_query($dbc, $get_req);
while($row = mysqli_fetch_array($result)){
$req_id = $row['req_id'];
$request_title = $row['request_title'];
$username = $row['username'];
$user_id = $row['user_id'];
$price = $row['price'];
$request_time = $row['request_time'];
$req_date = $row['req_date'];
$category = $row['category'];
$sub_category = $row['sub_category'];
$from_address = $row['from_address'];
$to_address = $row['to_address'];
$from_state = $row['from_state'];
$to_state = $row['to_state'];
$from_city = $row['from_city'];
$to_city = $row['to_city'];
$req_desc = $row['req_desc'];
$status = $row['req_status'];
$paid = $row['paid'];
}
$charge = Stripe_Charge::create(array(
"amount" => 999999,
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
$status = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
echo 'Payment Done ';
$status = 1;
//print_r($token);
} else {
$errors['token'] = 'The order cannot be processed. You have not been charged.
Please confirm that you have JavaScript enabled and try again.';
echo "payment not successfully done.Please try again";
$status = 0;
}
} // End of form submission conditional.
}
catch(Stripe_CardError $e) {
}
//catch the errors in any way you like
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
if($status2 = 1){
$query = "UPDATE `requests` SET `req_status`='1', `paid`='1' WHERE `req_id`='$req_id'";
$result = mysqli_query($dbc,$query);
}else{
}
I have not seen in your code, what the output of $price is. So, while I do
not assume that $price, drawn from your database, is incorrectly prepared,
it is as mentioned in the Stripe documentation, necessary to express the
price in cents. Such that if you place this code
$findme = ".";
$pos = strpos($price, $findme);
$PosPlus = $pos+1;
$Part1=substr($price, 0, $pos);
$Part2=substr($price, $PosPlus);
$price = ($Part1.$Part2);
above the line you have,
$charge = Stripe_Charge::create(array( //.....
your charge should succeed.

Categories