Home > Software engineering >  Woocommerce, payment successfully, run SQL command and email
Woocommerce, payment successfully, run SQL command and email

Time:11-17

I want to find a correct solution to my search. I use Woocommerce, I created 5 products including 3 dedicated virtual products. Here is the id of these products "Product 1" = #id23, "Product 2" = #id24 and "Product 3" = #id26 I would like when the payment for the order has been made successfully, the script (to be included in the functions.php of my child theme) analyzes my order, like that:

For example, if the buyer bought "product 1" in quantity x2, the script will run the script twice like adding something to the database (like an automatically generated password, a random serial number too, a date, the name of the product, a meta info ...). Please note: that the information looped twice must however be different, in particular for the password, a serial number, for example) And the buyer has to buy "Product 2", the script will have to be run again ....

So if you understood me this script would have to run n times including the products with their ids (id#23, id#24, id#26) and their quantities.

Here is a piece of code (which does not work) that is logical, since I am asking for help ;)

CODE CHANGED/UPDATED but doesn't works :(

                <?php
    // When payment is OK
    function so_32512552_payment_complete( $order_id )
    {
        // Connecting to external DB credentials
        // the file 'connect_sql.inc.php' is in the same directory than functions.php on your child theme?
        include ('connect.inc.php');
        // Create connection, try to avoid this, use wpdb class
        //$conn = new mysqli($DBHost, $DBLogin, $DBPass, $DBName);
        $conn = mysqli_connect($DBHost, $DBLogin, $DBPass, $DBName);
       
        // Check all specific products IDs (#23, #24 and #26) to be treat --- Possibility to add new products IDs later...
        // this must implement in other way, but depend on your process
        //$productsIds = array(18, 19, 20, 21, 22, 23);
        $productsIds = array(18, 19, 20, 21, 22, 23);
        // Check if the connection has no errors
        if (!$conn->connect_error)
        {
            $order = wc_get_order( $order_id );
            // remember $item is an instance of WC_Order_item
            foreach ( $order->get_items() as $item ) 
            {
                // no use $item['product_id']
                if ( in_array($item->get_id(), $productsIds) ) 
                {
                    //$qty = $order->get_quantity_from_item( $item );
                    // the correct way for get the quantity is this, but not necesary here, there will not be reuse
                    // $qty = $item->get_quantity();
                    // this is an infinite loop
                    // while ($qty):
                    for ($i=0; $i < $item->get_quantity(); $i  ) 
                    { 
                        // Get datas into variables
                        // this will not work
                        // $customer_name = $order->get_customer_name();
                        // use instead billing or shippings fields
                        $customer_name = $order->get_billing_first_name().' '.$order->get_billing_last_name();
                        // this will not work
                        // $customer_email = $order->get_customer_email();
                        $customer_email = $order->get_billing_email();
                        // this will not work
                        // use
                        $product = wc_get_product($item->get_id());
                        //$product_name = $order->get_product_from_item($item);
                        $product_name = $product->get_name();
                        // no use this, no good
                        // $password = rand(9999,9999999);
                        $password = wp_generate_password( 10, false );
                        // neither this
                        // $serial_number = rand(9999,9999999);
                        // this implementation depend on your project
                        $serial_number = rand(9999,9999999);
                        
                        // Add a new entry in DB thru SQL command
                        // where the sql is executed?
                        //$sql = "INSERT INTO tableTest_v5 (user_fullname, user_email, software_product, user_passwd, user_licensenumber, val1) VALUES ('$customer_name', '$customer_email', '$product_name', '$password', '$serial_number')";
                        
                        mysqli_query("INSERT INTO `tableTest_v5` (`id`, `state_account`, `user_email`, `user_passwd`, `user_fullname`, `user_corporate`, `user_licensenumber`, `software_product`, `software_license`, `activation_date`, `software_expiredate`, `wcid`, `user_computerinfos`, `activation_cpuname`, `activation_id`, `activation_cpt`, `superaccess`) VALUES (NULL, -1, 'email', NULL, 'Nick POHENIS', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 3, 0)");
                        
                        //$conn->query($sql);
                    
                        // Then entry added, prepare and send the mail to customer
                        // this not good, use other implementation if can
                        $message = 'Hi,'.$customer_name;
                        $message .= 'Your product: '.$product_name;
                        $message .= 'Name: '.$customer_name;
                        $message .= 'ID: '.$customer_email;
                        $message .= 'Password: '.$password;
                        $message .= 'Serial number: '.$serial_number;
                        wp_mail('[email protected]', 'Email: Additionnal Info', $message);
                    }
                    //endwhile;
                }
            }
            // Close DB
            //$conn->close();   
            mysqli_close($conn);
        } else {
            // no die, because we are in woocommerce task 'payment_complete'
            // register as other way for inform to you
            // die("Connection failed: " . $conn->connect_error);
        }
    }
    add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );
    ?>

Hope you understood, anyway, thank you very much in advance for your help. Because I've been doing research for weeks without success. Your help will be welcome !!!!

Regards, Nico

CodePudding user response:

<?php

// When payment is OK
// remove this, it is not in use
// global $woocommerce;

function so_32512552_payment_complete( $order_id )
{
    // Connecting to external DB credentials
    // the file 'connect_sql.inc.php' is in the same directory than functions.php on your child theme?
    include ('connect_sql.inc.php');
    // Create connection, try to avoid this, use wpdb class
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check all specific products IDs (#23, #24 and #26) to be treat --- Possibility to add new products IDs later...
    // this must implement in other way, but depend on your process
    $productsIds = array(23, 24, 26);
    // Check if the connection has no errors
    if (!$conn->connect_error)
    {
        $order = wc_get_order( $order_id );
        // remember $item is an instance of WC_Order_item
        foreach ( $order->get_items() as $item ) 
        {
            // no use $item['product_id']
            if ( in_array($item->get_id(), $productsIds) ) 
            {
                //$qty = $order->get_quantity_from_item( $item );
                // the correct way for get the quantity is this, but not necesary here, there will not be reuse
                // $qty = $item->get_quantity();
                // this is an infinite loop
                // while ($qty):
                for ($i=0; $i < $item->get_quantity(); $i  ) 
                { 
                    // Get datas into variables
                    // this will not work
                    // $customer_name = $order->get_customer_name();
                    // use instead billing or shippings fields
                    $customer_name = $order->get_billing_first_name().' '.$order->get_billing_last_name();
                    // this will not work
                    // $customer_email = $order->get_customer_email();
                    $customer_email = $order->get_billing_email();
                    // this will not work
                    // use
                    $product = wc_get_product($item->get_id());
                    //$product_name = $order->get_product_from_item($item);
                    $product_name = $product->get_name();
                    // no use this, no good
                    // $password = rand(9999,9999999);
                    $password = wp_generate_password( 16, false );
                    // neither this
                    // $serial_number = rand(9999,9999999);
                    // this implementation depend on your project
                    $serial_number = rand(9999,9999999);
                    
                    // Add a new entry in DB thru SQL command
                    // where the sql is executed?
                    $sql = "INSERT INTO MyData_v5 (fullname, email, productname, password, serialnumber, val1) VALUES ('$customer_name', '$customer_email', '$product_name', '$password', '$serial_number')";
                    // maybe $conn->query($sql);
                
                    // Then entry added, prepare and send the mail to customer
                    // this not good, use other implementation if can
                    // $message = 'Hi,'.$cumstomer_name;
                    // has an extra 'm'
                    $message = 'Hi,'.$customer_name;
                    // need '_'
                    $message .= 'Your product: '.$product_name;
                    // has an extra 'm'
                    // $message .= 'Name: '.$cumstomer_name;
                    $message .= 'Name: '.$customer_name;
                    $message .= 'ID: '.$customer_email;
                    $message .= 'Password: '.$password;
                    $message .= 'Serial number: '.$serial_number;
                    wp_mail($customer_email, 'Email: Additionnal Info', $message);
                }
                //endwhile;
            }
        }
        // Close DB
        $conn->close();   
    } else {
        // no die, because we are in woocommerce task 'payment_complete'
        // register as other way for inform to you
        // die("Connection failed: " . $conn->connect_error);
    }
}
add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );

CodePudding user response:

I updated the code below:

        <?php
    // When payment is OK
    function so_32512552_payment_complete( $order_id ) {
        
        // Connecting DB
        require_once('connect.inc.php');
        $conn = new PDO('mysql:host='.$DBHost.';dbname='.$DBName.';charset=utf8', $DBLogin, $DBPass);
        if (!$conn->connect_error) {
            
            $order = wc_get_order( $order_id );
            foreach ( $order->get_items() as $item ) {
                // Init.
                $product_ids = array($item->get_product_id(), $item->get_variation_id());
                
                // Declare all IDs products 
                $items_ids = array(18, 19, 20, 21, 22, 23, 92);
                
                // Variables
                $customer_name = $order->get_billing_first_name().' '.$order->get_billing_last_name();
                $customer_email = $order->get_billing_email();
                $product = wc_get_product($item->get_id());
                //$product_name = $product->get_name();
                $password = wp_generate_password( 10, false );
                $serial_number = rand(9999,9999999);
                $wcid = get_current_user_id();
       
    
                // Here SQL command and send email
                for ( $i = 0; $i <= $item->get_quantity(); $i   ) {
                    
                    // SQL Command
                     $req = $conn->prepare('INSERT INTO `tabletest_v5` (state_account, user_fullname, user_email, user_passwd, user_corporate, user_licensenumber, software_product, software_license, software_expiredate, activation_cpt, superaccess, wcid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                     $req->execute(array(
                        1,
                        $customer_name,
                        $customer_email,
                        $password,
                        "CORP INC.",
                        $serial_number,
                        1,
                        1,
                        date('Y-m-d', strtotime()),
                        3,
                        0,
                        $wcid
                    ));
                        
                    // Compose message email
                    $message = 'Hi,'.$customer_name;
                    $message .= 'Your product: '.$product_name;
                    $message .= 'Name: '.$customer_name;
                    $message .= 'ID: '.$customer_email;
                    $message .= 'Password: '.$password;
                    $message .= 'Serial number: '.$serial_number;
                    $message .= 'WCID: '.$wcid;
                    wp_mail($customer_email, 'Credentials', $message);
                    }
            }
        } else {}
    }
        
    add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );
?>

EDT : It works but, if I set at 3 the quantity (x3) an item... Problem, I get 3 emails but with same datas AND 3 new entries into DB but with same datas (like same password, same serial number...)

How to fix this?

Cheers, Nico.

  • Related