Multiple records are created for same order - php

I am using Database Transaction for a endpoint where staff can accept the order perform certain operation thereafter. I don't want same order to be assigned to different staff.I used Database transaction for that but the problem is multiple staff are assigned to same order when the staff accepts the order at same time.
The sample code is provided below:
try {
$message = [
"status_validation" => "Input status must have value assigned",
"unique" => "Order is assigned to other driver"
];
$this->validate($request, [
"restaurant_id" => 'required|integer|min:1',
"order_id" => 'required|integer|min:1|unique:driver_order,order_id',
"status" => 'required|status_validation'
], $message);
} catch (\Exception $ex) {
return response()->json([
"status" => "422",
"message" => $ex->response->original
], 422);
}
try {
DB::beginTransaction();
$assignOrderToDriver = $this->driverOrder->createDriverOrder($request);
DB:commit();
return response()->json([
"status" => "200",
"message" => "Order has been sucessfully assigned."
], 200);
}
catch (\Exception $ex) {
return response()->json([
"status" => "500",
"message" => $ex->getMessage()
], 500);
}
This issue is really creating problem in my project. Am I doing something wrong here?

Related

creating stripe connected subscriber account

I'm trying to first create a stripe account, then create the subscription and customer via the created account ID, and then ultimately link the two to create a 'connected' subscriber account on stripe and for it to appear under my connected accounts in my dashboard. So far the script is failing.
// Include Stripe PHP library
require_once 'stripe-php/init.php';
// Set API key
\Stripe\Stripe::setApiKey($STRIPE_API_KEY);
// Create Account
try {
$stripe = \Stripe\Account::create(array(
"email" => $email,
"country" => "US",
"type" => "custom",
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
));
// Add customer to stripe
try {
$customer = \Stripe\Customer::create(array(
"email" => $email,
"source" => $token
), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $customer){
// Convert price to cents
$priceCents = round($planPrice*100);
// Create a plan
try {
$plan = \Stripe\Plan::create(array(
"product" => [
"name" => $planName
],
"amount" => $priceCents,
"currency" => $currency,
"interval" => $planInterval,
"interval_count" => 1
), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $plan){
// Creates a new subscription
try {
$subscription = \Stripe\Subscription::create(array(
"customer" => $customer->id,
"items" => ["plan" => $plan->id]), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
echo $api_error;

Trying to add contacts via ActiveCampain API (Laravel)

I´m trying to integrate the RESTFUL API of ActiveCampaing to my Laravel environment, but I haven’t been so luckier, I'm using GuzzleHttp to make the requests, this is the error image and my code:
$client = new \GuzzleHttp\Client([‘base_uri’ => ‘https://myaccount.api-us1.com/api/3/’]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => [
'email' => 'test2021#test.com',
'first_name' => 'Julian',
'last_name' => 'Carax',
]
]);
echo $response->getStatusCode(); // 200
echo $response->getBody();
Hope you could help me! :D
you are not sending the data in correct format,
from the docs https://developers.activecampaign.com/reference#contact
{
"contact": {
"email": "johndoe#example.com",
"firstName": "John",
"lastName": "Doe",
"phone": "7223224241",
"fieldValues":[
{
"field":"1",
"value":"The Value for First Field"
},
{
"field":"6",
"value":"2008-01-20"
}
]
}
}
So create an array with key contact.
$contact["contact"] = [
"email" => "johndoe#example.com",
"firstName" => "John",
"lastName" => "Doe",
"phone" => "7223224241",
"fieldValues" => [
[
"field"=>"1",
"value"=>"The Value for First Field"
],
[
"field"=>"6",
"value"=>"2008-01-20"
]
]
];
Use try catch blocks as then you can catch your errors
try{
$client = new \GuzzleHttp\Client(["base_uri" => "https://myaccount.api-us1.com/api/3/"]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => $contact
]);
if($response->getStatusCode() == "200" || $response->getStatusCode() == "201"){
$arrResponse = json_decode($response->getBody(),true);
}
} catch(\GuzzleHttp\Exception\ClientException $e){
$error['error'] = $e->getMessage();
if ($e->hasResponse()){
$error['response'] = $e->getResponse()->getBody()->getContents();
}
// logging the request
\Illuminate\Support\Facades\Log::error("Guzzle Exception :: ", $error);
// take other actions
} catch(Exception $e){
return response()->json(
['message' => $e->getMessage()],
method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500);
}
You can check at the API docs that the fields email, first_name, last_name are under a contact node.
So make a contact array, put these fields inside and you should be fine.
The fields for first and last name are written line firstName and lastName - camelCase, not snake_case like you did.
Official php client
You should probably use the official ActiveCampaign php api client - that would make your life easier.

Laravel DB::select is breaking a future transaction

I have the following code :
DB::select($sql, $params);
DB::beginTransaction();
try {
DB::commit();
} catch (Exception $e) {
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
Which is causing the following error:
message: "There is no active transaction"
exception "PDOException"
There should be more instructions in the try statement but to show that none of them have an affect they have been removed. It seems to be that select is for some reason opening a transaction and not closing it. (The select is running an SP that returns two result sets but I only want one hence the use of select.) Everything works well without the select statement, and the select statement on it's own doesn't cause any errors and returns what I need. However, if I put the select statement in the try statement it causes an exception.
Thanks.
Does something like this work?
DB::beginTransaction();
DB::select($sql, $params);
try {
// your code that could fail
}
catch (Exception $e)
{
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
DB::commit();
return [
'code' => 200,
'error' => false,
'message' => 'Successful transaction.'
];

Laravel 7.0 Cashier - Stripe Payment Exception

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

How to fetch attribute in JSON object/array

I am currently using Amazon AWS SNS to send SMS to customers.
SMS works fine however I would like to simply display a success or error message when the form has been submitted depending on the outcome.
result after form submit on successful message below. I can see that statusCode with int(200) means that it was sent successfully. How can I fetch this and use it to display success or error message?
object(Aws\Result)#117(2){
[
"data": "Aws\Result": private
]=>array(2){
[
"MessageId"
]=>string(36)"f12f2261-5e13-54e8-b72e-37s26fd3c348"[
"#metadata"
]=>array(4){
[
"statusCode"
]=>int(200)[
"effectiveUri"
]=>string(35)"https://sns.eu-west-1.amazonaws.com"[
"headers"
]=>array(4){
[
"x-amzn-requestid"
]=>string(36)"716dase5-f048-5d35-8af0-sf36ce583d95"[
"content-type"
]=>string(8)"text/xml"[
"content-length"
]=>string(3)"294"[
"date"
]=>string(29)"Tue, 18 Jun 2019 19:31:28 GMT"
}[
"transferStats"
]=>array(1){
[
"http"
]=>array(1){
[
0
]=>array(0){
}
}
}
}
}[
"monitoringEvents": "Aws\Result": private
]=>array(0){
}
}
php code:
if(isset($_POST['gateeway'])){
$sender_id = $_POST['sender_id'];
$message = $_POST['message'];
$topic = 'arn:aws:sns:eu-west-1:52732446504:Testing';
try {
$result = $sns->publish([
'TargetArn' => $topic,
'Message' => $message,
'MessageAttributes' => [
'AWS.SNS.SMS.SenderID' => [
'DataType' => 'String',
'StringValue' => $sender_id,
],
'AWS.SNS.SMS.SMSType' => [
'DataType' => 'String',
'StringValue' => 'Promotional',
]
]
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}
}
You can get the status code like this
$metaInfo = $result->get('#metadata');
if($metaInfo ['statusCode'] === 200){
echo "Message Sent";
}

Categories