Terawallet credit function, Auto credit when purchasing

Viewed 21

I tried this code, and it works. But it automatically adds the credit to the person who sells the product. So, is it possible to add automatic credit to the person who buys the product, not the person who sells it? I tried to change this code but failed. It may seem easy to you, but my attempts were unsuccessful. I'm a bit new to this field, please excuse me.

   /**
 * Authomatically Top-up Multi vendor Woocommerce Seller on Complete order
 * @param int $order_id
 */
function izzycart_auto_topup_user_on_product_purchase( $order_id ) {
    $order = new WC_Order($order_id);

    /**
     * You may need order total and customer_id to compose 
     * Transaction message for top, which is why it is added
     * below as optional (if needed)
    */
    $total = $order->get_total(); // <=== Total order Price (if needed)
    $customer_id = $order->get_customer_id(); // <=== Customer ID (if needed)
    $order_items = $order->get_items(); // <=== Grab all items in order

    $item_details = [];

    foreach ( $order_items as $item ) {
        // Get the ID of each item in Order
        $product_id = $item->get_product_id();
        $item_details[] = [
            'product_name'  => $item->get_name(),
            'total'         => $item->get_total(),
            'author'        => get_post($product_id)->post_author // <=== The product/item author ID
        ];
    }

    //Loop through all product/items author and add topup their wallet
    foreach ($item_details as $item_detail) {
        $wallet = new Woo_Wallet_Wallet();

        // Get Administrator's percentage
        $adminsCut = 0.2 * $item_detail['total']; // <=== Admin Takes 20%

        // Get Author's Percentage
        $authorsCut = $item_detail['total'] - (0.2 * $item_detail['total']); // <=== Author Takes 80%

        //Top-Up Admin
        if( $item_detail['author'] != 1 ) {
             /**
             * By Default Administrator has an ID of 1
             * if Author of product is not Admin
            */
            $topUpAdmin = $wallet->credit(1, $adminsCut, "Top-Up cut from {$item_detail['product_name']} sales");

            //Top-Up Author of Product
            $topUpAuthor = $wallet->credit($item_detail['author'], $authorsCut, "Top-Up from {$item_detail['product_name']} purchase");
    }else {
            // Author of product is Admin. Give admin all the money
            $topUpAdmin = $wallet->credit(1, $item_detail['total'], "Top-Up from {$item_detail['product_name']} sales");
        }

    }
}
add_action( 'woocommerce_order_status_completed', 'izzycart_auto_topup_user_on_product_purchase', 10, 1 );

the code from

0 Answers
Related