After successful cashfree payment email/sms send not working properly (codeigniter 3)

167 Views Asked by At

After successful payment (cashfree test environment) I am reducing stocks from database, sending email & sms to vendor regarding order received & stock reduced as well as to customer regarding order placed. (email & sms).

The problem I am facing is vendor receiving email/sms infinity times, also same with the customer & stock keeps reducing automatically with each email/sms vendor & customer receives.

Receiving email/sms each 5min, 15 mins, 1hr interval. For one order 5 to 6 email/sms in some time intervals.

I don't know how its automatically works like a cron job or something.

Need help in this. Below is the reference code for the issue.

**Page: payment-checkout.php (view)**

<body onload="document.frm1.submit()">
<form action="<?php echo $url; ?>" name="frm1" method="post">
      <p>Please wait.......</p>
      <input type="hidden" name="signature" value='<?php echo $signature; ?>'/>
      <input type="hidden" name="orderNote" value='<?php echo $post_data['orderNote']; ?>'/>
      <input type="hidden" name="orderCurrency" value='<?php echo $post_data['orderCurrency']; ?>'/>
      <input type="hidden" name="customerName" value='<?php echo $post_data['customerName']; ?>'/>
      <input type="hidden" name="customerEmail" value='<?php echo $post_data['customerEmail']; ?>'/>
      <input type="hidden" name="customerPhone" value='<?php echo $post_data['customerPhone']; ?>'/>
      <input type="hidden" name="orderAmount" value='<?php echo $post_data['orderAmount']; ?>'/>
      <input type ="hidden" name="notifyUrl" value='<?php echo $post_data['notifyUrl']; ?>'/>
      <input type ="hidden" name="returnUrl" value='<?php echo $post_data['returnUrl']; ?>'/>
      <input type="hidden" name="appId" value='<?php echo $post_data['appId']; ?>'/>
      <input type="hidden" name="orderId" value='<?php echo $post_data['orderId']; ?>'/>
      <input type ="hidden" name="coupon_discount" value='<?php echo $post_data['coupon_discount']; ?>'/>
      <input type="hidden" name="total_price" value='<?php echo $post_data['total_price']; ?>'/>
      <input type="hidden" name="coupon_id" value='<?php echo $post_data['coupon_id']; ?>'/>
  </form>
    </body>
Here is the complete code from my controller

function cashfree_payment() {
        $user_id = $_SESSION['userdata']['user_id'];
        $session_id = $_SESSION['session_data']['session_id'];
        $deliveryaddress_id = $this->input->post('address_id');
        $payment_option = "";
        $order_id = "AM" . rand(111111111, 999999999);
        $grand_total = $this->input->post('totalAmount');
        $coupon_id = $this->input->post('coupon_id');
        $coupon_code = $this->input->post('coupon_code');
        $coupon_disount = $this->input->post('coupon_discount');
        $gst = $this->input->post('gst');
        $created_at = time();
        $order_status = 1;

        $chk = $this->Web_model->doOrder($session_id, $user_id, $deliveryaddress_id, $payment_option, $created_at, $order_status, $grand_total, $order_id, $coupon_id, $coupon_code, $coupon_disount, $gst);

        if (is_array($chk)) {
            if ($chk['status'] == '@success') {
                $order_details = $this->Web_model->orderDetails($chk['order_id']);
                $mode = "TEST"; //<------------ Change to TEST for test server, PROD for production
                //extract($_POST);
                $secretKey = TEST_SECRET_KEY;
                $postData = array(
                    "appId" => TEST_APP_ID,
                    "orderId" => $order_id,
                    "orderAmount" => $grand_total,
                    "orderCurrency" => DEFAULT_CURRENCY,
                    "orderNote" => 'ORDER',
                    "customerName" => $order_details['ordersdetails']['customer_name'],
                    "customerPhone" => $order_details['ordersdetails']['mobile'],
                    "customerEmail" => $order_details['ordersdetails']['email'],
                    "returnUrl" => base_url('web/do_cashfree_order'),
                    "notifyUrl" => base_url('web/do_cashfree_order'),
                    "coupon_discount" => $coupon_disount,
                    'total_price' => $grand_total,
                    'coupon_id' => $coupon_id
                );

                //pr($postData);
                ksort($postData);
                $signatureData = "";
                foreach ($postData as $key => $value) {

                    $signatureData .= $key . $value;
                }
                $signature = hash_hmac('sha256', $signatureData, $secretKey, true);
                $signature = base64_encode($signature);

                if ($mode == "PROD") {
                    $url = "https://www.cashfree.com/checkout/post/submit";
                } else {
                    $url = "https://test.cashfree.com/billpay/checkout/post/submit";
                }

                $this->load->view('web/includes/payment-checkout', ['post_data' => $postData, 'signature' => $signature, 'url' => $url]);
            }
        }
    }

    function do_cashfree_order() {

        $secretkey = TEST_SECRET_KEY;
        $orderId = $_POST["orderId"];
        $orderAmount = $_POST["orderAmount"];
        $referenceId = $_POST["referenceId"];
        $txStatus = $_POST["txStatus"];
        $paymentMode = $_POST["paymentMode"];
        $txMsg = $_POST["txMsg"];
        $txTime = $_POST["txTime"];
        $signature = $_POST["signature"];
        if ($txStatus == "SUCCESS") {
            $trans_status = 1;
        } else {
            $trans_status = 0;
        }

        $data = $orderId . $orderAmount . $referenceId . $txStatus . $paymentMode . $txMsg . $txTime;

        $hash_hmac = hash_hmac('sha256', $data, $secretkey, true);
        $computedSignature = base64_encode($hash_hmac);
        if ($signature == $computedSignature) {
            $insert['pay_orderid'] = $orderId;
            $insert['payment_option'] = $paymentMode;
            $insert['transaction_time'] = $txTime;
            $insert['pay_transaction_id'] = $referenceId;
            $insert['payment_status'] = $trans_status;
            $insert['order_status'] = 2;
            if ($txStatus == "SUCCESS") {
                $update_order_transaction = $this->Web_model->update_order_transaction($insert);
                if ($update_order_transaction) {
                    $id = ($this->common_model->get_data_row(['pay_orderid' => $orderId], 'orders'))->id;
                    $order_details = $this->Web_model->orderDetails($id);

                    //sms send to customer
//                    $phone = $order_details['ordersdetails']['mobile'];
//                    $otp_message = "Dear " . $order_details['ordersdetails']['customer_name'] . ", your order with order ID #" . $order_details['ordersdetails']['id'] . " placed successfully. Thank you for shopping. In case of any queries pls contact customer care. Thanks and Regards";
//                    $template_id = '1407165995915174281';
//                    $this->Web_model->send_message($otp_message, $phone, $template_id);
                    //sms send to vendor (check if multiple vendors)
//                    $vendor_mobile = ($this->common_model->get_data_row(['id' => $order_details['ordersdetails']['vendor_id']], 'vendor_shop'))->mobile;
//                    $vendor_otp_message = "Dear vendor thank you for accepting order no #" . $order_details['ordersdetails']['id'] . " & pls prepare goods as requested and pack them for delivery. Thanks and Regards";
//                    $vendor_template_id = '1407165996082020881';
//                    $this->Web_model->send_message($vendor_otp_message, $vendor_mobile, $vendor_template_id);
                    //email send

                    $subject = $this->data['order_placed_invoice']->subject;
                    $title = $this->data['order_placed_invoice']->title;
                    $message = $this->data['order_placed_invoice']->message;
                    $footer = $this->data['order_placed_invoice']->footer;

                    $message .= '<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Invoice</title>
        <style>
            .clearfix:after {
                content: "";
                display: table;
                clear: both;
            }

            a {
                color: #5D6975;
                text-decoration: underline;
            }

            body {
                position: relative;
                width: 21cm;
                height: auto;
                margin: 0 auto;
                color: #001028;
                background: #FFFFFF;
                font-family: Arial, sans-serif;
                font-size: 12px;
                font-family: Arial;
            }

            header {
                padding: 10px 0;
                margin-bottom: 30px;
            }

            #logo {
                text-align: center;
                margin-bottom: 10px;
            }

            #logo img {
                width: 90px;
            }

            h1 {
                border-top: 1px solid  #5D6975;
                border-bottom: 1px solid  #5D6975;
                color: #5D6975;
                font-size: 2.4em;
                line-height: 1.4em;
                font-weight: normal;
                text-align: center;
                margin: 0 0 20px 0;
                background: url(' . base_url('web_assets/img/') . 'dimension.png);
            }

            #project {
                float: left;
            }

            #project span {
                color: #5D6975;
                text-align: right;
                width: 87px;
                margin-right: 10px;
                display: inline-block;
                font-size: 0.9em;
            }

            #company {
                float: right;
                text-align: right;
            }

            #project div,
            #company div {
                white-space: nowrap;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                border-spacing: 0;
                margin-bottom: 20px;
            }

            table tr:nth-child(2n-1) td {
                background: #F5F5F5;
            }

            table th,
            table td {
                text-align: center;
            }

            table th {
                padding: 5px 20px;
                color: #5D6975;
                border-bottom: 1px solid #C1CED9;
                white-space: nowrap;
                font-weight: normal;
            }

            table .service,
            table .desc {
                text-align: left;
            }

            table td {
                padding: 20px;
                text-align: right;
            }

            table td.service,
            table td.desc {
                vertical-align: top;
            }

            table td.unit,
            table td.qty,
            table td.total {
                font-size: 1.2em;
            }

            table td.grand {
                border-top: 1px solid #5D6975;
                ;
            }

            #notices .notice {
                color: #5D6975;
                font-size: 1.2em;
            }

            footer {
                color: #5D6975;
                width: 100%;
                height: 30px;
                position: absolute;
                bottom: 0;
                border-top: 1px solid #C1CED9;
                padding: 8px 0;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <header class="clearfix">
            <div id="logo">
                <img src="' . base_url('uploads/images/') . $this->data['site']->logo . '">
            </div>
            <h1>[ ' . $title . ' ]</h1>
            <div id="company" class="clearfix">
                <div>' . $order_details['ordersdetails']['customer_name'] . '</div>
                <div><a href="mailto:' . $order_details['ordersdetails']['email'] . '">' . $order_details['ordersdetails']['email'] . '</a></div>
                <div>' . $order_details['ordersdetails']['mobile'] . '</div>
                <div>' . $order_details['ordersdetails']['useraddress'] . '</div>
            </div>
            <div id="project">
                <div><span>Order ID</span> #' . $order_details['ordersdetails']['id'] . '</div>
                <div><span>Placed On</span> ' . $order_details['ordersdetails']['created_date'] . '</div>
                <div><span>Payment Status</span> ' . $order_details['ordersdetails']['payment_status'] . '</div>
                <div><span>Payment Method</span> ' . $order_details['ordersdetails']['payment_type'] . '</div>
                <div><span>Order status</span> ' . $order_details['ordersdetails']['order_status'] . '</div>    
            </div>
        </header>
        <main>
            <table>
                <thead>
                    <tr>
                        <th class="service">#</th>
                        <th class="service">Product</th>
                        <th class="desc">Product Name</th>
                        <th class="desc">Price</th>
                        <th class="desc">Quantity</th>
                        <th class="desc">Total</th>
                    </tr>
                </thead>
                <tbody>';

                    $count = 1;
                    foreach ($order_details['ordersdetails']['cartdetails'] as $item) {

                        $message .= '<tr>
                            <td class="service">' . $count . '</td>
                            <td class="service"><img src ="' . $item['image'] . '" style="width:50px;height:50px" /></td>
                            <td class="desc">
                                ' . $item['productname'] . '<br>
                                [' . ucfirst($item['attributes'][0]['attribute_type']) . ': ' . $item['attributes'][0]['attribute_values'] . ']
                            </td>
                            <td class="desc">' . DEFAULT_CURRENCY . '. ' . $item['price'] . '</td>
                            <td class="desc">' . $item['quantity'] . '</td>
                            <td class="desc">' . DEFAULT_CURRENCY . '. ' . $item['total_price'] . '</td>

                        </tr>';
                    }
                    $message .= '<tr>
                        <td colspan="5">Subtotal</td>
                        <td class="total">' . DEFAULT_CURRENCY . '. ' . $order_details['ordersdetails']['sub_total'] . '</td>
                    </tr>';
                    if (!empty($order_details['ordersdetails']['coupon_disount'])) {
                        $message .= '<tr>
                        <td colspan="5">Coupon Discount</td>
                        <td class="total">(' . DEFAULT_CURRENCY . '. ' . $order_details['ordersdetails']['coupon_disount'] . ')</td>
                    </tr>';
                    }

                    if (!empty($order_details['ordersdetails']['deliveryboy_commission'])) {
                        $message .= '<tr>
                        <td colspan="5">Delivery Charge</td>
                        <td class="total">' . DEFAULT_CURRENCY . '. ' . $order_details['ordersdetails']['deliveryboy_commission'] . '</td>
                    </tr>';
                    }

                    if (!empty($order_details['ordersdetails']['gst'])) {
                        $message .= '<tr>
                        <td colspan="5">GST</td>
                        <td class="total">' . DEFAULT_CURRENCY . '. ' . $order_details['ordersdetails']['gst'] . '</td>
                    </tr>';
                    }

                    if ($order_details['ordersdetails']['gst'] == "") {
                        $gst = 0;
                    } else {
                        $gst = $order_details['ordersdetails']['gst'];
                    }

                    $sub_coupon = ($order_details['ordersdetails']['sub_total'] - $order_details['ordersdetails']['coupon_disount']);
                    $order_boy = ($order_details['ordersdetails']['deliveryboy_commission'] + $gst);
                    $final_total = $sub_coupon + $order_boy;

                    $message .= '<tr>
                        <td colspan="5" class="grand total">GRAND TOTAL</td>
                        <td class="grand total">' . DEFAULT_CURRENCY . '. ' . $final_total . '</td>
                    </tr>
                </tbody>
            </table>
        </main>
        <footer>
            ' . $footer . '
        </footer>
    </body>
</html>';

                    //send mail to customer

                    $config1['protocol'] = MAIL_PROTOCOL;
                    $config1['smtp_host'] = MAIL_SMTP_HOST;
                    $config1['smtp_port'] = MAIL_SMTP_PORT;
                    $config1['smtp_timeout'] = '7';
                    $config1['smtp_user'] = MAIL_SMTP_USER;
                    $config1['smtp_pass'] = MAIL_SMTP_PASS;
                    $config1['charset'] = MAIL_CHARSET;
                    $config1['newline'] = "\r\n";
                    $config1['mailtype'] = 'html'; // or html
                    $config1['validation'] = TRUE; // bool whether to validate email or not      

                    $this->email->initialize($config1);

                    $this->email->from(MAIL_SMTP_USER, $this->data['site']->seo_title);
                    $this->email->to($order_details['ordersdetails']['email']);
                    $this->email->subject($subject);
                    $this->email->message($message);

                    if ($this->email->send()) {
                        echo '@success';
                    } else {
                        echo '@error';
                    }

                    //Manage stock here
                    $vendor_quanity_arr = [];
                    $user_id = $order_details['ordersdetails']['user_id'];
                    $session_id = $order_details['ordersdetails']['session_id'];
                    $cart = $this->common_model->get_data_with_condition(['user_id' => $user_id, 'session_id' => $session_id], 'cart');
                    foreach ($cart as $value) {
                        array_push($vendor_quanity_arr, ['variant_id' => $value->variant_id, 'quantity' => $value->quantity]);
                    }

                    $stockObj = json_decode(json_encode($vendor_quanity_arr));

                    //send notification to vendor regarding stock reduce
                    foreach ($stockObj as $row) {
                        $row->variant = $this->common_model->get_data_row(['id' => $row->variant_id], 'link_variant');
                        $row->product = $this->common_model->get_data_row(['id' => $row->variant->product_id], 'products');
                        $product_image = $this->common_model->get_data_row(['variant_id' => $row->variant_id], 'product_images')->image;
                        $row->product_image = base_url('uploads/products/') . $product_image;
                        $row->vendor = $this->common_model->get_data_row(['id' => $row->product->shop_id], 'vendor_shop');
                        $row->stock_left = (int) $row->variant->stock - (int) $row->quantity;
                        $attribute = (json_decode($row->variant->jsondata))[0];
                        $row->attr_title = $this->common_model->get_data_row(['id' => $attribute->attribute_type], 'attributes_title')->title;
                        $row->attr_value = $this->common_model->get_data_row(['id' => $attribute->attribute_value], 'attributes_values')->value;

                        $ar = array('varient_id' => $row->variant_id, 'product_id' => $row->variant->product_id, 'quantity' => $row->quantity, 'paid_status' => 'Debit', 'message' => 'New Order', 'total_stock' => $row->stock_left, 'created_at' => time());

                        $ins11 = $this->db->insert("stock_management", $ar);

                        if ($ins11) {
                            $this->db->update("link_variant", array('stock' => $row->stock_left), array('id' => $row->variant_id));
                        }

                        //check stock limit set
                        $stock_limit = $this->data['site']->stock_limit;
                        if ($row->stock_left <= $stock_limit) {

                            $subject = 'Stock Deducted';
                            $message = 'Dear Vendor,<br>';
                            $message .= 'Find out the stock details for your product ID: #' . $row->product->id . '<br>';
                            $message .= '<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Invoice</title>
        <style>
            .clearfix:after {
                content: "";
                display: table;
                clear: both;
            }

            a {
                color: #5D6975;
                text-decoration: underline;
            }

            body {
                position: relative;
                width: 21cm;
                height: auto;
                margin: 0 auto;
                color: #001028;
                background: #FFFFFF;
                font-family: Arial, sans-serif;
                font-size: 12px;
                font-family: Arial;
            }

            header {
                padding: 10px 0;
                margin-bottom: 30px;
            }

            #logo {
                text-align: center;
                margin-bottom: 10px;
            }

            #logo img {
                width: 90px;
            }

            h1 {
                border-top: 1px solid  #5D6975;
                border-bottom: 1px solid  #5D6975;
                color: #5D6975;
                font-size: 2.4em;
                line-height: 1.4em;
                font-weight: normal;
                text-align: center;
                margin: 0 0 20px 0;
                background: url(' . base_url('web_assets/img/') . 'dimension.png);
            }

            #project {
                float: left;
            }

            #project span {
                color: #5D6975;
                text-align: right;
                width: 87px;
                margin-right: 10px;
                display: inline-block;
                font-size: 0.9em;
            }

            #company {
                float: right;
                text-align: right;
            }

            #project div,
            #company div {
                white-space: nowrap;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                border-spacing: 0;
                margin-bottom: 20px;
            }

            table tr:nth-child(2n-1) td {
                background: #F5F5F5;
            }

            table th,
            table td {
                text-align: center;
            }

            table th {
                padding: 5px 20px;
                color: #5D6975;
                border-bottom: 1px solid #C1CED9;
                white-space: nowrap;
                font-weight: normal;
            }

            table .service,
            table .desc {
                text-align: left;
            }

            table td {
                padding: 20px;
                text-align: right;
            }

            table td.service,
            table td.desc {
                vertical-align: top;
            }

            table td.unit,
            table td.qty,
            table td.total {
                font-size: 1.2em;
            }

            table td.grand {
                border-top: 1px solid #5D6975;
                ;
            }

            #notices .notice {
                color: #5D6975;
                font-size: 1.2em;
            }

            footer {
                color: #5D6975;
                width: 100%;
                height: 30px;
                position: absolute;
                bottom: 0;
                border-top: 1px solid #C1CED9;
                padding: 8px 0;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <header class="clearfix">
            <div id="logo">
                <img src="' . base_url('uploads/images/') . $this->data['site']->logo . '">
            </div>
            <h1>Stock Notification</h1>
        </header>
        <main>
            <table>
                <thead>
                    <tr>
                        <th class="service">#</th>
                        <th class="service">Product</th>
                        <th class="desc">Product Name</th>
                        <th class="desc">Total Stock</th>
                        <th class="desc">Stock Deducted</th>
                        <th class="desc">Final Stock</th>
                    </tr>
                </thead>
                <tbody>
                <tr>
                            <td class="service">1</td>
                            <td class="service"><img src ="' . $row->product_image . '" style="width:50px;height:50px" /></td>
                            <td class="desc">
                            ' . $row->product->name . '<br>
                                [' . ucfirst($row->attr_title) . ': ' . $row->attr_value . ']
                            </td>
                            <td class="desc">' . $row->variant->stock . '</td>
                            <td class="desc">' . $row->quantity . '</td>
                            <td class="desc">' . $row->stock_left . '</td>

                        </tr>
                </tbody>
            </table>
        </main>
    </body>
</html>';

                            $config1['protocol'] = MAIL_PROTOCOL;
                            $config1['smtp_host'] = MAIL_SMTP_HOST;
                            $config1['smtp_port'] = MAIL_SMTP_PORT;
                            $config1['smtp_timeout'] = '7';
                            $config1['smtp_user'] = MAIL_SMTP_USER;
                            $config1['smtp_pass'] = MAIL_SMTP_PASS;
                            $config1['charset'] = MAIL_CHARSET;
                            $config1['newline'] = "\r\n";
                            $config1['mailtype'] = 'html'; // or html
                            $config1['validation'] = TRUE; // bool whether to validate email or not      

                            $this->email->initialize($config1);

                            $this->email->from(MAIL_SMTP_USER, $this->data['site']->seo_title);
                            $this->email->to($row->vendor->email);
                            $this->email->subject($subject);
                            $this->email->message($message);

                            $this->email->send();
                        }
                    }

                    $sess_arr_old = array(
                        'session_id' => false,
                        'session_status' => false
                    );

                    $this->session->unset_userdata('session_data', $sess_arr_old);
                    $user_id = $this->db->get_where('orders', ['pay_orderid' => $orderId])->row()->user_id;
                    $user_data = $this->db->get_where('users', ['id' => $user_id])->row();
                    $sess_arr = array(
                        'user_id' => $user_id,
                        'email' => $user_data->email,
                        'phone' => $user_data->phone,
                        'logged_in' => true
                    );
                    $this->session->set_userdata('userdata', $sess_arr);

                    $session_id = rand(11111111111111, 99999999999999);
                    $sess = array(
                        'session_id' => $session_id,
                        'session_status' => true
                    );
                    $this->session->set_userdata('session_data', $sess);

                    redirect('web/thankYou');
                }
            } else {
                $user_id = $this->db->get_where('orders', ['pay_transaction_id' => $orderId])->row()->user_id;
                $user_data = $this->db->get_where('users', ['id' => $user_id])->row();
                $sess_arr = array(
                    'user_id' => $user_id,
                    'email' => $user_data->email,
                    'phone' => $user_data->phone,
                    'logged_in' => true
                );
                $this->session->set_userdata('userdata', $sess_arr);

                $session_id = rand(11111111111111, 99999999999999);
                $sess = array(
                    'session_id' => $session_id,
                    'session_status' => true
                );
                $this->session->set_userdata('session_data', $sess);

                $this->db->where('pay_transaction_id', $orderId)->delete('orders');
                redirect('web/failure_cashfree');
            }
        }
    }

    function failure_cashfree() {
        $this->load->view("web/includes/header_styles", $this->data);
        $this->load->view('web/includes/payment_failure');
        $this->load->view("web/includes/footer", $this->data);
    }
0

There are 0 best solutions below