Stripe how to retrieve a Checkout Session's line items quantity? - stripe-payments

Create payment Sessions :
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'], //, 'fpx','alipay'
'line_items' => [[
'price_data' => [
'product_data' => [
'name' => "Topup USDT Wallet",
'images' => ["https://abc-uaha.co/uploads/site_logo/site_logo_20210321130054.png"],
'metadata' => [
'pro_id' => "USD".$_GET['price']/100
]
],
'unit_amount' => $_GET['price'],
'currency' => 'usd',
],
'quantity' => 1,
'description' => "Spartan Capital",
]],
'mode' => 'payment',
'success_url' => STRIPE_SUCCESS_URL.'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => STRIPE_CANCEL_URL,
]);
Refer to this docs : https://stripe.com/docs/api/checkout/sessions/line_items
I tried retrieve quantity from session:
try {
$checkout_session = \Stripe\Checkout\Session::retrieve([
'id' =>$session_id,
'expand' => ['line_items'],
]);
}catch(Exception $e) {
$api_error = $e->getMessage();
}
$line_items = $session->line_items[0].quantity;
echo $line_items; //it shows nothing, how to make it output "1"?

line_items are no longer included by default when retrieving Checkout Sessions. To get them in your retrieve call, you need to expand the line_item property.
You have two syntax errors :
You're missing a layer and using dot notation instead of PHP arrow syntax. The 2nd error is using $session instead of $checkout_session. So it should be :
$quantity = $checkout_session->line_items->data[0]->quantity;

Related

Stripe plan dynamic plan with sca

My issue:
I am working on a subscription or installment based application so the user gets whatever amount they had to for 3 or 6 months. I used stripe plan and schedule method to accomplish this:
When creating plan if the price is provided manually it works. Subscription is created
But for me sometimes there is calculation and amount varies like dynamic subscription and I want price to be dynamic.
But when I make amount" => $price, dynamic I get error
"This payment requires additional user action before it can be completed successfully. Payment can be completed using the PaymentIntent associated with the invoice. For more details see: https://stripe.com/docs/billing/subscriptions/overview#requires-action"
//Fetching intent
$intent = \Stripe\PaymentIntent::retrieve($paymentMethodParams->paymentIntent['id']);
//Create stripe user
$customer = \Stripe\Customer::create(([
'email' => 'evansd#ed.com',
'description' => 'Valued Customer',
'name' => 'Ed Ward',
'payment_method' => $paymentMethodParams->paymentMethod['id'],
'invoice_settings' =>
[
'default_payment_method' => $paymentMethodParams->paymentMethod['id']
]
]));
//Attaching paymentIntent with Customer
\Stripe\PaymentIntent::update($paymentMethodParams->paymentIntent['id'],
[
'customer' => $customer->id,
]
);
$intent = \Stripe\PaymentIntent::retrieve($paymentMethodParams->paymentIntent['id']);
$product = \Stripe\Product::create([
'name' => 'Payment plan for user',
'type' => 'service'
]);
//Creating plan for the customer
$plan = \Stripe\Plan::create(
array(
"product" => [
"name" => '#1 monthly Subscription'
],
"amount" => 200,
'nickname' => 'Payment Plan for order - ',
"currency" => 'GBP',
"interval" => 'month',
"interval_count" => 1,
'metadata' => [
]
)
);
$schedule = \Stripe\SubscriptionSchedule::create([
'customer' => $customer->id,
'start_date' => 'now',
'end_behavior' => 'cancel',
'metadata' => [
'local_id' => 'ABC 12345',
],
'phases' => [
[
'items' => [
[
'plan' => $plan->id,
],
],
'iterations'=>2
],
],
]);
$subscription_id = $schedule->subscription;
$result = \Stripe\Subscription::update($subscription_id,
[
'expand' => ['latest_invoice.payment_intent'],
]
);
$invoice = \Stripe\Invoice::retrieve($result->latest_invoice->id);
$invoice->pay();
What I did so far:
1: I even tried to set the $price = 1 and in phases 'quantity' => $price * $qty so it charges my price.
But then its same again.
This issue is only for certain test cards like : 4000 0027 6000 3184.(issue started when SCA was implemented). The other cards without sca rules works perfectly.
(These card that requires authentication on all transactions, regardless of how the card is set up.)
2:Created plan first and then created customer with the plan just like in mentioned in
Stripe Subscription Plans of Varying Amounts
I think its not user action, but its dynamic plan price issue.
If the price is static, it works and with sca card.
Thanks in advance.

Stripe Session with Shipping fee

How can I add shipping fee to stripe session create.
Here is what the have so far:
`
$line_items = [
'price_data' => [
'product_data' => [
'name' => $product->title
],
'unit_amount' => $product->price * 100,
'currency' => 'cad',
],
'quantity' => $product->qty
];
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain . '/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain . '/cart',
'payment_method_types' => ['card'],
'mode' => 'payment',
'line_items' => [$line_items]
]);
`
There is no way to have Stripe calculate shipping. In order to include a shipping amount, you can either increase the unit_amount on your current line item, or add another line item for the shipping total.
I would recommend creating the full product catalog inside of Stripe and consider using a standard Product for Shipping, then use a derived amount for the unit amount on that shipping price data with the standard Shipping product.

How to export excel with phone number format data using Maatwebsite Laravel

I'm confused with laravel export using maatwebsite, I want to keep phone number data after exported with "+62" but the result is "62...".
0 => array:17 [▼
"created_at" => "13 Sep 2016 # 04:37:16"
"merchant_name" => "XXX"
"merchant_email" => "XXX"
"merchant_phone" => "+6281290926402"
"merchant_address" => """
XXX
"""
"instagram_id" => "XXX"
"facebook_account" => "XXX"
"bank_name" => "CIMB Niaga"
"branch_name" => "XXX"
"province_name" => "DKI JAKARTA"
"city_name" => "JAKARTA SELATAN"
"district_name" => "CILANDAK"
"subdistrict_name" => "CIPETE SELATAN"
"postal_code" => "12410"
"account_name" => "XXX"
"account_number" => "XXX"
"merchant_status" => "active"
]
And here's my code to export the data
$result = Excel::create('Merchant Recap - '.$day.' '.$month.' '.$year.' '.$hour.':'.$minute.':'.$second, function ($excel) use ($day, $month, $year, $hour, $minute, $second, $data) {
$excel->sheet('Order Recap', function($sheet) use ($day, $month, $year, $hour, $minute, $second, $data) {
$row = 1;
$sheet->row($row, array('Merchant Name', 'Merchant Email', 'Merchant Phone', 'Merchant Address', 'Instagram', 'Facebook', 'Bank of Merchant', 'Branch', 'Province', 'City', 'District', 'Subdistrict', 'Postal Code', 'Account Name', 'Account Number', 'Status', 'Created Date'));
$sheet->cells('A'.$row.':Q'.$row, function($cells) {
$cells->setFont(array(
'size' => 12,
'bold' => true
));
});
$row++;
$sheet->setColumnFormat([
'C' => "aaaaa",
'O' => "#",
'Q' => "dd mmmm yyyy HH:mm:ss"
]);
foreach ($data as $key => $merchant) {
$sheet->row
($row, array(
$merchant->merchant_name
,$merchant->merchant_email
,$merchant->merchant_phone
....
,PHPExcel_Shared_Date::PHPToExcel(strtotime($created_at))
));
$sheet->getStyle('A'.$row.':Q'.$row)->getAlignment()->applyFromArray(
array('horizontal' => 'left')
);
$row++;
}
$sheet->setAutoFilter('A4:Q4');
});
})->export('xls');
Please, help me to solve that problem (export the data with phone number format). Also if phone number in database "081..." then after exported is "81...". I want to keep phone number in database full export to excel without changed format. Thank you in advance.
Try changing the column format from:
'C' => "aaaaa"
...to:
'C' => "###-###-####"
...or:
'C' => "[<=9999999]###-####;(###) ###-####"
Change the column format:
[
'D' => '+#'
]
I hope it helps.

Yii2- How to add a search box in grid view

I am new to Yii-2.
I have a grid-view in my index page which some entries are displaying.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'meter_id',
[
'label' => 'Meter MSN',
'value' => function ($d) {
return $d->meter->meter_msn;
},
// 'filter' => Html::activeDropDownList($searchModel, 'meter_id', \app\models\Meters::toArrayList(), ['prompt' => "All Meters", 'class' => 'form-control']),
],
'imsi',
'telecom',
'status',
[
'label' => 'Created By',
'value' => function ($data) {
if (is_object($data))
return $data->created->name;
return ' - ';
},
//'filter' => Html::activeDropDownList($searchModel, 'created_by', \app\models\User::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']),
],
'comments',
'historic',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Now I want to add a search-box against Meter MSN. In above code the filter is hidden so it was working but I don't want to add a drop-down instead I want a search box.
Below is my search class
public function search($params)
{
$query = MetersInventoryStore::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'meter_id' => $this->meter_id,
'created_by' => $this->created_by,
'updated_by' => $this->updated_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'store_id' => $this->store_id,
'meter_serial'=>$this->meter_serial,
// 'historic' => $this->historic,
'status'=>'SIM Installed',
])
// ->orFilterWhere(['status'=>'Communication Failed'])
;
// $query->andFilterWhere(['like', 'meter_serial', $this->meter_serial])
// ->andFilterWhere(['like','meter_id',$this->meter_id]);
$query->orderBy(['id' => SORT_DESC]);
return $dataProvider;
}
How can I place a search-box in it? As the simple search class will set up the search functionality by default. But my MSN value is coming from a function so I have no idea how can I place a search-box.
Any help would be highly appreciated.
for add filter field in a calculated column you should add a pubblic var in
in your search model
public function search($params)
{
public $your_column;
// declare as safe
public function rules()
{
return [
...
[[ 'your_column', ], 'safe'],
];
}
$query = MetersInventoryStore::find();
and then refer to your_column in grid_view
...
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'meter_id',
[
'attribute' => 'your_column',
'label' => 'Meter MSN',
'value' => function ($d) {
return $d->meter->meter_msn;
},
],
And last your searchModel you must expand your filter condition for manage properly your calculated column based on the filter value you passed.
You can find some sample in this tutorial http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

Yii2 disable highlighting menu item

My main.php code
<?php
NavBar::begin([
'brandLabel' => 'Styl-dekoracje.pl',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'Orders', 'url' => ['/order']],
Yii::$app->user->isGuest ?
['label' => 'Login', 'url' => ['/site/login']] :
['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']],
],
]);
NavBar::end();
?>
When I click for login/logout or home item its will be highlight. But how can I disable highlighting for SiteController? Where is file who set item as active?
Each item insive Nav have active property.
Set it depending on current controller, action, or route.
Example:
[
'label' => 'Login',
'url' => ['/site/login'],
'active' => $this->context->route == 'site/login',
],
Setting this for site/logout doesn't make sense because it's immediate action with redirect.
Official documentation:
Nav $items
View $context
Controller $route
I am not familiar with Yii2, but in Yii there was an activeCssClass option.
'activeCssClass' => ''
The code above disbaled the higlighting of active menu item.
You can use Url::to() to make it work. This is just a workaround.
<?php
NavBar::begin([
'brandLabel' => 'Styl-dekoracje.pl',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Home', 'url' => Url::to(['/site/index'])],
['label' => 'Orders', 'url' => Url::to(['/order'])],
Yii::$app->user->isGuest ?
['label' => 'Login', 'url' => Url::to(['/site/login'])] :
['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => Url::to(['/site/logout']),
'linkOptions' => ['data-method' => 'post']],
],
]);
NavBar::end();
?>

Resources