Deducting commission from accounts connected via Stripe in Laravel

73 Views Asked by At
<?php

namespace App\Http\Controllers\Stripe\MarketPlace\PaymentIntent;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;
use Stripe\PaymentIntent;
use Stripe\Token;
use Stripe\Product;
use Stripe\Price;
use Stripe\Checkout\Session;

class MultiVendor extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {

        try {
            Stripe::setApiKey(config('services.stripe.secret'));
         
            $stripe = new \Stripe\StripeClient([
                'api_key' => config('services.stripe.secret'),
            ]);
            $customer = Customer::create([
                'email' => '[email protected]',
                'source' => 'tok_visa', 
                'name' => 'Cavid Mehdi',
                'address' => [
                    'line1' => '123 Main St',
                    'city' => 'Anytown',
                    'state' => 'CA',
                    'postal_code' => '12345',
                    'country' => 'US',
                ],
                'metadata' => [
                    'order_id' => '1234',
                    'product_ids' => '5678'
                ]
            ]);

            $products = [];
            $prices = [];

            $onceConnectedAccountId = 'acct_1OZWoOGbXQHnE0RA'; 
            $secondConnectedAccountId = 'acct_1OZAXz2e37RpwEkH';



            $items = 
            [
                [
                    'name' => "Amazon Essentials Women's Skinny Jean", 
                    'description' => 'Authentic five-pocket styling, zip fly, shank button closure, and skinny leg. Available in short, regular, and tall inseam lengths. All denim is unique and will vary in color due to wash, finish, and dye.', 
                    'images' => ['https://m.media-amazon.com/images/I/7174TDiYiWL._AC_SY879_.jpg'],
                    'amount' => '10000',
                    'connected_account_id' => $onceConnectedAccountId
               ],
                [
                    'name' => 'Under Armour Unisex-Adult Lockdown 6 Basketball Shoe', 
                    'description' => 'Durable solid rubber outsole with herringbone traction pattern for ultimate on-court movement & control', 
                    'images' => ['https://m.media-amazon.com/images/I/51f97K1qS7L._AC_SY695_.jpg'],
                    'amount' => '15000',
                    'connected_account_id' => $onceConnectedAccountId
                ],
                [
                    'name' => "Amazon Essentials Women's Fleece Blouson Sleeve Crewneck Sweatshirt Dress", 
                    'description' => 'COZY BRUSHED BACK FLEECE: Buttery soft and comfy midweight cotton blend fleece with brushed interior.', 
                    'images' => ['https://m.media-amazon.com/images/I/714Io18547L._AC_SY879_.jpg'],
                    'amount' => '16200',
                    'connected_account_id' => $secondConnectedAccountId
                ],
            ];

            foreach ($items as $item) {
                $product = Product::create([
                    'name' => $item['name'],
                    'description' => $item['description'],
                    'images' => $item['images'],
                ]);

                $products[] = $product;

                $price = Price::create([
                    'product' => $product->id,
                    'unit_amount' => $item['amount'],
                    'currency' => 'usd',
                ]);

                $prices[] = $price;

                // Connect ID'ye göre komisyon miktarını belirle
                $connectedAccountId = $item['connected_account_id'];
                $applicationFeePercentage = 5;
                $applicationFeeAmount = $price->unit_amount * ($applicationFeePercentage / 100);

                // Payment Intent oluştur
                $paymentIntent = $stripe->paymentIntents->create([
                    'amount' => $price->unit_amount,
                    'currency' => $price->currency,
                    'automatic_payment_methods' => ['enabled' => true],
                    'application_fee_amount' => $applicationFeeAmount,
                    'transfer_data' => [
                        'destination' => $connectedAccountId,
                    ],                   
                    'customer' => $customer->id,
                    //'payment_method' => $paymentMethod->id, 

                ]);

                $result = $stripe->paymentIntents->confirm([
                    'payment_intent' => $paymentIntent->id,
                    'payment_method' => 'pm_card_visa',
                    'return_url' => 'http://stripe-api.local',
                ]);
            }

              
            return $result;
        } 
        catch (ApiErrorException $e) 
        {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
            ], 500);
        }
       
          
    


        
    }
}

One of the 3 products is from one seller, the other two are from another seller. A customer comes and buys these products in one basket at the same time, and I have to deduct commission from both sellers. Could you edit the code accordingly?

Products are purchased from two different sellers at the same time in the cart and as a marketplace, I want to deduct transaction commission from both sellers.

1

There are 1 best solutions below

0
AudioBubble On
    <?php

namespace App\Http\Controllers\Stripe\PaymentIntent;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Customer;
use Stripe\Product;
use Stripe\Price;
use Stripe\PaymentIntent;

class Store extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {

        try {
            Stripe::setApiKey(config('services.stripe.secret'));

            $stripe = new \Stripe\StripeClient([
                'api_key' => config('services.stripe.secret'),
            ]);

            $customer = Customer::create([
                'email' => '[email protected]',
                'source' => 'tok_visa',
                'name' => 'Cavid Mehdi',
                'address' => [
                    'line1' => '123 Main St',
                    'city' => 'Anytown',
                    'state' => 'CA',
                    'postal_code' => '12345',
                    'country' => 'US',
                ],
                'metadata' => [
                    'order_id' => '1234',
                    'product_ids' => '5678',
                ],
            ]);

            $products = [];
            $prices = [];

            $items = [
                [
                    'name' => "Amazon Essentials Women's Skinny Jean",
                    'description' => 'Authentic five-pocket styling, zip fly, shank button closure, and skinny leg. Available in short, regular, and tall inseam lengths. All denim is unique and will vary in color due to wash, finish, and dye.',
                    'images' => ['https://m.media-amazon.com/images/I/7174TDiYiWL._AC_SY879_.jpg'],
                    'amount' => '20000',
                    'connected_account_id' => 'acct_1OZWoOGbXQHnE0RA',
                ],
                [
                    'name' => 'Under Armour Unisex-Adult Lockdown 6 Basketball Shoe',
                    'description' => 'Durable solid rubber outsole with herringbone traction pattern for ultimate on-court movement & control',
                    'images' => ['https://m.media-amazon.com/images/I/51f97K1qS7L._AC_SY695_.jpg'],
                    'amount' => '25000',
                    'connected_account_id' => 'acct_1OZAXz2e37RpwEkH',
                ],
                [
                    'name' => "Amazon Essentials Women's Fleece Blouson Sleeve Crewneck Sweatshirt Dress",
                    'description' => 'COZY BRUSHED BACK FLEECE: Buttery soft and comfy midweight cotton blend fleece with brushed interior.',
                    'images' => ['https://m.media-amazon.com/images/I/714Io18547L._AC_SY879_.jpg'],
                    'amount' => '30000',
                    'connected_account_id' => 'acct_1OZAXz2e37RpwEkH',
                ],
            ];

            $totalCommission = 0;

            foreach ($items as $item) {
               // dd($item);
                $product = Product::create([
                    'name' => $item['name'],
                    'description' => $item['description'],
                    'images' => $item['images'],
                ]);
                $products[] = $product;


                $price = Price::create([
                    'product' => $product->id,
                    'unit_amount' => $item['amount'],
                    'currency' => 'usd',
                ]);
                $prices[] = $price;

                $commissionAmount = $price->unit_amount * 0.05; 
               
                $paymentIntent = $stripe->paymentIntents->create([
                    'amount' => $price->unit_amount,
                    'currency' => 'usd',  
                    'customer' => $customer->id,
                    'automatic_payment_methods' => ['enabled' => true],
                    'application_fee_amount' => $commissionAmount,  
                    'transfer_data' => [
                        'destination' => $item['connected_account_id']
                    ],
                ]); 
                $result = $stripe->paymentIntents->confirm(
                    $paymentIntent->id,
                    [
                      'payment_method' => 'pm_card_visa',
                      'return_url' => 'http://stripe-api.local',
                    ]
                  );
              
            }


            return $result;
        } catch (\Stripe\Exception\ApiErrorException $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}

I was able to solve the problem this way.It worked when all operations were in the loop and confrim was specified correctly

*