Retrieve a multiple stripe charges in php - php

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

Related

Laravel API Validation errors to be displayed

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 cannot print the array that I am sending to the database - Laravel

I have the following function, but when I run it in Postman to see the result, it doesn't print any value to me, it doesn't even give me an error. The var_dump set if it detects them, but the array does not... I think there is something wrong in the method updateOrCreate , because when I print this variable with var_dump, I can't see anything in the console.
This is the function:
public function createBidRival(Request $request)
{
$response = array('code' => 400, 'error_msg' => []);
if (!$request->id_karatekas) array_push($response['error_msg'], 'id_karateka is required');
if (!$request->id_participant_bid_send ) array_push($response['error_msg'], 'id_participant_bid_send is required');
if (!$request->id_participant_bid_receive) array_push($response['error_msg'], ' id_participant_bid_receive is required');
if (!$request->bid_rival) array_push($response['error_msg'], 'bid rival is required');
if (!count($response['error_msg']) > 0) {
try {
var_dump($request->id_karatekas);
var_dump($request->id_participant_bid_send);
var_dump($request->id_participant_bid_receive);
var_dump($request->bid_rival);
$bidRival = new BidBetweenRivals();
$bidRival = BidBetweenRivals::updateOrCreate(
[
'id_participant_bid_send' => $request->id_participant_bid_send,
'id_participant_bid_receive' => $request->id_participant_bid_receive,
'id_karatekas' => $request->id_karatekas
],
[
'id_participant_bid_send' => $request->id_participant_bid_send,
'id_participant_bid_receive' => $request->id_participant_bid_receive,
'id_karatekas' => $request->id_karatekas,
'bid_rival' => $request->bid_rival
]
);
$bidBetweenRivals->save;
$response = array('code' => 200, 'bidBetweenRivals' => $bidRival, 'msg' => 'Bid created');
}catch(\Exception $exception) {
$response = array('code' => 500, 'error_msg' => $exception->getMessage());
}
}
}
Dump to see whether if (!count($response['error_msg']) > 0) true or not and also dump something in the catch block to see if exception is occurring or not.
You can also test by commenting out the updateOrCreate part to see if it is interfering.

How to make Facebook Marketing API for Ad Creative using php?

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

Paypal api, get BUSINESS_ERROR

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.

Getresponse lookup contact to see if exists

I have this code to find a contact in GetResponse to see if it exists.
The first part (getting the campaign) works, but getting the contact fails in an exception: Request have return error: Invalid params:
<?php
$jsonfile = 'jsonrpcclient.php';
if (file_exists($jsonfile))
{
require_once $jsonfile;
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$api_url = 'http://api2.getresponse.com';
$client = new jsonRPCClient($api_url);
$result = NULL;
// Get campaign
try
{
$result = $client->get_campaigns(
$api_key,
array (
'name' => array ( 'EQUALS' => 'my_customer_list' )
)
);
}
catch (Exception $e)
{
die($e->getMessage());
}
$campaigns = array_keys($result);
$CAMPAIGN_ID = array_pop($campaigns);
// Lookup contact
try
{
$result = $client->get_contacts(
$api_key,
array (
'campaigns' => $CAMPAIGN_ID,
'email' => $track_order_email
)
);
}
catch (Exception $e)
{
die($e->getMessage());
}
}
else
{
echo "Json include file NOT found";
}
?>
Any help would be appreciated in formatting the get_contacts parameters.
As I explained here: Getresponse API 2 (Adding Custom fields and contacts using PHP)
both of your parameters should be formatted differently.
Instead of:
array (
'campaigns' => $CAMPAIGN_ID,
'email' => $track_order_email
)
it should be:
array (
'campaigns' => array( $CAMPAIGN_ID ),
'email' => array( 'EQUALS' => $track_order_email )
)
Good luck! :)

Categories