Plugin Directory

Changeset 3324918


Ignore:
Timestamp:
07/09/2025 10:50:35 AM (8 months ago)
Author:
razorpay
Message:

Update: 4.7.5

Location:
woo-razorpay/trunk
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • woo-razorpay/trunk/debug.md

    r2687215 r3324918  
    4646
    4747curl --location --request POST 'https://api.razorpay.com/v1/orders' \
    48 --header 'Authorization: Basic cnpwX3Rlc3RfMURQNW1tT2xGNUc1YWc6dGhpc2lzc3VwZXJzZWNyZXQ=' \
     48--header 'Authorization: Basic <base64_encoded_test_key:secret>' \
    4949--header 'Content-Type: application/json' \
    5050--data-raw '{
  • woo-razorpay/trunk/includes/api/cart.php

    r3134652 r3324918  
    1010function fetchCartData(WP_REST_Request $request)
    1111{
    12     rzpLogInfo("fetchCartData");
    13     global $woocommerce;
    14 
    15     $params = $request->get_params();
    16     $logObj = ['api' => 'fetchCartData', 'params' => $params];
    17 
    18     //Abandoment cart plugin decode the coupon code from token
    19     $couponCode = null;
    20     if (isset($params['token'])) {
    21         $token = sanitize_text_field($params['token']);
    22         parse_str(base64_decode(urldecode($token)), $token);
    23         if (is_array($token) && array_key_exists('wcf_session_id', $token) && isset($token['wcf_coupon_code'])) {
    24             $couponCode = $token['wcf_coupon_code'];
     12    try
     13    {
     14        rzpLogInfo("fetchCartData");
     15        global $woocommerce;
     16
     17        $params = $request->get_params();
     18        $logObj = ['api' => 'fetchCartData', 'params' => $params];
     19
     20        //Abandoment cart plugin decode the coupon code from token
     21        $couponCode = null;
     22        if (isset($params['token'])) {
     23            $token = sanitize_text_field($params['token']);
     24            parse_str(base64_decode(urldecode($token)), $token);
     25            if (is_array($token) && array_key_exists('wcf_session_id', $token) && isset($token['wcf_coupon_code'])) {
     26                $couponCode = $token['wcf_coupon_code'];
     27            }
    2528        }
    26     }
    27 
    28     initCartCommon();
    29 
    30     // check if cart is empty
    31     checkCartEmpty($logObj);
    32 
    33     // Get coupon if already added on cart.
    34     $couponCode = null;
    35     $coupons = WC()->cart->get_applied_coupons();
    36     if (!empty($coupons)) {
    37         $couponCode = $coupons[0];
    38     }
    39 
    40     $response = cartResponse($couponCode);
    41 
    42     $response['user'] = getCartUserObject();
    43 
    44     $response['plugins'] = getPluginsDetails();
    45 
    46     return new WP_REST_Response($response, 200);
     29
     30        initCartCommon();
     31
     32        // check if cart is empty
     33        checkCartEmpty($logObj);
     34
     35        // Get coupon if already added on cart.
     36        $couponCode = null;
     37        $coupons = WC()->cart->get_applied_coupons();
     38        if (!empty($coupons)) {
     39            $couponCode = $coupons[0];
     40        }
     41
     42        $response = cartResponse($couponCode);
     43
     44        $response['user'] = getCartUserObject();
     45
     46        $response['plugins'] = getPluginsDetails();
     47
     48        return new WP_REST_Response($response, 200);
     49    }
     50    catch (Throwable $e)
     51    {
     52        $rzp = new WC_Razorpay();
     53        $trackObject = $rzp->newTrackPluginInstrumentation();
     54        $properties = [
     55            'error' => $e->getMessage(),
     56            'code'  => $e->getCode(),
     57            'file'  => $e->getFile(),
     58            'line'  => $e->getLine()
     59        ];
     60        $trackObject->rzpTrackDataLake('razorpay.1cc.fetch.cart.processing.failed', $properties);
     61        rzpLogError(json_encode($properties));
     62
     63        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
     64    }
    4765}
    4866
     
    5169function createCartData(WP_REST_Request $request)
    5270{
    53     rzpLogInfo("createCartData");
    54     global $woocommerce;
    55     $params = $request->get_params();
    56     $logObj = ['api' => 'createCartData', 'params' => $params];
    57 
    58     $couponCode = null;
    59     initCartCommon();
    60 
    61     if (empty($params['pdpCheckout']) === false) {
    62         $variations = [];
    63         // Cleanup cart.
    64         WC()->cart->empty_cart();
    65 
    66         $variationId = (empty($params['variationId']) === false) ? (int) $params['variationId'] : 0;
    67 
    68         if (empty($params['variations']) === false) {
    69             $variationsArr = json_decode($params['variations'], true);
    70 
    71             foreach ($variationsArr as $key => $value) {
    72                 $varKey          = explode('_', $key);
    73                 $variationsKey[] = ucwords(end($varKey));
    74                 $variationsVal[] = ucwords($value);
     71    try
     72    {
     73        rzpLogInfo("createCartData");
     74        global $woocommerce;
     75        $params = $request->get_params();
     76        $logObj = ['api' => 'createCartData', 'params' => $params];
     77
     78        $couponCode = null;
     79        initCartCommon();
     80
     81        if (empty($params['pdpCheckout']) === false) {
     82            $variations = [];
     83            // Cleanup cart.
     84            WC()->cart->empty_cart();
     85
     86            $variationId = (empty($params['variationId']) === false) ? (int) $params['variationId'] : 0;
     87
     88            if (empty($params['variations']) === false) {
     89                $variationsArr = json_decode($params['variations'], true);
     90
     91                foreach ($variationsArr as $key => $value) {
     92                    $varKey          = explode('_', $key);
     93                    $variationsKey[] = ucwords(end($varKey));
     94                    $variationsVal[] = ucwords($value);
     95                }
     96
     97                $variations = array_combine($variationsKey, $variationsVal);
    7598            }
    7699
    77             $variations = array_combine($variationsKey, $variationsVal);
    78         }
    79 
    80         //To add custom fields to buy now orders
    81         if (empty($params['fieldObj']) === false) {
    82             foreach ($params['fieldObj'] as $key => $value) {
    83                 if (!empty($value)) {
    84                     $variations[$key] = $value;
     100            //To add custom fields to buy now orders
     101            if (empty($params['fieldObj']) === false) {
     102                foreach ($params['fieldObj'] as $key => $value) {
     103                    if (!empty($value)) {
     104                        $variations[$key] = $value;
     105                    }
    85106                }
    86107            }
     108
     109            WC()->cart->add_to_cart($params['productId'], $params['quantity'], $variationId, $variations);
    87110        }
    88111
    89         WC()->cart->add_to_cart($params['productId'], $params['quantity'], $variationId, $variations);
    90     }
    91 
    92     // check if cart is empty
    93     checkCartEmpty($logObj);
    94 
    95     $response = cartResponse($couponCode);
    96 
    97     $response['user'] = getCartUserObject();
    98 
    99     $response['plugins'] = getPluginsDetails();
    100 
    101     return new WP_REST_Response($response, 200);
     112        // check if cart is empty
     113        checkCartEmpty($logObj);
     114
     115        $response = cartResponse($couponCode);
     116
     117        $response['user'] = getCartUserObject();
     118
     119        $response['plugins'] = getPluginsDetails();
     120
     121        return new WP_REST_Response($response, 200);
     122    }
     123    catch (Throwable $e)
     124    {
     125        $rzp = new WC_Razorpay();
     126        $trackObject = $rzp->newTrackPluginInstrumentation();
     127        $properties = [
     128            'error' => $e->getMessage(),
     129            'code'  => $e->getCode(),
     130            'file'  => $e->getFile(),
     131            'line'  => $e->getLine()
     132        ];
     133        $trackObject->rzpTrackDataLake('razorpay.1cc.create.cart.processing.failed', $properties);
     134        rzpLogError(json_encode($properties));
     135
     136        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
     137    }
    102138}
    103139
     
    234270        rzpLogError(json_encode($logObj));
    235271
    236         return new WP_REST_Response($response, $statusCode);
     272        $rzp = new WC_Razorpay();
     273        $trackObject = $rzp->newTrackPluginInstrumentation();
     274        $properties = [
     275            'error' => 'Cart cannot be empty',
     276            'log'   => $logObj
     277        ];
     278        $trackObject->rzpTrackDataLake('razorpay.1cc.empty.cart.error', $properties);
     279
     280        return new WP_REST_Response($response, 400);
    237281    }
    238282}
  • woo-razorpay/trunk/includes/api/coupon-apply.php

    r2947552 r3324918  
    77function applyCouponOnCart(WP_REST_Request $request)
    88{
    9     global $woocommerce;
    10 
    11     $status         = 400;
    12     $failure_reason = "";
    13 
    14     $params = $request->get_params();
    15    
    16     $logObj           = [];
    17     $logObj["api"]    = "applyCouponOnCart";
    18     $logObj["params"] = $params;
    19 
    20     $validateInput = validateApplyCouponApi($params);
    21 
    22     if ($validateInput != null) {
    23         $response["failure_reason"] = $validateInput;
    24         $response["failure_code"]   = "VALIDATION_ERROR";
    25         $logObj["response"]         = $response;
    26 
    27         rzpLogError(json_encode($logObj));
    28 
    29         return new WP_REST_Response($response, 400);
    30     }
    31 
    32     $couponCode = sanitize_text_field($params["code"]);
    33     $email      = sanitize_text_field($params["email"]) ?? "";
    34     $orderId    = sanitize_text_field($params["order_id"]);
    35 
    36     // initializes the session
    37     initCustomerSessionAndCart();
    38 
    39     // Set current user for smart coupon plugin
    40     if (is_plugin_active('wt-smart-coupons-for-woocommerce/wt-smart-coupon.php')) {
    41         if (empty($email) === false) {
    42             $user = get_user_by('email', $email);
    43             wp_set_current_user($user->id);
    44         }
    45     }
    46 
    47     // check for individual specific coupons
    48     // cart->apply does not enforce this
    49     $coupon = new WC_Coupon($couponCode);
    50 
    51     // check the enable coupon option
    52     if (get_option("woocommerce_enable_coupons") === "no") {
    53         $response["failure_reason"] = "Coupon feature disabled";
    54         $response["failure_code"]   = "INVALID_COUPON";
    55         $logObj["response"]         = $response;
    56 
    57         rzpLogError(json_encode($logObj));
    58 
    59         return new WP_REST_Response($response, 400);
    60     }
    61 
    62     //check woo-discount-rule plugin disabling the coupons
    63     if (is_plugin_active('woo-discount-rules/woo-discount-rules.php')) {
    64         $discountOptions = get_option('woo-discount-config-v2', []);
    65         if (!empty($discountOptions)) {
    66             $isCouponEnabled = $discountOptions['disable_coupon_when_rule_applied'];
    67             if ($isCouponEnabled == 'disable_coupon') {
    68                 $response["failure_reason"] = "Coupon feature disabled";
     9    try
     10    {
     11        global $woocommerce;
     12
     13        $status         = 400;
     14        $failure_reason = "";
     15
     16        $params = $request->get_params();
     17
     18        $logObj           = [];
     19        $logObj["api"]    = "applyCouponOnCart";
     20        $logObj["params"] = $params;
     21
     22        $validateInput = validateApplyCouponApi($params);
     23
     24        if ($validateInput != null) {
     25            $response["failure_reason"] = $validateInput;
     26            $response["failure_code"]   = "VALIDATION_ERROR";
     27            $logObj["response"]         = $response;
     28
     29            rzpLogError(json_encode($logObj));
     30
     31            $rzp = new WC_Razorpay();
     32            $trackObject = $rzp->newTrackPluginInstrumentation();
     33            $properties = [
     34                'error' => $validateInput,
     35                'log'   => $logObj
     36            ];
     37            $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.validation.error', $properties);
     38
     39            return new WP_REST_Response($response, 400);
     40        }
     41
     42        $couponCode = sanitize_text_field($params["code"]);
     43        $email      = sanitize_text_field($params["email"]) ?? "";
     44        $orderId    = sanitize_text_field($params["order_id"]);
     45
     46        // initializes the session
     47        initCustomerSessionAndCart();
     48
     49        // Set current user for smart coupon plugin
     50        if (is_plugin_active('wt-smart-coupons-for-woocommerce/wt-smart-coupon.php')) {
     51            if (empty($email) === false) {
     52                $user = get_user_by('email', $email);
     53                wp_set_current_user($user->id);
     54            }
     55        }
     56
     57        // check for individual specific coupons
     58        // cart->apply does not enforce this
     59        $coupon = new WC_Coupon($couponCode);
     60
     61        // check the enable coupon option
     62        if (get_option("woocommerce_enable_coupons") === "no") {
     63            $response["failure_reason"] = "Coupon feature disabled";
     64            $response["failure_code"]   = "INVALID_COUPON";
     65            $logObj["response"]         = $response;
     66
     67            rzpLogError(json_encode($logObj));
     68
     69            $rzp = new WC_Razorpay();
     70            $trackObject = $rzp->newTrackPluginInstrumentation();
     71            $properties = [
     72                'error' => 'Coupon feature disabled',
     73                'log'   => $logObj
     74            ];
     75            $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.invalid.coupon', $properties);
     76
     77            return new WP_REST_Response($response, 400);
     78        }
     79
     80        //check woo-discount-rule plugin disabling the coupons
     81        if (is_plugin_active('woo-discount-rules/woo-discount-rules.php')) {
     82            $discountOptions = get_option('woo-discount-config-v2', []);
     83            if (!empty($discountOptions)) {
     84                $isCouponEnabled = $discountOptions['disable_coupon_when_rule_applied'];
     85                if ($isCouponEnabled == 'disable_coupon') {
     86                    $response["failure_reason"] = "Coupon feature disabled";
     87                    $response["failure_code"]   = "INVALID_COUPON";
     88                    $logObj["response"]         = $response;
     89
     90                    rzpLogError(json_encode($logObj));
     91
     92                    return new WP_REST_Response($response, 400);
     93                }
     94            }
     95        }
     96
     97        if (empty($coupon->get_email_restrictions()) === false) {
     98            if ($email == "") {
     99                $response["failure_reason"] = "User email is required";
     100                $response["failure_code"]   = "LOGIN_REQUIRED";
     101                $logObj["response"]         = $response;
     102
     103                rzpLogError(json_encode($logObj));
     104
     105                $rzp = new WC_Razorpay();
     106                $trackObject = $rzp->newTrackPluginInstrumentation();
     107                $properties = [
     108                    'error' => 'User email is required',
     109                    'log'   => $logObj
     110                ];
     111                $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.login.required', $properties);
     112
     113                return new WP_REST_Response($response, 400);
     114            } elseif (in_array($email, $coupon->get_email_restrictions()) === false) {
     115                $response["failure_reason"] = "Coupon does not exist";
    69116                $response["failure_code"]   = "INVALID_COUPON";
    70117                $logObj["response"]         = $response;
     
    72119                rzpLogError(json_encode($logObj));
    73120
     121                $rzp = new WC_Razorpay();
     122                $trackObject = $rzp->newTrackPluginInstrumentation();
     123                $properties = [
     124                    'error' => 'Coupon does not exist',
     125                    'log'   => $logObj
     126                ];
     127                $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.invalid.coupon', $properties);
     128
    74129                return new WP_REST_Response($response, 400);
    75130            }
    76131        }
    77     }
    78 
    79     if (empty($coupon->get_email_restrictions()) === false) {
    80         if ($email == "") {
    81             $response["failure_reason"] = "User email is required";
    82             $response["failure_code"]   = "LOGIN_REQUIRED";
    83             $logObj["response"]         = $response;
    84 
    85             rzpLogError(json_encode($logObj));
    86 
    87             return new WP_REST_Response($response, 400);
    88         } elseif (in_array($email, $coupon->get_email_restrictions()) === false) {
    89             $response["failure_reason"] = "Coupon does not exist";
    90             $response["failure_code"]   = "INVALID_COUPON";
    91             $logObj["response"]         = $response;
    92 
    93             rzpLogError(json_encode($logObj));
    94 
    95             return new WP_REST_Response($response, 400);
    96         }
    97     }
    98 
    99     // Get coupon usage limit per user
    100     $userLimit = $coupon->get_usage_limit_per_user();
    101     if (!empty($userLimit)) {
    102         $dataStore  = $coupon->get_data_store();
    103         $order      = wc_get_order($orderId);
    104         $usageCount = $order->get_customer_id() ? $dataStore->get_usage_by_user_id($coupon, $order->get_customer_id()) : $dataStore->get_usage_by_email($coupon, $email);
    105 
    106         if (!empty($usageCount) && !empty($userLimit)) {
    107             // Calculate remaining
    108             $remainingCount = $userLimit - $usageCount;
    109 
    110             if ($remainingCount <= 0) {
    111                 $response["failure_reason"] = "Coupon usage limit has been reached";
    112                 $response["failure_code"]   = "REQUIREMENT_NOT_MET";
    113                 $logObj["response"]         = $response;
    114 
    115                 rzpLogError(json_encode($logObj));
    116 
    117                 return new WP_REST_Response($response, 400);
    118             }
    119         }
    120     }
    121 
    122     // to clear any residual notices
    123     $temp = wc_print_notices(true);
    124 
    125     WC()->cart->empty_cart();
    126 
    127     $cart1cc = create1ccCart($orderId);
    128 
    129     WC()->cart->remove_coupon($couponCode);
    130 
    131     if ($cart1cc) {
    132         $applyCoupon = WC()->cart->add_discount($couponCode);
    133 
    134         if ($applyCoupon === true) {
    135             $status = true;
     132
     133        // Get coupon usage limit per user
     134        $userLimit = $coupon->get_usage_limit_per_user();
     135        if (!empty($userLimit)) {
     136            $dataStore  = $coupon->get_data_store();
     137            $order      = wc_get_order($orderId);
     138            $usageCount = $order->get_customer_id() ? $dataStore->get_usage_by_user_id($coupon, $order->get_customer_id()) : $dataStore->get_usage_by_email($coupon, $email);
     139
     140            if (!empty($usageCount) && !empty($userLimit)) {
     141                // Calculate remaining
     142                $remainingCount = $userLimit - $usageCount;
     143
     144                if ($remainingCount <= 0) {
     145                    $response["failure_reason"] = "Coupon usage limit has been reached";
     146                    $response["failure_code"]   = "REQUIREMENT_NOT_MET";
     147                    $logObj["response"]         = $response;
     148
     149                    rzpLogError(json_encode($logObj));
     150
     151                    $rzp = new WC_Razorpay();
     152                    $trackObject = $rzp->newTrackPluginInstrumentation();
     153                    $properties = [
     154                        'error' => 'Coupon usage limit has been reached',
     155                        'log'   => $logObj
     156                    ];
     157                    $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.requirement.not.met', $properties);
     158
     159                    return new WP_REST_Response($response, 400);
     160                }
     161            }
     162        }
     163
     164        // to clear any residual notices
     165        $temp = wc_print_notices(true);
     166
     167        WC()->cart->empty_cart();
     168
     169        $cart1cc = create1ccCart($orderId);
     170
     171        WC()->cart->remove_coupon($couponCode);
     172
     173        if ($cart1cc) {
     174            $applyCoupon = WC()->cart->add_discount($couponCode);
     175
     176            if ($applyCoupon === true) {
     177                $status = true;
     178            } else {
     179                $markup       = wc_print_notices(true);
     180                $errorArray   = explode("<li>", $markup);
     181                $errorMessage = preg_replace(
     182                    "/\t|\n/",
     183                    "",
     184                    strip_tags(end($errorArray))
     185                );
     186                $failureReason = html_entity_decode($errorMessage);
     187            }
    136188        } else {
    137             $markup       = wc_print_notices(true);
    138             $errorArray   = explode("<li>", $markup);
    139             $errorMessage = preg_replace(
    140                 "/\t|\n/",
    141                 "",
    142                 strip_tags(end($errorArray))
    143             );
    144             $failureReason = html_entity_decode($errorMessage);
    145         }
    146     } else {
    147         $invalidCartResponse                   = [];
    148         $invalidCartResponse["failure_reason"] = "Invalid merchant order id";
    149         $invalidCartResponse["failure_code"]   = "VALIDATION_ERROR";
    150 
    151         $logObj["response"] = $invalidCartResponse;
    152 
    153         rzpLogError(json_encode($logObj));
    154         return new WP_REST_Response($invalidCartResponse, 400);
    155     }
    156 
    157     $newAmount      = (WC()->cart->cart_contents_total + WC()->cart->tax_total) * 100;
    158     $discountAmount = (WC()->cart->get_cart_discount_tax_total() + WC()->cart->get_cart_discount_total()) * 100;
    159 
    160     $couponError = getApplyCouponErrorCodes($failureReason);
    161 
    162     $promotion                 = [];
    163     $promotion["code"]         = $couponCode;
    164     $promotion["reference_id"] = $couponCode;
    165     $promotion["value"]        = round($discountAmount ?? 0);
    166     $response["promotion"]     = $promotion;
    167 
    168     if ($couponError["failure_reason"] === "") {
    169         $logObj["response"] = $response;
    170         rzpLogInfo(json_encode($logObj));
    171         return new WP_REST_Response($response, 200);
    172     } else {
    173         $logObj["response"] = array_merge($response, $couponError);
    174         rzpLogError(json_encode($logObj));
    175         return new WP_REST_Response($couponError, 400);
     189            $invalidCartResponse                   = [];
     190            $invalidCartResponse["failure_reason"] = "Invalid merchant order id";
     191            $invalidCartResponse["failure_code"]   = "VALIDATION_ERROR";
     192
     193            $logObj["response"] = $invalidCartResponse;
     194
     195            rzpLogError(json_encode($logObj));
     196
     197            $rzp = new WC_Razorpay();
     198            $trackObject = $rzp->newTrackPluginInstrumentation();
     199            $properties = [
     200                'error' => 'Invalid merchant order id',
     201                'log'   => $logObj
     202            ];
     203            $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.validation.error', $properties);
     204
     205            return new WP_REST_Response($invalidCartResponse, 400);
     206        }
     207
     208        $newAmount      = (WC()->cart->cart_contents_total + WC()->cart->tax_total) * 100;
     209        $discountAmount = (WC()->cart->get_cart_discount_tax_total() + WC()->cart->get_cart_discount_total()) * 100;
     210
     211        $couponError = getApplyCouponErrorCodes($failureReason);
     212
     213        $promotion                 = [];
     214        $promotion["code"]         = $couponCode;
     215        $promotion["reference_id"] = $couponCode;
     216        $promotion["value"]        = round($discountAmount ?? 0);
     217        $response["promotion"]     = $promotion;
     218
     219        if ($couponError["failure_reason"] === "") {
     220            $logObj["response"] = $response;
     221            rzpLogInfo(json_encode($logObj));
     222            return new WP_REST_Response($response, 200);
     223        } else {
     224            $logObj["response"] = array_merge($response, $couponError);
     225            rzpLogError(json_encode($logObj));
     226
     227            $rzp = new WC_Razorpay();
     228            $trackObject = $rzp->newTrackPluginInstrumentation();
     229            $properties = [
     230                'error' => $validateInput,
     231                'log'   => $logObj
     232            ];
     233            $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupon.error', $properties);
     234
     235            return new WP_REST_Response($couponError, 400);
     236        }
     237    }
     238    catch (Throwable $e)
     239    {
     240        $rzp = new WC_Razorpay();
     241        $trackObject = $rzp->newTrackPluginInstrumentation();
     242        $properties = [
     243            'error' => $e->getMessage(),
     244            'code'  => $e->getCode(),
     245            'file'  => $e->getFile(),
     246            'line'  => $e->getLine()
     247        ];
     248        $trackObject->rzpTrackDataLake('razorpay.1cc.apply.coupons.processing.failed', $properties);
     249        rzpLogError(json_encode($properties));
     250
     251        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
    176252    }
    177253}
  • woo-razorpay/trunk/includes/api/coupon-get.php

    r2947552 r3324918  
    2020function getCouponList($request)
    2121{
    22     global $woocommerce;
    23     $couponData = [];
    24 
    25     $params           = $request->get_params();
    26     $logObj           = array();
    27     $logObj['api']    = 'getCouponList';
    28     $logObj['params'] = $params;
    29 
    30     $orderId = sanitize_text_field($request->get_params()['order_id']);
    31     $order   = wc_get_order($orderId);
    32 
    33     if (!$order) {
    34         $response['failure_reason'] = 'Invalid merchant order id';
    35         $response['failure_code']   = 'VALIDATION_ERROR';
    36         $statusCode                 = 400;
    37         $logObj['response']         = $response;
    38         $logObj['status_code']      = $statusCode;
    39         rzpLogError(json_encode($logObj));
    40         return new WP_REST_Response($response, $statusCode);
     22    try
     23    {
     24        global $woocommerce;
     25        $couponData = [];
     26
     27        $params           = $request->get_params();
     28        $logObj           = array();
     29        $logObj['api']    = 'getCouponList';
     30        $logObj['params'] = $params;
     31
     32        $orderId = sanitize_text_field($request->get_params()['order_id']);
     33        $order   = wc_get_order($orderId);
     34
     35        if (!$order) {
     36            $response['failure_reason'] = 'Invalid merchant order id';
     37            $response['failure_code']   = 'VALIDATION_ERROR';
     38            $statusCode                 = 400;
     39            $logObj['response']         = $response;
     40            $logObj['status_code']      = $statusCode;
     41            rzpLogError(json_encode($logObj));
     42
     43            $rzp = new WC_Razorpay();
     44            $trackObject = $rzp->newTrackPluginInstrumentation();
     45            $properties = [
     46                'error' => 'Invalid merchant order id',
     47                'log'   => $logObj
     48            ];
     49            $trackObject->rzpTrackDataLake('razorpay.1cc.get.coupons.validation.error', $properties);
     50            return new WP_REST_Response($response, $statusCode);
     51        }
     52
     53        $amount  = floatval($order->get_total());
     54        $email   = sanitize_text_field($request->get_params()['email']);
     55        $contact = sanitize_text_field($request->get_params()['contact']);
     56
     57        //Updating the email address to wc order.
     58        if (empty($email) == false) {
     59            if (isHposEnabled()) {
     60                $order->update_meta_data( '_billing_email', $email );
     61                $order->update_meta_data( '_shipping_email', $email );
     62                $order->save();
     63            }else{
     64                update_post_meta($orderId, '_billing_email', $email);
     65                update_post_meta($orderId, '_shipping_email', $email);
     66            }
     67        }
     68
     69        if (empty($contact) == false) {
     70            if (isHposEnabled()) {
     71                $order->update_meta_data( '_billing_phone', $contact );
     72                $order->update_meta_data( '_shipping_phone', $contact );
     73                $order->save();
     74            }else{
     75                update_post_meta($orderId, '_billing_phone', $contact);
     76                update_post_meta($orderId, '_shipping_phone', $contact);
     77            }
     78
     79        }
     80
     81        $args = array(
     82            'post_type'      => 'shop_coupon',
     83            'orderby'        => 'title',
     84            'order'          => 'ASC',
     85            'meta_query'     => array(
     86                array(
     87                    'key'     => 'discount_type',
     88                    'value'   => array('fixed_cart', 'percent', 'fixed_product'),
     89                    'compare' => 'IN',
     90                ),
     91                array(
     92                    'key'     => 'coupon_generated_by',
     93                    'compare' => 'NOT EXISTS',
     94                ),
     95            ),
     96            'fields'         => 'ids',
     97            'posts_per_page' => -1, // By default WP_Query will return only 10 posts, to avoid that we need to pass -1
     98        );
     99
     100        //check woo-discount-rule plugin disabling the coupons
     101        if (is_plugin_active('woo-discount-rules/woo-discount-rules.php')) {
     102            $discountOptions = get_option('woo-discount-config-v2', []);
     103            if (!empty($discountOptions)) {
     104                $isCouponEnabled = $discountOptions['disable_coupon_when_rule_applied'];
     105                if ($isCouponEnabled == 'disable_coupon') {
     106                    $args = array();
     107                }
     108            }
     109        }
     110
     111        $coupons = new WP_Query($args);
     112
     113        $couponData['promotions'] = array();
     114
     115        if ($coupons->have_posts() && 'yes' === get_option('woocommerce_enable_coupons')) {
     116            while ($coupons->have_posts()) {
     117                $coupons->the_post();
     118                $coupon           = new WC_Coupon(get_the_ID());
     119                $items            = $order->get_items();
     120                $couponMinAmount  = floatval($coupon->get_minimum_amount());
     121                $couponMaxAmount  = floatval($coupon->get_maximum_amount());
     122                $couponExpiryDate = $coupon->get_date_expires() ? $coupon->get_date_expires()->getTimestamp() : null;
     123
     124                //check coupon description
     125                if (empty($coupon->get_description()) === true) {
     126                    continue;
     127                }
     128
     129                // validation for email coupon
     130                if (empty($coupon->get_email_restrictions()) === false) {
     131                    if (empty($email) === true || in_array($email, $coupon->get_email_restrictions()) === false) {
     132                        continue;
     133                    }
     134                }
     135
     136                if (
     137                    ($amount < $couponMinAmount)
     138                    || (($amount > $couponMaxAmount) && ($couponMaxAmount != 0))
     139                    || ($couponExpiryDate !== null && $couponExpiryDate < time())
     140                ) {
     141                    continue;
     142                }
     143
     144                // Get usage count
     145                $count = $coupon->get_usage_count();
     146                // Get coupon limit
     147                $limit = $coupon->get_usage_limit();
     148
     149                if (!empty($count) && !empty($limit)) {
     150                    // Calculate remaining
     151                    $remaining = $limit - $count;
     152                    if ($remaining <= 0) {
     153                        continue;
     154                    }
     155                }
     156
     157                // Get coupon usage limit per user
     158                $userLimit = $coupon->get_usage_limit_per_user();
     159
     160                if (!empty($userLimit)) {
     161                    $dataStore  = $coupon->get_data_store();
     162                    $usageCount = $order->get_customer_id() ? $dataStore->get_usage_by_user_id($coupon, $order->get_customer_id()) : $dataStore->get_usage_by_email($coupon, $email);
     163
     164                    if (!empty($usageCount) && !empty($userLimit)) {
     165                        // Calculate remaining
     166                        $remainingCount = $userLimit - $usageCount;
     167                        if ($remainingCount <= 0) {
     168                            continue;
     169                        }
     170                    }
     171                }
     172
     173                // Add item based coupons
     174                if (count($coupon->get_product_ids()) > 0) {
     175                    $valid = false;
     176                    // TODO: fix this logic
     177                    foreach ($items as $item) {
     178                        if (in_array($item->get_product_id(), $coupon->get_product_ids()) || in_array($item->get_variation_id(), $coupon->get_product_ids())) {
     179                            $valid = true;
     180                            break;
     181                        }
     182                    }
     183                    if (!$valid) {
     184                        continue;
     185                    }
     186                }
     187
     188                // Exclude item based coupons
     189                if (count($coupon->get_excluded_product_ids()) > 0) {
     190                    $valid = false;
     191                    foreach ($items as $item) {
     192                        if (in_array($item->get_product_id(), $coupon->get_excluded_product_ids()) || in_array($item->get_variation_id(), $coupon->get_excluded_product_ids())) {
     193                            $valid = true;
     194                            break;
     195                        }
     196                    }
     197                    if ($valid) {
     198                        continue;
     199                    }
     200                }
     201
     202                // include and exclude product category items
     203                if (count($coupon->get_excluded_product_categories()) > 0) {
     204                    $categories = array();
     205                    foreach ($items as $item) {
     206                        $product_cats = wc_get_product_cat_ids($item->get_product_id());
     207                        $cat_id_list  = array_intersect($product_cats, $coupon->get_excluded_product_categories());
     208                        if (count($cat_id_list) > 0) {
     209                            foreach ($cat_id_list as $cat_id) {
     210                                $cat          = get_term($cat_id, 'product_cat');
     211                                $categories[] = $cat->name;
     212                            }
     213                        }
     214                    }
     215
     216                    if (!empty($categories)) {
     217                        continue;
     218                    }
     219                }
     220
     221                if (count($coupon->get_product_categories()) > 0) {
     222                    $valid = false;
     223                    foreach ($items as $item) {
     224                        $product_cats = wc_get_product_cat_ids($item->get_product_id());
     225                        if (count(array_intersect($product_cats, $coupon->get_product_categories())) > 0) {
     226                            $valid = true;
     227                            break;
     228                        }
     229                    }
     230
     231                    if (!$valid) {
     232                        continue;
     233                    }
     234                }
     235
     236                // exclude sale item from coupons
     237                if ($coupon->get_exclude_sale_items()) {
     238                    $valid = false;
     239                    foreach ($items as $item) {
     240                        $product = new WC_Product($item->get_product_id());
     241                        if ($product->is_on_sale()) {
     242                            $valid = true;
     243                            break;
     244                        }
     245                    }
     246
     247                    if ($valid) {
     248                        continue;
     249                    }
     250                }
     251
     252                // Check for smart coupon plugin
     253                if (is_plugin_active('wt-smart-coupons-for-woocommerce/wt-smart-coupon.php')) {
     254                    initCustomerSessionAndCart();
     255                    // Cleanup cart.
     256                    WC()->cart->empty_cart();
     257                    create1ccCart($orderId);
     258
     259                    $items = WC()->cart->get_cart();
     260
     261                    // Quantity of matching Products
     262                    $minMatchingProductQty = get_post_meta($coupon->get_id(), '_wt_min_matching_product_qty', true);
     263                    $maxMatchingProductQty = get_post_meta($coupon->get_id(), '_wt_max_matching_product_qty', true);
     264
     265                    if ($minMatchingProductQty > 0 || $maxMatchingProductQty > 0) {
     266                        $quantityMatchingProduct = getQuantityOfProduct($coupon, $items,[], []);
     267                        if ($minMatchingProductQty > 0 && $quantityMatchingProduct < $minMatchingProductQty) {
     268                            continue;
     269                        }
     270                        if ($maxMatchingProductQty > 0 && $quantityMatchingProduct > $maxMatchingProductQty) {
     271                            continue;
     272                        }
     273                    }
     274
     275                    //Subtotal of matching products
     276                    $minMatchingProductSubtotal = get_post_meta($coupon->get_id(), '_wt_min_matching_product_subtotal', true);
     277                    $maxMatchingProductSubtotal = get_post_meta($coupon->get_id(), '_wt_max_matching_product_subtotal', true);
     278
     279                    if ($minMatchingProductSubtotal !== 0 || $maxMatchingProductSubtotal !== 0) {
     280                        $subtotalMatchingProduct = getSubTotalOfProducts($coupon, $items, [], []);
     281                        if ($minMatchingProductSubtotal > 0 && $subtotalMatchingProduct < $minMatchingProductSubtotal) {
     282                            continue;
     283                        }
     284                        if ($maxMatchingProductSubtotal > 0 && $subtotalMatchingProduct > $maxMatchingProductSubtotal) {
     285                            continue;
     286                        }
     287                    }
     288
     289                    // User role restriction
     290                    $userRoles = get_post_meta($coupon->get_id(), '_wt_sc_user_roles', true);
     291                    if ('' != $userRoles && !is_array($userRoles)) {
     292                        $userRoles = explode(',', $userRoles);
     293                    } else {
     294                        $userRoles = array();
     295                    }
     296
     297                    if (sizeof($userRoles) > 0) {
     298                        if (empty($email) === false) {
     299                            $user = get_user_by('email', $email);
     300                            $role = !empty($user) ? $user->roles : [];
     301
     302                            if (!array_intersect($userRoles, $role)) {
     303                                continue;
     304                            }
     305                        } else {
     306                            continue;
     307                        }
     308                    }
     309                }
     310
     311                $couponData['promotions'][] = transformCouponResponse($coupon);
     312            }
     313        }
     314
     315        $logObj['response']    = $couponData;
     316        $statusCode            = 200;
     317        $logObj['status_code'] = $statusCode;
     318        rzpLogInfo(json_encode($logObj));
     319        return new WP_REST_Response($couponData, $statusCode);
    41320    }
    42 
    43     $amount  = floatval($order->get_total());
    44     $email   = sanitize_text_field($request->get_params()['email']);
    45     $contact = sanitize_text_field($request->get_params()['contact']);
    46 
    47     //Updating the email address to wc order.
    48     if (empty($email) == false) {
    49         if (isHposEnabled()) {
    50             $order->update_meta_data( '_billing_email', $email );
    51             $order->update_meta_data( '_shipping_email', $email );
    52             $order->save();
    53         }else{
    54             update_post_meta($orderId, '_billing_email', $email);
    55             update_post_meta($orderId, '_shipping_email', $email);
    56         }
     321    catch (Throwable $e)
     322    {
     323        $rzp = new WC_Razorpay();
     324        $trackObject = $rzp->newTrackPluginInstrumentation();
     325        $properties = [
     326            'error' => $e->getMessage(),
     327            'code'  => $e->getCode(),
     328            'file'  => $e->getFile(),
     329            'line'  => $e->getLine()
     330        ];
     331        $trackObject->rzpTrackDataLake('razorpay.1cc.get.coupons.processing.failed', $properties);
     332        rzpLogError(json_encode($properties));
     333
     334        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
    57335    }
    58 
    59     if (empty($contact) == false) {
    60         if (isHposEnabled()) {
    61             $order->update_meta_data( '_billing_phone', $contact );
    62             $order->update_meta_data( '_shipping_phone', $contact );
    63             $order->save();
    64         }else{
    65            update_post_meta($orderId, '_billing_phone', $contact);
    66            update_post_meta($orderId, '_shipping_phone', $contact);
    67         }
    68        
    69     }
    70 
    71     $args = array(
    72         'post_type'      => 'shop_coupon',
    73         'orderby'        => 'title',
    74         'order'          => 'ASC',
    75         'meta_query'     => array(
    76             array(
    77                 'key'     => 'discount_type',
    78                 'value'   => array('fixed_cart', 'percent', 'fixed_product'),
    79                 'compare' => 'IN',
    80             ),
    81             array(
    82                 'key'     => 'coupon_generated_by',
    83                 'compare' => 'NOT EXISTS',
    84             ),
    85         ),
    86         'fields'         => 'ids',
    87         'posts_per_page' => -1, // By default WP_Query will return only 10 posts, to avoid that we need to pass -1
    88     );
    89 
    90     //check woo-discount-rule plugin disabling the coupons
    91     if (is_plugin_active('woo-discount-rules/woo-discount-rules.php')) {
    92         $discountOptions = get_option('woo-discount-config-v2', []);
    93         if (!empty($discountOptions)) {
    94             $isCouponEnabled = $discountOptions['disable_coupon_when_rule_applied'];
    95             if ($isCouponEnabled == 'disable_coupon') {
    96                 $args = array();
    97             }
    98         }
    99     }
    100 
    101     $coupons = new WP_Query($args);
    102 
    103     $couponData['promotions'] = array();
    104 
    105     if ($coupons->have_posts() && 'yes' === get_option('woocommerce_enable_coupons')) {
    106         while ($coupons->have_posts()) {
    107             $coupons->the_post();
    108             $coupon           = new WC_Coupon(get_the_ID());
    109             $items            = $order->get_items();
    110             $couponMinAmount  = floatval($coupon->get_minimum_amount());
    111             $couponMaxAmount  = floatval($coupon->get_maximum_amount());
    112             $couponExpiryDate = $coupon->get_date_expires() ? $coupon->get_date_expires()->getTimestamp() : null;
    113 
    114             //check coupon description
    115             if (empty($coupon->get_description()) === true) {
    116                 continue;
    117             }
    118 
    119             // validation for email coupon
    120             if (empty($coupon->get_email_restrictions()) === false) {
    121                 if (empty($email) === true || in_array($email, $coupon->get_email_restrictions()) === false) {
    122                     continue;
    123                 }
    124             }
    125 
    126             if (
    127                 ($amount < $couponMinAmount)
    128                 || (($amount > $couponMaxAmount) && ($couponMaxAmount != 0))
    129                 || ($couponExpiryDate !== null && $couponExpiryDate < time())
    130             ) {
    131                 continue;
    132             }
    133 
    134             // Get usage count
    135             $count = $coupon->get_usage_count();
    136             // Get coupon limit
    137             $limit = $coupon->get_usage_limit();
    138 
    139             if (!empty($count) && !empty($limit)) {
    140                 // Calculate remaining
    141                 $remaining = $limit - $count;
    142                 if ($remaining <= 0) {
    143                     continue;
    144                 }
    145             }
    146 
    147             // Get coupon usage limit per user
    148             $userLimit = $coupon->get_usage_limit_per_user();
    149 
    150             if (!empty($userLimit)) {
    151                 $dataStore  = $coupon->get_data_store();
    152                 $usageCount = $order->get_customer_id() ? $dataStore->get_usage_by_user_id($coupon, $order->get_customer_id()) : $dataStore->get_usage_by_email($coupon, $email);
    153 
    154                 if (!empty($usageCount) && !empty($userLimit)) {
    155                     // Calculate remaining
    156                     $remainingCount = $userLimit - $usageCount;
    157                     if ($remainingCount <= 0) {
    158                         continue;
    159                     }
    160                 }
    161             }
    162 
    163             // Add item based coupons
    164             if (count($coupon->get_product_ids()) > 0) {
    165                 $valid = false;
    166                 // TODO: fix this logic
    167                 foreach ($items as $item) {
    168                     if (in_array($item->get_product_id(), $coupon->get_product_ids()) || in_array($item->get_variation_id(), $coupon->get_product_ids())) {
    169                         $valid = true;
    170                         break;
    171                     }
    172                 }
    173                 if (!$valid) {
    174                     continue;
    175                 }
    176             }
    177 
    178             // Exclude item based coupons
    179             if (count($coupon->get_excluded_product_ids()) > 0) {
    180                 $valid = false;
    181                 foreach ($items as $item) {
    182                     if (in_array($item->get_product_id(), $coupon->get_excluded_product_ids()) || in_array($item->get_variation_id(), $coupon->get_excluded_product_ids())) {
    183                         $valid = true;
    184                         break;
    185                     }
    186                 }
    187                 if ($valid) {
    188                     continue;
    189                 }
    190             }
    191 
    192             // include and exclude product category items
    193             if (count($coupon->get_excluded_product_categories()) > 0) {
    194                 $categories = array();
    195                 foreach ($items as $item) {
    196                     $product_cats = wc_get_product_cat_ids($item->get_product_id());
    197                     $cat_id_list  = array_intersect($product_cats, $coupon->get_excluded_product_categories());
    198                     if (count($cat_id_list) > 0) {
    199                         foreach ($cat_id_list as $cat_id) {
    200                             $cat          = get_term($cat_id, 'product_cat');
    201                             $categories[] = $cat->name;
    202                         }
    203                     }
    204                 }
    205 
    206                 if (!empty($categories)) {
    207                     continue;
    208                 }
    209             }
    210 
    211             if (count($coupon->get_product_categories()) > 0) {
    212                 $valid = false;
    213                 foreach ($items as $item) {
    214                     $product_cats = wc_get_product_cat_ids($item->get_product_id());
    215                     if (count(array_intersect($product_cats, $coupon->get_product_categories())) > 0) {
    216                         $valid = true;
    217                         break;
    218                     }
    219                 }
    220 
    221                 if (!$valid) {
    222                     continue;
    223                 }
    224             }
    225 
    226             // exclude sale item from coupons
    227             if ($coupon->get_exclude_sale_items()) {
    228                 $valid = false;
    229                 foreach ($items as $item) {
    230                     $product = new WC_Product($item->get_product_id());
    231                     if ($product->is_on_sale()) {
    232                         $valid = true;
    233                         break;
    234                     }
    235                 }
    236 
    237                 if ($valid) {
    238                     continue;
    239                 }
    240             }
    241 
    242             // Check for smart coupon plugin
    243             if (is_plugin_active('wt-smart-coupons-for-woocommerce/wt-smart-coupon.php')) {
    244                 initCustomerSessionAndCart();
    245                 // Cleanup cart.
    246                 WC()->cart->empty_cart();
    247                 create1ccCart($orderId);
    248 
    249                 $items = WC()->cart->get_cart();
    250 
    251                 // Quantity of matching Products
    252                 $minMatchingProductQty = get_post_meta($coupon->get_id(), '_wt_min_matching_product_qty', true);
    253                 $maxMatchingProductQty = get_post_meta($coupon->get_id(), '_wt_max_matching_product_qty', true);
    254 
    255                 if ($minMatchingProductQty > 0 || $maxMatchingProductQty > 0) {
    256                     $quantityMatchingProduct = getQuantityOfProduct($coupon, $items,[], []);
    257                     if ($minMatchingProductQty > 0 && $quantityMatchingProduct < $minMatchingProductQty) {
    258                         continue;
    259                     }
    260                     if ($maxMatchingProductQty > 0 && $quantityMatchingProduct > $maxMatchingProductQty) {
    261                         continue;
    262                     }
    263                 }
    264 
    265                 //Subtotal of matching products
    266                 $minMatchingProductSubtotal = get_post_meta($coupon->get_id(), '_wt_min_matching_product_subtotal', true);
    267                 $maxMatchingProductSubtotal = get_post_meta($coupon->get_id(), '_wt_max_matching_product_subtotal', true);
    268 
    269                 if ($minMatchingProductSubtotal !== 0 || $maxMatchingProductSubtotal !== 0) {
    270                     $subtotalMatchingProduct = getSubTotalOfProducts($coupon, $items, [], []);
    271                     if ($minMatchingProductSubtotal > 0 && $subtotalMatchingProduct < $minMatchingProductSubtotal) {
    272                         continue;
    273                     }
    274                     if ($maxMatchingProductSubtotal > 0 && $subtotalMatchingProduct > $maxMatchingProductSubtotal) {
    275                         continue;
    276                     }
    277                 }
    278 
    279                 // User role restriction
    280                 $userRoles = get_post_meta($coupon->get_id(), '_wt_sc_user_roles', true);
    281                 if ('' != $userRoles && !is_array($userRoles)) {
    282                     $userRoles = explode(',', $userRoles);
    283                 } else {
    284                     $userRoles = array();
    285                 }
    286 
    287                 if (sizeof($userRoles) > 0) {
    288                     if (empty($email) === false) {
    289                         $user = get_user_by('email', $email);
    290                         $role = !empty($user) ? $user->roles : [];
    291 
    292                         if (!array_intersect($userRoles, $role)) {
    293                             continue;
    294                         }
    295                     } else {
    296                         continue;
    297                     }
    298                 }
    299             }
    300 
    301             $couponData['promotions'][] = transformCouponResponse($coupon);
    302         }
    303     }
    304 
    305     $logObj['response']    = $couponData;
    306     $statusCode            = 200;
    307     $logObj['status_code'] = $statusCode;
    308     rzpLogInfo(json_encode($logObj));
    309     return new WP_REST_Response($couponData, $statusCode);
    310336}
    311337
  • woo-razorpay/trunk/includes/api/giftcard-apply.php

    r2854318 r3324918  
    77function validateGiftCardData(WP_REST_Request $request)
    88{
    9     global $woocommerce;
    10     global $wpdb;   
     9    try
     10    {
     11        global $woocommerce;
     12        global $wpdb;
    1113
    12     $status = 400;
    13     $giftCard = [];
    14     $giftCardData= [];
     14        $status = 400;
     15        $giftCard = [];
     16        $giftCardData= [];
     17        $response = [];
    1518
    16     $params = $request->get_params();
     19        $params = $request->get_params();
    1720
    18     $validateInput = validateApplyGiftCardApi($params);
     21        $validateInput = validateApplyGiftCardApi($params);
    1922
    20     $logObj           = [];
    21     $logObj["api"]    = "validateApplyGiftCardApi";
    22     $logObj["params"] = $params;
     23        $logObj           = [];
     24        $logObj["api"]    = "validateApplyGiftCardApi";
     25        $logObj["params"] = $params;
    2326
    24     //initializes the session
    25     initCustomerSessionAndCart();
     27        //initializes the session
     28        initCustomerSessionAndCart();
    2629
    27     if ($validateInput != null) {
     30        if ($validateInput != null) {
    2831
    29         $giftCardRes['response']["failure_reason"] = $validateInput;
    30         $giftCardRes['response']["failure_code"] = "VALIDATION_ERROR";
    31         $giftCardRes['status_code'] =  $status;
     32            $giftCardRes['response']["failure_reason"] = $validateInput;
     33            $giftCardRes['response']["failure_code"] = "VALIDATION_ERROR";
     34            $giftCardRes['status_code'] =  $status;
    3235
    33         $logObj["response"]         = $response;
    34         rzpLogError(json_encode($logObj));
     36            $logObj["response"] = $giftCardRes['response'];
     37            rzpLogError(json_encode($logObj));
    3538
    36         return new WP_REST_Response($giftCardRes, $status);
    37     }
     39            $rzp = new WC_Razorpay();
     40            $trackObject = $rzp->newTrackPluginInstrumentation();
     41            $properties = [
     42                'error' => $validateInput,
     43                'log'   => $logObj
     44            ];
     45            $trackObject->rzpTrackDataLake('razorpay.1cc.apply.giftcard.validation.error', $properties);
    3846
    39     $giftCardNumber = sanitize_text_field($params['gift_card_number']);
     47            return new WP_REST_Response($giftCardRes, $status);
     48        }
    4049
    41     //Yith gift card plugin
    42     if(is_plugin_active('yith-woocommerce-gift-cards/init.php'))
    43     {
    44         $yithArgs = ['gift_card_number'=> $giftCardNumber];
     50        $giftCardNumber = sanitize_text_field($params['gift_card_number']);
    4551
    46         $yithCard = new YITH_YWGC_Gift_Card($yithArgs);
     52        //Yith gift card plugin
     53        if(is_plugin_active('yith-woocommerce-gift-cards/init.php'))
     54        {
     55            $yithArgs = ['gift_card_number'=> $giftCardNumber];
    4756
    48         // check post status
    49         $post  = get_post($yithCard->ID);
    50         if ('trash' == $post->post_status ) {
     57            $yithCard = new YITH_YWGC_Gift_Card($yithArgs);
     58
     59            // check post status
     60            $post  = get_post($yithCard->ID);
     61            if ('trash' == $post->post_status ) {
     62                $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
     63                return new WP_REST_Response($response, $status);
     64            }
     65
     66            $giftCardBalance = $yithCard->get_balance();
     67
     68            if(!$yithCard->exists()){
     69                $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
     70                return new WP_REST_Response($response, $status);
     71
     72            }elseif($giftCardBalance <= 0) {
     73                $response = getApplyGiftCardErrors('ZERO_BALANCE');
     74                return new WP_REST_Response($response, $status);
     75            }else{
     76                $giftCardData['gift_card_number'] = $giftCardNumber;
     77                $giftCardData['balance']   = floatval($giftCardBalance) *100;
     78                $giftCardData['allowedPartialRedemption']   = 1;
     79
     80                $logObj['response']         = $response;
     81                $logObj['status_code']      = 200;
     82                $giftCard['gift_card_promotion'] = $giftCardData;
     83
     84                rzpLogError(json_encode($logObj));
     85                return new WP_REST_Response($giftCard, 200);
     86            }
     87
     88        }
     89
     90        //PW gift card plugin
     91        else if(is_plugin_active('pw-woocommerce-gift-cards/pw-gift-cards.php')){
     92            $result = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$wpdb->pimwick_gift_card}` WHERE `number` = %s and `active` =%s", $giftCardNumber, 1 ) );
     93
     94            if ( $result == null ) {
     95                $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
     96                return new WP_REST_Response($response, $status);
     97
     98            }
     99
     100            $balance = $wpdb->get_var( $wpdb->prepare( "SELECT SUM(amount) FROM {$wpdb->pimwick_gift_card_activity} WHERE pimwick_gift_card_id = %d", $result->pimwick_gift_card_id ) );
     101
     102            if($balance <= 0 ){
     103                $response = getApplyGiftCardErrors('ZERO_BALANCE');
     104                return new WP_REST_Response($response, $status);
     105            }
     106
     107            $giftCardData['gift_card_number'] = $giftCardNumber;
     108            $giftCardData['balance']   = floatval ($balance) *100;
     109            // 1 for Gift card allowed Partial Redemption
     110            $giftCardData['allowedPartialRedemption']   = 1;
     111            $giftCard['gift_card_promotion'] = $giftCardData;
     112
     113            $logObj['response']         = $response;
     114            $logObj['status_code']      = 200;
     115
     116            rzpLogError(json_encode($logObj));
     117            return new WP_REST_Response($giftCard, 200);
     118
     119        }else{
    51120            $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
    52121            return new WP_REST_Response($response, $status);
    53122        }
     123    }
     124    catch (Throwable $e)
     125    {
     126        $rzp = new WC_Razorpay();
     127        $trackObject = $rzp->newTrackPluginInstrumentation();
     128        $properties = [
     129            'error' => $e->getMessage(),
     130            'code'  => $e->getCode(),
     131            'file'  => $e->getFile(),
     132            'line'  => $e->getLine()
     133        ];
     134        $trackObject->rzpTrackDataLake('razorpay.1cc.apply.giftcart.processing.failed', $properties);
     135        rzpLogError(json_encode($properties));
    54136
    55         $giftCardBalance = $yithCard->get_balance();
    56 
    57         if(!$yithCard->exists()){
    58             $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
    59             return new WP_REST_Response($response, $status);
    60 
    61         }elseif($giftCardBalance <= 0) {
    62             $response = getApplyGiftCardErrors('ZERO_BALANCE');
    63             return new WP_REST_Response($response, $status);
    64         }else{
    65             $giftCardData['gift_card_number'] = $giftCardNumber;
    66             $giftCardData['balance']   = floatval($giftCardBalance) *100;
    67             $giftCardData['allowedPartialRedemption']   = 1;
    68 
    69             $logObj['response']         = $response;
    70             $logObj['status_code']      = 200;
    71             $giftCard['gift_card_promotion'] = $giftCardData;
    72 
    73             rzpLogError(json_encode($logObj));
    74             return new WP_REST_Response($giftCard, 200);
    75         }
    76 
     137        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
    77138    }
    78 
    79     //PW gift card plugin
    80     else if(is_plugin_active('pw-woocommerce-gift-cards/pw-gift-cards.php')){
    81         $result = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$wpdb->pimwick_gift_card}` WHERE `number` = %s and `active` =%s", $giftCardNumber, 1 ) );
    82 
    83         if ( $result == null ) {
    84             $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
    85             return new WP_REST_Response($response, $status);
    86        
    87         }
    88 
    89        $balance = $wpdb->get_var( $wpdb->prepare( "SELECT SUM(amount) FROM {$wpdb->pimwick_gift_card_activity} WHERE pimwick_gift_card_id = %d", $result->pimwick_gift_card_id ) );
    90 
    91        if($balance <= 0 ){
    92             $response = getApplyGiftCardErrors('ZERO_BALANCE');
    93             return new WP_REST_Response($response, $status);
    94        }
    95 
    96         $giftCardData['gift_card_number'] = $giftCardNumber;
    97         $giftCardData['balance']   = floatval ($balance) *100;
    98         // 1 for Gift card allowed Partial Redemption
    99         $giftCardData['allowedPartialRedemption']   = 1;
    100         $giftCard['gift_card_promotion'] = $giftCardData;
    101 
    102         $logObj['response']         = $response;
    103         $logObj['status_code']      = 200;
    104        
    105         rzpLogError(json_encode($logObj));
    106         return new WP_REST_Response($giftCard, 200);
    107        
    108     }else{
    109         $response = getApplyGiftCardErrors('INVALID_GIFTCODE');
    110         return new WP_REST_Response($response, $status);
    111     }
    112 
    113139}
    114140
     
    145171    }
    146172
    147     $logObj['response']         = $response;
     173    $logObj['response']         = $error;
    148174    $logObj['status_code']      = $statusCode;
    149175    rzpLogError(json_encode($logObj));
     176
     177    $rzp = new WC_Razorpay();
     178    $trackObject = $rzp->newTrackPluginInstrumentation();
     179    $properties = [
     180        'error' => $error['failure_reason'],
     181        'log'   => $logObj
     182    ];
     183    $eventName = ($errCode == 'ZERO_BALANCE')? 'razorpay.1cc.apply.giftcard.zero.balance.error':'razorpay.1cc.apply.giftcard.invalid.gift.code';
     184    $trackObject->rzpTrackDataLake($eventName, $properties);
    150185
    151186    return $error;
  • woo-razorpay/trunk/includes/api/order.php

    r2947552 r3324918  
    99function createWcOrder(WP_REST_Request $request)
    1010{
    11     rzpLogInfo("createWcOrder");
    12     global $woocommerce;
    13     $params           = $request->get_params();
    14     $logObj           = array();
    15     $logObj['api']    = 'createWcOrder';
    16     $logObj['params'] = $params;
    17 
    18     // fetching wp_woocommerce_session_ from cookies
    19     $sessionVal = array_filter($params['cookies'], function($key) {
    20        return strpos($key, 'wp_woocommerce_session_') === 0;
    21     }, ARRAY_FILTER_USE_KEY);
    22 
    23     foreach($sessionVal as $key => $value){
    24         $expKey = explode('wp_woocommerce_session_', $key);
    25         $sessionResult = $expKey[1];
    26     }
    27    
    28     //Abandoment cart plugin decode the coupon code from token
    29     $couponCode = null;
    30     if (isset($params['token'])) {
    31         $token = sanitize_text_field($params['token']);
    32         parse_str(base64_decode(urldecode($token)), $token);
    33         if (is_array($token) && array_key_exists('wcf_session_id', $token) && isset($token['wcf_coupon_code'])) {
    34             $couponCode = $token['wcf_coupon_code'];
    35         }
    36     }
    37 
    38     $nonce     = $request->get_header('X-WP-Nonce');
    39     $verifyReq = wp_verify_nonce($nonce, 'wp_rest');
    40 
    41     if ($verifyReq === false) {
    42         $response['status']  = false;
    43         $response['message'] = 'Authentication failed';
    44 
    45         $statusCode            = 401;
    46         $logObj['status_code'] = $statusCode;
    47         $logObj['response']    = $response;
    48         rzpLogError(json_encode($logObj));
    49 
    50         return new WP_REST_Response($response, $statusCode);
    51     }
    52 
    53     initCartCommon();
    54 
    55     // check if cart is empty
    56     checkCartEmpty($logObj);
    57 
    58     $cartHash  = WC()->cart->get_cart_hash();
    59     $hash = $sessionResult."_".$cartHash;
    60     $orderIdFromHash = get_transient(RZP_1CC_CART_HASH . $hash);
    61 
    62     if (isHposEnabled()) {
    63         $updateOrderStatus = 'checkout-draft';
    64     }else{
    65         $updateOrderStatus = 'draft';
    66     }
    67 
    68     if ($orderIdFromHash == null) {
    69         $checkout = WC()->checkout();
    70         $orderId  = $checkout->create_order(array());
    71 
    72         if (is_wp_error($orderId)) {
    73             $checkout_error = $orderId->get_error_message();
    74         }
    75         //Keep order in draft status untill customer info available
    76         updateOrderStatus($orderId, $updateOrderStatus);
    77     } else {
    78         $existingOrder = wc_get_order($orderIdFromHash);
    79         $orderStatus   = $existingOrder->get_status();
    80         $existingOrder->calculate_totals();
    81         if ($orderStatus != $updateOrderStatus && $existingOrder->needs_payment() == false) {
    82             $woocommerce->session->__unset(RZP_1CC_CART_HASH . $cartHash);
     11    try
     12    {
     13        rzpLogInfo("createWcOrder");
     14        global $woocommerce;
     15        $params           = $request->get_params();
     16        $logObj           = array();
     17        $logObj['api']    = 'createWcOrder';
     18        $logObj['params'] = $params;
     19
     20        // fetching wp_woocommerce_session_ from cookies
     21        $sessionVal = array_filter($params['cookies'], function($key) {
     22            return strpos($key, 'wp_woocommerce_session_') === 0;
     23        }, ARRAY_FILTER_USE_KEY);
     24
     25        foreach($sessionVal as $key => $value){
     26            $expKey = explode('wp_woocommerce_session_', $key);
     27            $sessionResult = $expKey[1];
     28        }
     29
     30        //Abandoment cart plugin decode the coupon code from token
     31        $couponCode = null;
     32        if (isset($params['token'])) {
     33            $token = sanitize_text_field($params['token']);
     34            parse_str(base64_decode(urldecode($token)), $token);
     35            if (is_array($token) && array_key_exists('wcf_session_id', $token) && isset($token['wcf_coupon_code'])) {
     36                $couponCode = $token['wcf_coupon_code'];
     37            }
     38        }
     39
     40        $nonce     = $request->get_header('X-WP-Nonce');
     41        $verifyReq = wp_verify_nonce($nonce, 'wp_rest');
     42
     43        if ($verifyReq === false) {
     44            $response['status']  = false;
     45            $response['message'] = 'Authentication failed';
     46
     47            $statusCode            = 401;
     48            $logObj['status_code'] = $statusCode;
     49            $logObj['response']    = $response;
     50            rzpLogError(json_encode($logObj));
     51
     52            return new WP_REST_Response($response, $statusCode);
     53        }
     54       
     55        initCartCommon();
     56
     57        // check if cart is empty
     58        checkCartEmpty($logObj);
     59
     60        $cartHash  = WC()->cart->get_cart_hash();
     61        $hash = $sessionResult."_".$cartHash;
     62        //Setting the $orderIdFromHash to null, to create a fresh RZP order for each checkout initialisation.
     63        //In future if we need to revert back to earlier flow then consider it from transient as mentioned below.
     64        // $orderIdFromHash = get_transient(RZP_1CC_CART_HASH . $hash);
     65        $orderIdFromHash = null;
     66
     67        if (isHposEnabled()) {
     68          $updateOrderStatus = 'checkout-draft';
     69        } else {
     70            // Check if WooCommerce supports the "checkout-draft" status (added in newer versions).
     71            $postStatus = get_post_status_object('wc-checkout-draft');
     72            if ($postStatus) {
     73                $updateOrderStatus = 'checkout-draft';
     74            } else {
     75                $updateOrderStatus = 'draft'; // Older WooCommerce versions fallback
     76            }
     77        }
     78
     79        if ($orderIdFromHash == null) {
    8380            $checkout = WC()->checkout();
    8481            $orderId  = $checkout->create_order(array());
     
    9087            updateOrderStatus($orderId, $updateOrderStatus);
    9188        } else {
    92             $orderId = $orderIdFromHash;
    93             //To get the applied coupon details from cart object.
    94             $coupons    = WC()->cart->get_coupons();
    95             $couponCode = !empty($coupons) ? array_key_first($coupons) : null;
    96         }
    97     }
    98 
    99     $order = wc_get_order($orderId);
    100    
    101     if($order){
    102 
    103         $disableCouponFlag = false;
    104 
    105         // Woo dynamic discount price plugin
    106         if(is_plugin_active('yith-woocommerce-dynamic-pricing-and-discounts-premium/init.php')) {
    107 
    108             foreach ($order->get_items() as $itemId => $item) {
    109                 $dynamicRules = $item->get_meta('_ywdpd_discounts');
    110 
    111                 if(empty($dynamicRules) == false){
    112                    
    113                     foreach ($dynamicRules['applied_discounts'] as $appliedDiscount) {
    114                         if (isset( $appliedDiscount['set_id'])){
    115                             $ruleId = $appliedDiscount['set_id'];
    116                             $rule    = ywdpd_get_rule($ruleId);
    117                         } else {
    118                             $rule = $appliedDiscount['by'];
    119                         }
    120                         // check coupon is disable with discount price
    121                         if($rule->is_disabled_with_other_coupon() == 1){
    122                             $disableCouponFlag = true;
     89            $existingOrder = wc_get_order($orderIdFromHash);
     90            $orderStatus   = $existingOrder->get_status();
     91            $existingOrder->calculate_totals();
     92            if ($orderStatus != $updateOrderStatus && $existingOrder->needs_payment() == false) {
     93                $woocommerce->session->__unset(RZP_1CC_CART_HASH . $cartHash);
     94                $checkout = WC()->checkout();
     95                $orderId  = $checkout->create_order(array());
     96
     97                if (is_wp_error($orderId)) {
     98                    $checkout_error = $orderId->get_error_message();
     99                }
     100                //Keep order in draft status untill customer info available
     101                updateOrderStatus($orderId, $updateOrderStatus);
     102            } else {
     103                $orderId = $orderIdFromHash;
     104                //To get the applied coupon details from cart object.
     105                $coupons    = WC()->cart->get_coupons();
     106                $couponCode = !empty($coupons) ? array_key_first($coupons) : null;
     107            }
     108        }
     109
     110        $order = wc_get_order($orderId);
     111
     112        if($order){
     113
     114            $disableCouponFlag = false;
     115
     116            // Woo dynamic discount price plugin
     117            if(is_plugin_active('yith-woocommerce-dynamic-pricing-and-discounts-premium/init.php')) {
     118                foreach ($order->get_items() as $itemId => $item) {
     119                    $dynamicRules = $item->get_meta('_ywdpd_discounts');
     120
     121                    if(empty($dynamicRules) == false){
     122
     123                        foreach ($dynamicRules['applied_discounts'] as $appliedDiscount) {
     124                            if (isset( $appliedDiscount['set_id'])){
     125                                $ruleId = $appliedDiscount['set_id'];
     126                                $rule    = ywdpd_get_rule($ruleId);
     127                            } else {
     128                                $rule = $appliedDiscount['by'];
     129                            }
     130                            // check coupon is disable with discount price
     131                            if($rule->is_disabled_with_other_coupon() == 1){
     132                                $disableCouponFlag = true;
     133                            }
    123134                        }
    124135                    }
    125136                }
    126137            }
    127         }
    128 
    129         // Pixel your site PRO UTM data
    130         if (is_plugin_active('pixelyoursite-pro/pixelyoursite-pro.php')) {
    131 
    132             $pysData = get_option('pys_core');
    133 
    134             // Store UTM data only if config enabled.
    135             if ($pysData['woo_enabled_save_data_to_orders'] == true) {
    136                 wooSaveCheckoutUTMFields($order, $params);
    137             }
    138         }
    139 
    140         // To remove coupon added on order.
    141         $coupons = $order->get_coupon_codes();
    142         if (!empty($coupons)) {
    143             foreach ($coupons as $coupon) {
    144                 $order->remove_coupon($coupon);
    145             }
    146             $couponCode = $coupons[0];
    147         }
    148 
    149         //To remove by default shipping method added on order.
    150         $items = (array) $order->get_items('shipping');
    151 
    152         if (sizeof($items) > 0) {
    153             // Loop through shipping items
    154             foreach ($items as $item_id => $item) {
    155                 $order->remove_item($item_id);
    156             }
    157         }
    158 
    159         $order->calculate_totals();
    160 
    161         if (isHposEnabled()) {
    162             $order->update_meta_data( 'is_magic_checkout_order', 'yes' );
    163             $order->save();
    164         }else{
    165             update_post_meta($orderId, 'is_magic_checkout_order', 'yes');
    166         }
    167 
    168         $minCartAmount1cc = !empty(get_option('woocommerce_razorpay_settings')['1cc_min_cart_amount']) ? get_option('woocommerce_razorpay_settings')['1cc_min_cart_amount'] : 0;
    169 
    170         // Response sent to the user when order creation fails
    171         if ($order->get_total() < $minCartAmount1cc) {
     138
     139            // Pixel your site PRO UTM data
     140            if (is_plugin_active('pixelyoursite-pro/pixelyoursite-pro.php')) {
     141
     142                $pysData = get_option('pys_core');
     143
     144                // Store UTM data only if config enabled.
     145                if ($pysData['woo_enabled_save_data_to_orders'] == true) {
     146                    wooSaveCheckoutUTMFields($order, $params);
     147                }
     148            }
     149
     150            // To remove coupon added on order.
     151            $coupons = $order->get_coupon_codes();
     152            if (!empty($coupons)) {
     153                foreach ($coupons as $coupon) {
     154                    $order->remove_coupon($coupon);
     155                }
     156                $couponCode = $coupons[0];
     157            }
     158
     159            //To remove by default shipping method added on order.
     160            $items = (array) $order->get_items('shipping');
     161
     162            if (sizeof($items) > 0) {
     163                // Loop through shipping items
     164                foreach ($items as $item_id => $item) {
     165                    $order->remove_item($item_id);
     166                }
     167            }
     168
     169            $order->calculate_totals();
     170
     171            if (isHposEnabled()) {
     172                $order->update_meta_data( 'is_magic_checkout_order', 'yes' );
     173                $order->save();
     174            }else{
     175                update_post_meta($orderId, 'is_magic_checkout_order', 'yes');
     176            }
     177
     178            $minCartAmount1cc = !empty(get_option('woocommerce_razorpay_settings')['1cc_min_cart_amount']) ? get_option('woocommerce_razorpay_settings')['1cc_min_cart_amount'] : 0;
     179
     180            // Response sent to the user when order creation fails
     181            if ($order->get_total() < $minCartAmount1cc) {
     182                $response['status']  = false;
     183                $response['message'] = 'Your current order total is ₹' . $order->get_total() . ' — you must have an order with a minimum of ₹' . $minCartAmount1cc . ' to place your order';
     184                $response['code']    = 'MIN_CART_AMOUNT_CHECK_FAILED';
     185
     186                $status                 = 400;
     187                $logObj['response']     = $response;
     188                $logObj['rzp_order_id'] = $rzp_order_id;
     189                $logObj['rzp_response'] = $rzp_response;
     190                rzpLogError(json_encode($logObj));
     191
     192                return new WP_REST_Response($response, $status);
     193            }
     194
     195            $razorpay = new WC_Razorpay(false);
     196
     197            $rzp_order_id = $razorpay->createOrGetRazorpayOrderId($order, $orderId, 'yes');
     198            $rzp_response = $razorpay->getDefaultCheckoutArguments($order);
     199
     200            // Response sent to the user when order creation fails
     201            if (empty($rzp_response['order_id'])) {
     202                $response['status']  = false;
     203                $response['message'] = 'Unable to create order';
     204                $response['code']    = 'ORDER_CREATION_FAILED';
     205
     206                $status                 = 400;
     207                $logObj['response']     = $response;
     208                $logObj['rzp_order_id'] = $rzp_order_id;
     209                $logObj['rzp_response'] = $rzp_response;
     210                rzpLogError(json_encode($logObj));
     211
     212                $trackObject = $razorpay->newTrackPluginInstrumentation();
     213                $properties = [
     214                    'error' => 'Unable to create order',
     215                    'log'   => $logObj
     216                ];
     217                $trackObject->rzpTrackDataLake('razorpay.1cc.create.order.failed', $properties);
     218
     219                return new WP_REST_Response($response, $status);
     220            }
     221
     222            // TODO: getDefaultCheckoutArguments() is already being called in L65 above
     223            $response = $razorpay->getDefaultCheckoutArguments($order);
     224
     225            $fbAnalytics = get_option('woocommerce_razorpay_settings')['enable_1cc_fb_analytics'] === 'yes' ? true : false;
     226
     227
     228            if($disableCouponFlag == true){
     229                $response['show_coupons']  = false;
     230            }
     231
     232            if ($fbAnalytics === true) {
     233                //Customer cart related data for FB analytics.
     234                $customer_cart['value']        = (string) WC()->cart->subtotal;
     235                $customer_cart['content_type'] = 'product';
     236                $customer_cart['currency']     = 'INR';
     237
     238                $x = 0;
     239                // Loop over $cart items
     240                foreach (WC()->cart->get_cart() as $cart_item) {
     241
     242                    $customer_cart['contents'][$x]['id']         = (string) $cart_item['product_id'];
     243                    $customer_cart['contents'][$x]['name']       = $cart_item['data']->get_title();
     244                    $customer_cart['contents'][$x]['quantity']   = (string) $cart_item['quantity'];
     245                    $customer_cart['contents'][$x]['value']      = (string) ($cart_item['line_subtotal'] + $cart_item['line_subtotal_tax']) / $cart_item['quantity'];
     246                    $customer_cart['contents'][$x]['variant_id'] = (string) $cart_item['variation_id'];
     247
     248                    $x++;
     249                }
     250
     251                $response['customer_cart'] = $customer_cart ?? '';
     252            }
     253
     254            $hash = $sessionResult."_".$cartHash;
     255            $woocommerce->session->set(RZP_1CC_CART_HASH . $hash, $orderId);
     256            set_transient(RZP_1CC_CART_HASH . $orderId, $hash, 14400);
     257            set_transient(RZP_1CC_CART_HASH . $hash, $orderId, 14400);
     258            set_transient($razorpay::SESSION_KEY, $orderId, 14400);
     259
     260            $logObj['response'] = $response;
     261            rzpLogInfo(json_encode($logObj));
     262
     263            return new WP_REST_Response($response, 200);
     264        } else {
    172265            $response['status']  = false;
    173             $response['message'] = 'Your current order total is ₹' . $order->get_total() . ' — you must have an order with a minimum of ₹' . $minCartAmount1cc . ' to place your order';
    174             $response['code']    = 'MIN_CART_AMOUNT_CHECK_FAILED';
    175 
    176             $status                 = 400;
    177             $logObj['response']     = $response;
    178             $logObj['rzp_order_id'] = $rzp_order_id;
    179             $logObj['rzp_response'] = $rzp_response;
     266            $response['message'] = $checkout_error;
     267            $response['code']    = 'WOOCOMMERCE_ORDER_CREATION_FAILED';
     268
     269            $logObj['response']    = $response;
     270            $logObj['status_code'] = 400;
    180271            rzpLogError(json_encode($logObj));
    181272
    182             return new WP_REST_Response($response, $status);
    183         }
    184 
    185         $razorpay = new WC_Razorpay(false);
    186 
    187         $rzp_order_id = $razorpay->createOrGetRazorpayOrderId($order, $orderId, 'yes');
    188         $rzp_response = $razorpay->getDefaultCheckoutArguments($order);
    189 
    190         // Response sent to the user when order creation fails
    191         if (empty($rzp_response['order_id'])) {
    192             $response['status']  = false;
    193             $response['message'] = 'Unable to create order';
    194             $response['code']    = 'ORDER_CREATION_FAILED';
    195 
    196             $status                 = 400;
    197             $logObj['response']     = $response;
    198             $logObj['rzp_order_id'] = $rzp_order_id;
    199             $logObj['rzp_response'] = $rzp_response;
    200             rzpLogError(json_encode($logObj));
    201 
    202             return new WP_REST_Response($response, $status);
    203         }
    204 
    205         // TODO: getDefaultCheckoutArguments() is already being called in L65 above
    206         $response = $razorpay->getDefaultCheckoutArguments($order);
    207 
    208         $fbAnalytics = get_option('woocommerce_razorpay_settings')['enable_1cc_fb_analytics'] === 'yes' ? true : false;
    209 
    210 
    211         if($disableCouponFlag == true){
    212            $response['show_coupons']  = false;
    213         }
    214 
    215         if ($fbAnalytics === true) {
    216             //Customer cart related data for FB analytics.
    217             $customer_cart['value']        = (string) WC()->cart->subtotal;
    218             $customer_cart['content_type'] = 'product';
    219             $customer_cart['currency']     = 'INR';
    220 
    221             $x = 0;
    222             // Loop over $cart items
    223             foreach (WC()->cart->get_cart() as $cart_item) {
    224 
    225                 $customer_cart['contents'][$x]['id']         = (string) $cart_item['product_id'];
    226                 $customer_cart['contents'][$x]['name']       = $cart_item['data']->get_title();
    227                 $customer_cart['contents'][$x]['quantity']   = (string) $cart_item['quantity'];
    228                 $customer_cart['contents'][$x]['value']      = (string) ($cart_item['line_subtotal'] + $cart_item['line_subtotal_tax']) / $cart_item['quantity'];
    229                 $customer_cart['contents'][$x]['variant_id'] = (string) $cart_item['variation_id'];
    230 
    231                 $x++;
    232             }
    233 
    234             $response['customer_cart'] = $customer_cart ?? '';
    235         }
    236 
    237         $hash = $sessionResult."_".$cartHash;
    238         $woocommerce->session->set(RZP_1CC_CART_HASH . $hash, $orderId);
    239         set_transient(RZP_1CC_CART_HASH . $orderId, $hash, 14400);
    240         set_transient(RZP_1CC_CART_HASH . $hash, $orderId, 14400);
    241         set_transient($razorpay::SESSION_KEY, $orderId, 14400);
    242 
    243         $logObj['response'] = $response;
    244         rzpLogInfo(json_encode($logObj));
    245 
    246         return new WP_REST_Response($response, 200);
    247     } else {
    248         $response['status']  = false;
    249         $response['message'] = $checkout_error;
    250         $response['code']    = 'WOOCOMMERCE_ORDER_CREATION_FAILED';
    251 
    252         $logObj['response']    = $response;
    253         $logObj['status_code'] = 400;
    254         rzpLogError(json_encode($logObj));
    255 
    256         return new WP_REST_Response($response, 400);
     273            $rzp = new WC_Razorpay();
     274            $trackObject = $rzp->newTrackPluginInstrumentation();
     275            $properties = [
     276                'error' => $checkout_error,
     277                'log'   => $logObj
     278            ];
     279            $trackObject->rzpTrackDataLake('razorpay.1cc.create.woocommerce.order.failed', $properties);
     280
     281            return new WP_REST_Response($response, 400);
     282        }
     283    }
     284    catch (Throwable $e)
     285    {
     286        $rzp = new WC_Razorpay();
     287        $trackObject = $rzp->newTrackPluginInstrumentation();
     288        $properties = [
     289            'error' => $e->getMessage(),
     290            'code'  => $e->getCode(),
     291            'file'  => $e->getFile(),
     292            'line'  => $e->getLine()
     293        ];
     294        $trackObject->rzpTrackDataLake('razorpay.1cc.create.order.processing.failed', $properties);
     295        rzpLogError(json_encode($properties));
     296
     297        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
    257298    }
    258299}
     
    266307        $order->save();
    267308    }else{
    268         wp_update_post(array(
    269             'ID'          => $orderId,
    270             'post_status' => $orderStatus,
    271          ));
    272     }
    273    
     309        // Handling order status update for WooCommerce versions that do not support HPOS.
     310        // We are unsure if older versions use `wp_update_post()`, while newer versions may use `$order->update_status()`.
     311        // To maintain compatibility across different WooCommerce versions, we add an additional if-else condition.
     312        if (!isHposEnabled()) { // Explicitly checking if HPOS is NOT enabled
     313            $order->update_status($orderStatus);
     314            $order->save(); // Save changes
     315        } else {
     316            wp_update_post([
     317                'ID'          => $orderId,
     318                'post_status' => $orderStatus,
     319            ]);
     320        }
     321    }
     322
    274323}
    275324
     
    300349        update_post_meta($order->get_id(), "pys_enrich_data", $pysData);
    301350    }
    302    
     351
    303352}
  • woo-razorpay/trunk/includes/api/prepay-cod.php

    r2933784 r3324918  
    88
    99function prepayCODOrder(WP_REST_Request $request): WP_REST_Response {
    10     $payload = $request->get_params();
    11     $wcRazorpay = new WC_Razorpay(false);
    12 
    13     $orderId = $payload[WC_ORDER_ID];
    14     $razorpayPaymentId = $payload[RAZORPAY_PAYMENT_ID];
    15     $razorpayOrderId = $payload[RAZORPAY_ORDER_ID];
    16     $signature = $payload[RAZORPAY_SIGNATURE];
    17     $razorpayOffer = $payload[RAZORPAY_OFFER];
    18     $attributes = array(
    19         RAZORPAY_ORDER_ID => $razorpayOrderId,
    20         RAZORPAY_PAYMENT_ID => $razorpayPaymentId,
    21         RAZORPAY_SIGNATURE  => $signature,
    22     );
    23 
    2410    try
    2511    {
    26         $api = $wcRazorpay->getRazorpayApiInstance();
    27         $api->utility->verifyPaymentSignature($attributes);
     12        $payload = $request->get_params();
     13        $wcRazorpay = new WC_Razorpay(false);
     14
     15        $orderId = $payload[WC_ORDER_ID];
     16        $razorpayPaymentId = $payload[RAZORPAY_PAYMENT_ID];
     17        $razorpayOrderId = $payload[RAZORPAY_ORDER_ID];
     18        $signature = $payload[RAZORPAY_SIGNATURE];
     19        $razorpayOffer = $payload[RAZORPAY_OFFER];
     20        $attributes = array(
     21            RAZORPAY_ORDER_ID => $razorpayOrderId,
     22            RAZORPAY_PAYMENT_ID => $razorpayPaymentId,
     23            RAZORPAY_SIGNATURE  => $signature,
     24        );
     25
     26        try
     27        {
     28            $api = $wcRazorpay->getRazorpayApiInstance();
     29            $api->utility->verifyPaymentSignature($attributes);
     30        }
     31        catch (Exception $e)
     32        {
     33            return new WP_REST_Response(["code" => 'woocommerce_order_payment_signature_verfication_failed'], 400);
     34        }
     35        $order = wc_get_order($orderId);
     36        if ('on-hold' != $order->get_status())
     37        {
     38            return new WP_REST_Response(['code' => 'woocommerce_order_not_in_on_hold_status'], 400);
     39        }
     40
     41        $order->set_status('pending');
     42        $order->save();
     43        $couponInput = [];
     44
     45        if (isset($payload['coupon']))
     46        {
     47            $couponKey = $payload['coupon']['code'];
     48            $amount = $payload['coupon']['amount'];
     49            $amountInRs = $amount/100;
     50            $couponInput[$couponKey] = $amountInRs;
     51        }
     52        if ($razorpayOffer > 0)
     53        {
     54            $razorpayOfferInRs = $razorpayOffer/100;
     55            $couponKey = 'Razorpay offers_'. $orderId .'(₹'. $razorpayOfferInRs .')';
     56            $couponInput[$couponKey] = $razorpayOfferInRs;
     57        }
     58
     59        if (sizeof($couponInput) > 0 )
     60        {
     61            $error = bulkCouponApply($couponInput, $wcRazorpay, $order);
     62            if (sizeof($error) > 0 )
     63            {
     64                handleCouponFailure($couponInput, $order);
     65
     66                $rzp = new WC_Razorpay();
     67                $trackObject = $rzp->newTrackPluginInstrumentation();
     68                $properties = [
     69                    'error' => 'Bulk coupon apply failed',
     70                    'log'   => $error
     71                ];
     72                $trackObject->rzpTrackDataLake('razorpay.1cc.cod.create.coupon.error', $properties);
     73
     74                return new WP_REST_Response($error, 500);
     75            }
     76        }
     77        $order->set_payment_method($wcRazorpay->id);
     78        $order->set_payment_method_title($wcRazorpay->title);
     79        $order->payment_complete($razorpayPaymentId);
     80        $order->set_status("processing");
     81        $order->save();
     82        $order->add_order_note("COD Order Converted to Prepaid <br/> Razorpay payment successful <br/>Razorpay Id: $razorpayPaymentId");
     83        return new WP_REST_Response([], 200);
    2884    }
    29     catch (Exception $e)
     85    catch (Throwable $e)
    3086    {
    31         return new WP_REST_Response(["code" => 'woocommerce_order_payment_signature_verfication_failed'], 400);
     87        $rzp = new WC_Razorpay();
     88        $trackObject = $rzp->newTrackPluginInstrumentation();
     89        $properties = [
     90            'error' => $e->getMessage(),
     91            'code'  => $e->getCode(),
     92            'file'  => $e->getFile(),
     93            'line'  => $e->getLine()
     94        ];
     95        $trackObject->rzpTrackDataLake('razorpay.1cc.cod.processing.failed', $properties);
     96        rzpLogError(json_encode($properties));
     97
     98        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
    3299    }
    33     $order = wc_get_order($orderId);
    34     if ('on-hold' != $order->get_status())
    35     {
    36         return new WP_REST_Response(['code' => 'woocommerce_order_not_in_on_hold_status'], 400);
    37     }
    38 
    39     $order->set_status('pending');
    40     $order->save();
    41     $couponInput = [];
    42 
    43     if (isset($payload['coupon']))
    44     {
    45         $couponKey = $payload['coupon']['code'];
    46         $amount = $payload['coupon']['amount'];
    47         $amountInRs = $amount/100;
    48         $couponInput[$couponKey] = $amountInRs;
    49     }
    50     if ($razorpayOffer > 0)
    51     {
    52         $razorpayOfferInRs = $razorpayOffer/100;
    53         $couponKey = 'Razorpay offers_'. $orderId .'(₹'. $razorpayOfferInRs .')';
    54         $couponInput[$couponKey] = $razorpayOfferInRs;
    55     }
    56 
    57     if (sizeof($couponInput) > 0 )
    58     {
    59         $error = bulkCouponApply($couponInput, $wcRazorpay, $order);
    60         if (sizeof($error) > 0 )
    61         {
    62             handleCouponFailure($couponInput, $order);
    63             return new WP_REST_Response($error, 500);
    64         }
    65     }
    66     $order->set_payment_method($wcRazorpay->id);
    67     $order->set_payment_method_title($wcRazorpay->title);
    68     $order->payment_complete($razorpayPaymentId);
    69     $order->set_status("processing");
    70     $order->save();
    71     $order->add_order_note("COD Order Converted to Prepaid <br/> Razorpay payment successful <br/>Razorpay Id: $razorpayPaymentId");
    72     return new WP_REST_Response([], 200);
    73100}
    74101
  • woo-razorpay/trunk/includes/api/save-abandonment-data.php

    r2947552 r3324918  
    1212function saveCartAbandonmentData(WP_REST_Request $request)
    1313{
    14     global $woocommerce;
    15     global $wpdb;
    16 
    17     $params     = $request->get_params();
    18     $rzpOrderId = sanitize_text_field($params['order_id']);
    19 
    20     $logObj           = array();
    21     $logObj['api']    = "saveCartAbandonmentData";
    22     $logObj['params'] = $params;
    23 
    24     $razorpay = new WC_Razorpay(false);
    25     $api      = $razorpay->getRazorpayApiInstance();
    2614    try
    2715    {
    28         $razorpayData = $api->order->fetch($rzpOrderId);
    29     } catch (Exception $e) {
    30         $response['status']  = false;
    31         $response['message'] = 'RZP order id does not exist';
    32         $statusCode          = 400;
    33 
    34         $logObj['response']    = $response;
    35         $logObj['status_code'] = $statusCode;
    36         rzpLogError(json_encode($logObj));
    37 
    38         return new WP_REST_Response($response, $statusCode);
    39     }
    40     if (isset($razorpayData['receipt'])) {
    41         $wcOrderId = $razorpayData['receipt'];
    42 
    43         $order = wc_get_order($wcOrderId);
    44 
    45         $orderStatus = $order->get_status();
    46 
    47         if ($orderStatus === 'draft' && isset($razorpayData['customer_details']['shipping_address'])) {
    48             //Update the order status to wc-pending as we have the customer address info at this point.
    49             updateOrderStatus($wcOrderId, 'wc-pending');
    50 
    51         }
    52     }
    53 
    54     $razorpay->UpdateOrderAddress($razorpayData, $order);
    55 
    56     abandonedPluginHook($razorpayData); // do_action to notify/send the abandonedCart data to 3rd party plugins
    57 
    58     initCustomerSessionAndCart();
    59 
    60     if (isHposEnabled()) {
    61         $customerEmail  = $order->get_billing_email();
    62 
    63     }else{
    64         $customerEmail = get_post_meta($wcOrderId, '_billing_email', true);
    65     }
    66 
    67     //Retrieving cart products and their quantities.
    68     // check plugin is activated or not
    69     rzpLogInfo('Woocommerce order id:');
    70     rzpLogInfo(json_encode($wcOrderId));
    71 
    72     $result['response']    = "";
    73     $result['status_code'] = 400;
    74 
    75  //check woocommerce cart abandonment recovery plugin is activated or not
    76  if (is_plugin_active('woo-cart-abandonment-recovery/woo-cart-abandonment-recovery.php') && empty($customerEmail) == false) {
    77 
    78     //save abandonment data
    79     $res = saveWooCartAbandonmentRecoveryData($razorpayData);
    80 
    81     if($res['status_code'] == 200){
    82         $result['response']    = "Data inserted for WooCart abandoned recovery plugin";
     16        global $woocommerce;
     17        global $wpdb;
     18
     19        $params     = $request->get_params();
     20        $rzpOrderId = sanitize_text_field($params['order_id']);
     21
     22        $logObj           = array();
     23        $logObj['api']    = "saveCartAbandonmentData";
     24        $logObj['params'] = $params;
     25
     26        $razorpay = new WC_Razorpay(false);
     27        $api      = $razorpay->getRazorpayApiInstance();
     28        try
     29        {
     30            $razorpayData = $api->order->fetch($rzpOrderId);
     31        } catch (Exception $e) {
     32            $response['status']  = false;
     33            $response['message'] = 'RZP order id does not exist';
     34            $statusCode          = 400;
     35
     36            $logObj['response']    = $response;
     37            $logObj['status_code'] = $statusCode;
     38            rzpLogError(json_encode($logObj));
     39
     40            $rzp = new WC_Razorpay();
     41            $trackObject = $rzp->newTrackPluginInstrumentation();
     42            $properties = [
     43                'error' => $response['message'],
     44                'log'   => $logObj
     45            ];
     46            $trackObject->rzpTrackDataLake('razorpay.1cc.abandon.cart.validation.error', $properties);
     47
     48            return new WP_REST_Response($response, $statusCode);
     49        }
     50        if (isset($razorpayData['receipt'])) {
     51            $wcOrderId = $razorpayData['receipt'];
     52
     53            $order = wc_get_order($wcOrderId);
     54
     55            $orderStatus = $order->get_status();
     56
     57
     58            if (($orderStatus === 'draft' || $orderStatus ==='checkout-draft') && isset($razorpayData['customer_details']['shipping_address'])) {
     59                //Update the order status to wc-pending as we have the customer address info at this point.
     60                updateOrderStatus($wcOrderId, 'wc-pending');
     61            }
     62        }
     63
     64        $razorpay->UpdateOrderAddress($razorpayData, $order);
     65
     66        abandonedPluginHook($razorpayData); // do_action to notify/send the abandonedCart data to 3rd party plugins
     67
     68        initCustomerSessionAndCart();
     69
     70        if (isHposEnabled()) {
     71            $customerEmail  = $order->get_billing_email();
     72
     73        }else{
     74            $customerEmail = get_post_meta($wcOrderId, '_billing_email', true);
     75        }
     76
     77        //Retrieving cart products and their quantities.
     78        // check plugin is activated or not
     79        rzpLogInfo('Woocommerce order id:');
     80        rzpLogInfo(json_encode($wcOrderId));
     81
     82        $result['response']    = "";
    8383        $result['status_code'] = 200;
    84     }else{
    85         $result['response']    = "Failed to insert data for WooCart abandoned recovery plugin";
    86         $result['status_code'] = 400;
    87     }
    88 }
    89 
    90     // Check Wati.io retargetting plugin is active or not
    91     if (is_plugin_active('wati-chat-and-notification/wati-chat-and-notification.php')){
    92 
    93         $res = saveWatiCartAbandonmentData($razorpayData);
    94         if($res['status_code'] == 200){
    95             $result['response']    = $result['response']."Data inserted for Wati plugin";
    96             $result['status_code'] = 200;
    97         }else{
    98             $result['response']    = $result['response']."Failed to insert data for Wati plugin";
    99             $result['status_code'] = 400;
    100         }
    101 
    102     }
    103 
    104     //Check CartBounty plugin is activated or not
    105     if (is_plugin_active('woo-save-abandoned-carts/cartbounty-abandoned-carts.php') && (empty($razorpayData['customer_details']['email']) == false || empty($customerEmail) == false)) {
    106 
    107         $res = saveCartBountyData($razorpayData); //save abandonment data
    108 
    109         if($res['status_code'] == 200){
    110             $result['response']    = $result['response'].PHP_EOL."Data inserted for CartBounty plugin";
    111             $result['status_code'] = 200;
    112         }else{
    113             $result['response']    = $result['response'].PHP_EOL."Failed to insert data for CartBounty plugin";
    114         }
    115     }
    116 
    117     // check yith woocommerce recover abandoned cart plugin activated or not
    118     if (is_plugin_active('yith-woocommerce-recover-abandoned-cart-premium/init.php') && (empty($razorpayData['customer_details']['email']) == false) && (empty($razorpayData['customer_details']['shipping_address']))== true) {
    119         if ((email_exists($razorpayData['customer_details']['email'])) == false) {
    120 
    121             $meta_cart = array(
    122                 'user_id'         => '0',
    123                 'user_email'      => $razorpayData['customer_details']['email'],
    124                 'user_first_name' => '',
    125                 'user_last_name'  => '',
    126                 'user_phone'      => $razorpayData['customer_details']['contact'],
    127                 'language'        => substr( get_bloginfo( 'language' ), 0, 2 ),
    128                 'email_sent'      => 'no',
    129                 'cart_status'     => 'open',
    130                 'user_currency'   => get_woocommerce_currency(),
    131             );
    132 
    133             $title = $razorpayData['customer_details']['email'];
    134 
    135             $postId = abandonedCart( $title, $meta_cart );
    136 
    137             if ( $postId ) {
    138                 // add a cookie to the user.
    139                 setcookie( 'ywrac_guest_cart', $postId, ywrac_get_timestamp() + $this->delete_abandoned_time * 60, '/' );
    140                 $result['message']   = $result['response'].PHP_EOL."Data successfully inserted for yith cart abandonment recovery and postid";
    141                 $result['status_code']           = 200;
     84
     85        //check woocommerce cart abandonment recovery plugin is activated or not
     86        if (is_plugin_active('woo-cart-abandonment-recovery/woo-cart-abandonment-recovery.php') && empty($customerEmail) == false) {
     87
     88            //save abandonment data
     89            $res = saveWooCartAbandonmentRecoveryData($razorpayData);
     90
     91            if($res['status_code'] == 200){
     92                $result['response']    = "Data inserted for WooCart abandoned recovery plugin";
     93                $result['status_code'] = 200;
    14294            }else{
    143                 $result['message']   = $result['response'].PHP_EOL."Data falied to inserted for yith cart abandonment recovery";
     95                $result['response']    = "Failed to insert data for WooCart abandoned recovery plugin";
    14496                $result['status_code'] = 400;
    14597            }
    146 
    147         }
    148    
    149     }
    150 
    151     if (is_plugin_active('klaviyo/klaviyo.php') && empty($razorpayData['customer_details']['email']) == false) {
    152         WC()->cart->empty_cart();
    153         $cart1cc = create1ccCart($wcOrderId);
    154 
    155         $cart = WC()->cart;
    156         //Insert data for tracking started checkout.
    157         $eventData = wck_build_cart_data($cart);
    158         if (empty($eventData['$extra']['Items'])) {
    159             $response['status']    = false;
    160             $response['message']   = 'Failed to insert as Cart item does not exist in klaviyo';
    161             $statusCode            = 400;
    162             $result['response']    = $result['response'].PHP_EOL.$response['message'];
    163         }
    164         $eventData['$service'] = 'woocommerce';
    165         unset($eventData['Tags']);
    166         unset($eventData['Quantity']);
    167         $email = $customerEmail;
    168 
    169         //Get token from kalviyo plugin
    170         $klaviyoApi  = WooCommerceKlaviyo::instance();
    171         $token       = $klaviyoApi->options->get_klaviyo_option('klaviyo_public_api_key');
    172         $eventObject = ['token' => $token, 'event' => '$started_checkout', 'customer_properties' => array('$email' => $email), 'properties' => $eventData];
    173         $dataParam   = json_encode($eventObject);
    174         $data        = base64_encode($dataParam);
    175         $event       = 'track';
    176 
    177         $logObj['klaviyoData'] = $eventData;
    178         //calling klaviyo plugin public api
    179         $url = "https://a.klaviyo.com/api/" . $event . '?data=' . $data;
    180         file_get_contents($url);
    181     }
    182 
    183     //check Abandonment cart lite plugin active or not
    184     if (is_plugin_active('woocommerce-abandoned-cart/woocommerce-ac.php') && empty($razorpayData['customer_details']['email']) == false) {
    185         //To verify whether the email id is already exist on WordPress
    186         if (email_exists($razorpayData['customer_details']['email'])) {
    187             $response['status']    = false;
    188             $statusCode            = 400;
    189             $result['response']    = $result['response'].PHP_EOL."Failed to insert data for Abandonment Cart Lite plugin for registered user";
    190         }
    191 
    192         // Save Abandonment data for Abandonment cart lite
    193         $res = saveWooAbandonmentCartLiteData($razorpayData, $wcOrderId);
    194 
    195         if($res['status_code'] == 200){
    196             $result['response']    = $result['response'].PHP_EOL."Successfully inserted data for Abandonment Cart Lite plugin";
    197             $result['status_code'] = 200;
    198         }else{
    199             $result['response']    = $result['response'].PHP_EOL."Failed to insert data for Abandonment Cart Lite plugin";
    200         }
    201 
    202     } else {
    203         $response['status']    = false;
    204         $response['message']   = 'Failed to insert data';
    205         $statusCode            = 400;
    206         $result['response']    = $result['response'].PHP_EOL."Failed to insert data for Abandonment Cart Lite plugin";
    207         $logObj['response']    = $response;
    208         $logObj['status_code'] = $statusCode;
    209         rzpLogInfo(json_encode($logObj));
    210     }
    211 
    212     return new WP_REST_Response($result['response'], $result['status_code']);
     98        }
     99
     100        // Check Wati.io retargetting plugin is active or not
     101        if (is_plugin_active('wati-chat-and-notification/wati-chat-and-notification.php')){
     102
     103            $res = saveWatiCartAbandonmentData($razorpayData);
     104            if($res['status_code'] == 200){
     105                $result['response']    = $result['response']."Data inserted for Wati plugin";
     106                $result['status_code'] = 200;
     107            }else{
     108                $result['response']    = $result['response']."Failed to insert data for Wati plugin";
     109                $result['status_code'] = 400;
     110            }
     111
     112        }
     113
     114        //Check CartBounty plugin is activated or not
     115        if (is_plugin_active('woo-save-abandoned-carts/cartbounty-abandoned-carts.php') && (empty($razorpayData['customer_details']['email']) == false || empty($customerEmail) == false)) {
     116
     117            $res = saveCartBountyData($razorpayData); //save abandonment data
     118
     119            if($res['status_code'] == 200){
     120                $result['response']    = $result['response'].PHP_EOL."Data inserted for CartBounty plugin";
     121                $result['status_code'] = 200;
     122            }else{
     123                $result['response']    = $result['response'].PHP_EOL."Failed to insert data for CartBounty plugin";
     124            }
     125        }
     126
     127        // check yith woocommerce recover abandoned cart plugin activated or not
     128        if (is_plugin_active('yith-woocommerce-recover-abandoned-cart-premium/init.php') && (empty($razorpayData['customer_details']['email']) == false) && (empty($razorpayData['customer_details']['shipping_address']))== true) {
     129            if ((email_exists($razorpayData['customer_details']['email'])) == false) {
     130
     131                $meta_cart = array(
     132                    'user_id'         => '0',
     133                    'user_email'      => $razorpayData['customer_details']['email'],
     134                    'user_first_name' => '',
     135                    'user_last_name'  => '',
     136                    'user_phone'      => $razorpayData['customer_details']['contact'],
     137                    'language'        => substr( get_bloginfo( 'language' ), 0, 2 ),
     138                    'email_sent'      => 'no',
     139                    'cart_status'     => 'open',
     140                    'user_currency'   => get_woocommerce_currency(),
     141                );
     142
     143                $title = $razorpayData['customer_details']['email'];
     144
     145                $postId = abandonedCart( $title, $meta_cart );
     146
     147                if ( $postId ) {
     148                    // add a cookie to the user.
     149                    setcookie( 'ywrac_guest_cart', $postId, ywrac_get_timestamp() + $this->delete_abandoned_time * 60, '/' );
     150                    $result['message']   = $result['response'].PHP_EOL."Data successfully inserted for yith cart abandonment recovery and postid";
     151                    $result['status_code']           = 200;
     152                }else{
     153                    $result['message']   = $result['response'].PHP_EOL."Data falied to inserted for yith cart abandonment recovery";
     154                    $result['status_code'] = 400;
     155                }
     156
     157            }
     158       
     159        }
     160
     161        if (is_plugin_active('klaviyo/klaviyo.php') && empty($razorpayData['customer_details']['email']) == false) {
     162            WC()->cart->empty_cart();
     163            $cart1cc = create1ccCart($wcOrderId);
     164
     165            $cart = WC()->cart;
     166            //Insert data for tracking started checkout.
     167            $eventData = wck_build_cart_data($cart);
     168            if (empty($eventData['$extra']['Items'])) {
     169                $response['status']    = false;
     170                $response['message']   = 'Failed to insert as Cart item does not exist in klaviyo';
     171                $statusCode            = 400;
     172                $result['response']    = $result['response'].PHP_EOL.$response['message'];
     173            }
     174            $eventData['$service'] = 'woocommerce';
     175            unset($eventData['Tags']);
     176            unset($eventData['Quantity']);
     177            $email = $customerEmail;
     178
     179            //Get token from kalviyo plugin
     180            $klaviyoApi  = WooCommerceKlaviyo::instance();
     181            $token       = $klaviyoApi->options->get_klaviyo_option('klaviyo_public_api_key');
     182            $eventObject = ['token' => $token, 'event' => '$started_checkout', 'customer_properties' => array('$email' => $email), 'properties' => $eventData];
     183            $dataParam   = json_encode($eventObject);
     184            $data        = base64_encode($dataParam);
     185            $event       = 'track';
     186
     187            $logObj['klaviyoData'] = $eventData;
     188            //calling klaviyo plugin public api
     189            $url = "https://a.klaviyo.com/api/" . $event . '?data=' . $data;
     190            file_get_contents($url);
     191        }
     192
     193        //check Abandonment cart lite plugin active or not
     194        if (is_plugin_active('woocommerce-abandoned-cart/woocommerce-ac.php') && empty($razorpayData['customer_details']['email']) == false) {
     195            //To verify whether the email id is already exist on WordPress
     196            if (email_exists($razorpayData['customer_details']['email'])) {
     197                $response['status']    = false;
     198                $statusCode            = 400;
     199                $result['response']    = $result['response'].PHP_EOL."Failed to insert data for Abandonment Cart Lite plugin for registered user";
     200            }
     201
     202            // Save Abandonment data for Abandonment cart lite
     203            $res = saveWooAbandonmentCartLiteData($razorpayData, $wcOrderId);
     204
     205            if($res['status_code'] == 200){
     206                $result['response']    = $result['response'].PHP_EOL."Successfully inserted data for Abandonment Cart Lite plugin";
     207                $result['status_code'] = 200;
     208            }else{
     209                $result['response']    = $result['response'].PHP_EOL."Failed to insert data for Abandonment Cart Lite plugin";
     210            }
     211
     212        } else {
     213            $response['status']    = true;
     214            $response['message']   = 'No action performed';
     215            $statusCode            = 200;
     216            $result['response']    = $result['response'].PHP_EOL." no abandonment plugin configured";
     217            $logObj['response']    = $response;
     218            $logObj['status_code'] = $statusCode;
     219            rzpLogInfo(json_encode($logObj));
     220        }
     221       
     222        if (!isset($result['status_code']) || $result['status_code'] !== 200) {
     223            $rzp = new WC_Razorpay();
     224            $trackObject = $rzp->newTrackPluginInstrumentation();
     225            $properties = [
     226                'error' => $result['response'] ?? 'Unknown error',
     227                'log'   => $logObj ?? [],
     228            ];
     229            $trackObject->rzpTrackDataLake('razorpay.1cc.abandon.cart.data.insertion.failed', $properties);
     230        }
     231        return new WP_REST_Response($result['response'], $result['status_code']);
     232    }
     233    catch (Throwable $e)
     234    {
     235        $rzp = new WC_Razorpay();
     236        $trackObject = $rzp->newTrackPluginInstrumentation();
     237        $properties = [
     238            'error' => $e->getMessage(),
     239            'code'  => $e->getCode(),
     240            'file'  => $e->getFile(),
     241            'line'  => $e->getLine()
     242        ];
     243        $trackObject->rzpTrackDataLake('razorpay.1cc.abandon.cart.processing.failed', $properties);
     244        rzpLogError(json_encode($properties));
     245        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
     246    }
    213247}
    214248
  • woo-razorpay/trunk/includes/api/shipping-info.php

    r2947552 r3324918  
    1212function calculateShipping1cc(WP_REST_Request $request)
    1313{
    14      global $wpdb;
    15     $params = $request->get_params();
    16 
    17     $logObj           = array();
    18     $logObj['api']    = 'calculateShipping1cc';
    19     $logObj['params'] = $params;
    20 
    21     $validateInput = validateInput('shipping', $params);
    22    
    23     if ($validateInput != null) {
    24         $response['failure_reason'] = $validateInput;
    25         $response['failure_code']   = 'VALIDATION_ERROR';
    26         $logObj['response']         = $response;
    27         rzpLogError(json_encode($logObj));
    28         return new WP_REST_Response($response, 400);
    29     }
    30 
    31     $cartResponse = false;
    32     $orderId      = (int) sanitize_text_field($params['order_id']);
    33     $addresses    = $params['addresses'];
    34     $rzpOrderId   = sanitize_text_field($params['razorpay_order_id']);
    35 
    36     initCustomerSessionAndCart();
    37     // Cleanup cart.
    38     WC()->cart->empty_cart();
    39 
    40     $cartResponse = create1ccCart($orderId);
    41 
    42     if ($cartResponse === false) {
    43         $response['status']         = false;
    44         $response['failure_reason'] = 'Invalid merchant order id';
    45         $response['failure_code']   = 'VALIDATION_ERROR';
    46         $logObj['response']         = $response;
    47         rzpLogError(json_encode($logObj));
    48         return new WP_REST_Response($response, 400);
    49     }
    50 
    51     foreach ($addresses as $address) {
    52         if ($cartResponse) {
    53             $customerResponse = shippingUpdateCustomerInformation1cc($address);
    54         }
    55 
    56         if ($customerResponse) {
    57             $response[] = shippingCalculatePackages1cc($address['id'], $orderId, $address, $rzpOrderId);
    58         } else {
    59             $response['failure_reason'] = 'Set customer shipping information failed';
     14    try
     15    {
     16        global $wpdb;
     17        $params = $request->get_params();
     18
     19        $logObj           = array();
     20        $logObj['api']    = 'calculateShipping1cc';
     21        $logObj['params'] = $params;
     22
     23        $validateInput = validateInput('shipping', $params);
     24
     25        if ($validateInput != null) {
     26            $response['failure_reason'] = $validateInput;
    6027            $response['failure_code']   = 'VALIDATION_ERROR';
    61             $logger->log('info', json_encode($response), array('source' => 'rzp1cc'));
     28            $logObj['response']         = $response;
     29            rzpLogError(json_encode($logObj));
     30
     31            $rzp = new WC_Razorpay();
     32            $trackObject = $rzp->newTrackPluginInstrumentation();
     33            $properties = [
     34                'error' => $validateInput,
     35                'log'   => $logObj
     36            ];
     37            $trackObject->rzpTrackDataLake('razorpay.1cc.shipping.validation.error', $properties);
     38
    6239            return new WP_REST_Response($response, 400);
    6340        }
    64     }
    65 
    66     // Cleanup cart.
    67     WC()->cart->empty_cart();
    68     $logObj['response'] = $response;
    69     rzpLogInfo(json_encode($logObj));
    70     return new WP_REST_Response(array('addresses' => $response), 200);
     41
     42        $cartResponse = false;
     43        $orderId      = (int) sanitize_text_field($params['order_id']);
     44        $addresses    = $params['addresses'];
     45        $rzpOrderId   = sanitize_text_field($params['razorpay_order_id']);
     46
     47        initCustomerSessionAndCart();
     48        // Cleanup cart.
     49        WC()->cart->empty_cart();
     50
     51        $cartResponse = create1ccCart($orderId);
     52
     53        if ($cartResponse === false) {
     54            $response['status']         = false;
     55            $response['failure_reason'] = 'Invalid merchant order id';
     56            $response['failure_code']   = 'VALIDATION_ERROR';
     57            $logObj['response']         = $response;
     58            rzpLogError(json_encode($logObj));
     59
     60            $rzp = new WC_Razorpay();
     61            $trackObject = $rzp->newTrackPluginInstrumentation();
     62            $properties = [
     63                'error' => 'Invalid merchant order id',
     64                'log'   => $logObj
     65            ];
     66            $trackObject->rzpTrackDataLake('razorpay.1cc.shipping.validation.error', $properties);
     67
     68            return new WP_REST_Response($response, 400);
     69        }
     70
     71        foreach ($addresses as $address) {
     72            if ($cartResponse) {
     73                $customerResponse = shippingUpdateCustomerInformation1cc($address);
     74            }
     75
     76            if ($customerResponse) {
     77                $response[] = shippingCalculatePackages1cc($address['id'], $orderId, $address, $rzpOrderId);
     78            } else {
     79                $response['failure_reason'] = 'Set customer shipping information failed';
     80                $response['failure_code']   = 'VALIDATION_ERROR';
     81                $logger->log('info', json_encode($response), array('source' => 'rzp1cc'));
     82
     83                $rzp = new WC_Razorpay();
     84                $trackObject = $rzp->newTrackPluginInstrumentation();
     85                $properties = [
     86                    'error' => 'Set customer shipping information failed',
     87                    'log'   => $logObj
     88                ];
     89                $trackObject->rzpTrackDataLake('razorpay.1cc.shipping.validation.error', $properties);
     90
     91                return new WP_REST_Response($response, 400);
     92            }
     93        }
     94
     95        // Cleanup cart.
     96        WC()->cart->empty_cart();
     97        $logObj['response'] = $response;
     98        rzpLogInfo(json_encode($logObj));
     99        return new WP_REST_Response(array('addresses' => $response), 200);
     100    }
     101    catch (Throwable $e)
     102    {
     103        $rzp = new WC_Razorpay();
     104        $trackObject = $rzp->newTrackPluginInstrumentation();
     105        $properties = [
     106            'error' => $e->getMessage(),
     107            'code'  => $e->getCode(),
     108            'file'  => $e->getFile(),
     109            'line'  => $e->getLine()
     110        ];
     111        $trackObject->rzpTrackDataLake('razorpay.1cc.shipping.processing.failed', $properties);
     112        rzpLogError(json_encode($properties));
     113
     114        return new WP_REST_Response(['message' => "woocommerce server error : " . $e->getMessage()], 500);
     115    }
    71116}
    72117
  • woo-razorpay/trunk/includes/plugin-instrumentation.php

    r3221997 r3324918  
    1313    {
    1414        $this->api = $api;
     15
     16        if (empty($key_id) === true)
     17        {
     18            $key_id = get_option('woocommerce_razorpay_settings')['key_id'];
     19        }
    1520        $this->mode = (substr($key_id, 0, 8) === 'rzp_live') ? 'live' : 'test';
    1621
  • woo-razorpay/trunk/includes/razorpay-webhook.php

    r3282256 r3324918  
    138138                    rzpLogError(json_encode($log));
    139139
     140                    $trackObject = $this->razorpay->newTrackPluginInstrumentation();
     141                    $properties = [
     142                        'error' => $e->getMessage(),
     143                        'log'   => $log
     144                    ];
     145                    $trackObject->rzpTrackDataLake('razorpay.webhook.signature.verification.failed', $properties);
     146
    140147                    return;
    141148                }
     
    222229        {
    223230            rzpLogError("Insert webhook event failed. " . $e->getMessage());
     231
     232            $trackObject = $this->razorpay->newTrackPluginInstrumentation();
     233            $properties = [
     234                'error' => $e->getMessage()
     235            ];
     236            $trackObject->rzpTrackDataLake('razorpay.webhook.save.event.failed', $properties);
    224237        }
    225238    }
     
    311324        }
    312325
    313         if ($orderStatus == 'draft') {
     326        if ($orderStatus == 'checkout-draft' || $orderStatus == 'draft') {
    314327            updateOrderStatus($orderId, 'wc-pending');
    315328        }
     
    417430        }
    418431
    419         if ($orderStatus == 'draft') {
     432        if ($orderStatus == 'checkout-draft' || $orderStatus == 'draft') {
    420433            updateOrderStatus($orderId, 'wc-pending');
    421434        }
  • woo-razorpay/trunk/readme.txt

    r3288430 r3324918  
    44Requires at least: 3.9.2
    55Tested up to: 6.8
    6 Stable tag: 4.7.4
     6Stable tag: 4.7.5
    77Requires PHP: 7.0
    88License: GPLv2 or later
     
    6969
    7070== Changelog ==
     71
     72= 4.7.5 =
     73* Added instrumentation for alerts.
     74* Fixed certificate issue in cron.
     75* Fixed HPOS and signature verification issue in 1cc.
    7176
    7277= 4.7.4 =
  • woo-razorpay/trunk/tests/phpunit/tests/test-order-methods.php

    r3100300 r3324918  
    126126        $sessionKey = "razorpay_order_id" . $orderId;
    127127
    128         $razorpayOrderId = get_transient($sessionKey);
    129 
     128        $orderData = wc_get_order($wcOrderId);
     129        if ($this->isHposEnabled)
     130        {
     131            $razorpayOrderId = $orderData->get_meta($sessionKey);
     132        }
     133        else
     134        {
     135            $razorpayOrderId = get_post_meta($wcOrderId, $sessionKey, true);
     136        }
    130137        $address = array(
    131138            'first_name' => 'Shaina',
  • woo-razorpay/trunk/woo-razorpay.php

    r3288430 r3324918  
    44 * Plugin URI: https://razorpay.com
    55 * Description: Razorpay Payment Gateway Integration for WooCommerce.Razorpay Welcome Back Offer: New to Razorpay? Sign up to enjoy FREE payments* of INR 2 lakh till March 31st! Transact before January 10th to grab the offer.
    6  * Version: 4.7.4
    7  * Stable tag: 4.7.4
     6 * Version: 4.7.5
     7 * Stable tag: 4.7.5
    88 * Author: Team Razorpay
    99 * WC tested up to: 9.1.2
     
    479479                        isset($merchantPreferences['assigned_features']) === false)
    480480                    {
    481                         throw new Exception("Error in Api call.");
     481                        throw new Exception("Error in get features Api call.");
    482482                    }
    483483
     
    524524                {
    525525                    rzpLogError($e->getMessage());
     526
     527                    $trackObject = $this->newTrackPluginInstrumentation();
     528                    $properties = [
     529                        'error' => $e->getMessage()
     530                    ];
     531                    $trackObject->rzpTrackDataLake('razorpay.afd.rtb.set.features.failed', $properties);
     532
    526533                    return;
    527534                }
     
    578585            {
    579586                $validationErrorProperties = $this->triggerValidationInstrumentation(
    580                     ['error_message' => 'Key Id and or Key Secret is null']);
     587                    ['error' => 'Key Id and or Key Secret is null']);
    581588                ?>
    582589                <div class="notice error is-dismissible" >
     
    597604            {
    598605                $validationErrorProperties = $this->triggerValidationInstrumentation(
    599                     ['error_message' => 'Invalid Key Id and Key Secret']);
     606                    ['error' => 'Invalid Key Id and Key Secret']);
    600607                ?>
    601608                <div class="notice error is-dismissible" >
     
    724731        }
    725732
    726         public function newTrackPluginInstrumentation($key, $secret)
     733        public function newTrackPluginInstrumentation($key = "", $secret = "")
    727734        {
    728735            $api = $this->getRazorpayApiInstance($key, $secret);
     
    925932                );
    926933
    927                 error_log(json_encode($log));
     934                $trackObject = $this->newTrackPluginInstrumentation();
     935                $properties = [
     936                    'error'     => $e->getMessage(),
     937                    'method'    => $method,
     938                    'url'       => $url
     939                ];
     940                $trackObject->rzpTrackDataLake('razorpay.webhook.api.failed', $properties);
     941
    928942                rzpLogError(json_encode($log));
    929943            }
     
    10221036            try
    10231037            {
    1024                 $razorpayOrderId = get_transient($sessionKey);
     1038                if ($this->isHposEnabled)
     1039                {
     1040                    $razorpayOrderId = $order->get_meta($sessionKey);
     1041                }
     1042                else
     1043                {
     1044                    $razorpayOrderId = get_post_meta($orderId, $sessionKey, true);
     1045                }
    10251046                rzpLogInfo("razorpayOrderId $razorpayOrderId | sessionKey $sessionKey");
    10261047                // If we don't have an Order
    10271048                // or the if the order is present in transient but doesn't match what we have saved
    1028                 if (($razorpayOrderId === false) or
     1049                if (($razorpayOrderId === false || $razorpayOrderId == "") or
    10291050                    (($razorpayOrderId and ($this->verifyOrderAmount($razorpayOrderId, $orderId, $is1ccCheckout)) === false)))
    10301051                {
     
    11501171            $sessionKey = $this->getOrderSessionKey($wcOrderId);
    11511172
    1152             $razorpayOrderId = get_transient($sessionKey);
    1153 
     1173            $orderData = wc_get_order($wcOrderId);
     1174
     1175            if ($orderData) {
     1176                if ($this->isHposEnabled)
     1177                {
     1178                    $razorpayOrderId = $orderData->get_meta($sessionKey);
     1179                }
     1180                else
     1181                {
     1182                    $razorpayOrderId = get_post_meta($wcOrderId, $sessionKey, true);
     1183                }
     1184            }
    11541185            $productinfo = "Order $orderId";
    11551186
     
    11601191                'description'  => $productinfo,
    11611192                'notes'        => array(
    1162                     self::WC_ORDER_ID => $orderId,
    1163                     self::WC_ORDER_NUMBER => $wcOrderId
     1193                    self::WC_ORDER_ID       => $wcOrderId,
     1194                    self::WC_ORDER_NUMBER   => $orderId
    11641195                ),
    11651196                'order_id'     => $razorpayOrderId,
     
    12531284            {
    12541285                rzpLogInfo("rzp order error " . $e->getMessage());
     1286
     1287                $trackObject = $this->newTrackPluginInstrumentation();
     1288                $properties = [
     1289                    'error' => $e->getMessage()
     1290                ];
     1291                $trackObject->rzpTrackDataLake('razorpay.create.order.failed', $properties);
     1292
    12551293                return $e;
    12561294            }
     
    12741312            $razorpayOrderId = $razorpayOrder['id'];
    12751313
    1276             // Storing the razorpay order id in transient for 5 hours time.
    1277             set_transient($sessionKey, $razorpayOrderId, 18000);
    1278 
    1279             // By default woocommerce session TTL is 48 hours.
    1280             $woocommerce->session->set($sessionKey, $razorpayOrderId);
     1314            $order = wc_get_order($orderId);
     1315            if ($order) {
     1316                // Update or create the meta data using the session key
     1317                if ($this->isHposEnabled)
     1318                {
     1319                    $order->update_meta_data($sessionKey, $razorpayOrderId);
     1320                    $order->save();
     1321                }
     1322                else
     1323                {
     1324                    update_post_meta($orderId, $sessionKey, $razorpayOrderId);
     1325                }
     1326                rzpLogInfo("Meta data saved for Order ID {$orderId} with key {$sessionKey} and value {$razorpayOrderId}.");
     1327
     1328            } else {
     1329                rzpLogInfo("Order not found for order ID {$orderId}. Unable to update order meta.");
     1330            }
    12811331
    12821332            rzpLogInfo('For order session key ' . $sessionKey);
     
    13231373                $message = $e->getMessage();
    13241374                rzpLogInfo("Failed at verifyOrderAmount with $message");
     1375                $trackObject = $this->newTrackPluginInstrumentation();
     1376                $properties = [
     1377                    'error' => $message
     1378                ];
     1379                $trackObject->rzpTrackDataLake('razorpay.order.amount.validation.failed', $properties);
     1380
    13251381                return "RAZORPAY ERROR: Order fetch failed with the message '$message'";
    13261382            }
     
    16261682            catch(Exception $e)
    16271683            {
     1684                $trackObject = $this->newTrackPluginInstrumentation();
     1685                $properties = [
     1686                    'error' => $e->getMessage()
     1687                ];
     1688                $trackObject->rzpTrackDataLake('razorpay.refund.failed', $properties);
     1689
    16281690                return new WP_Error('error', __($e->getMessage(), 'woocommerce'));
    16291691            }
     
    16781740            {
    16791741                rzpLogInfo('failure message for refund:' . $e->getMessage());
     1742
     1743                $trackObject = $this->newTrackPluginInstrumentation();
     1744                $properties = [
     1745                    'error' => $e->getMessage()
     1746                ];
     1747                $trackObject->rzpTrackDataLake('razorpay.refund.with.giftcard.failed', $properties);
    16801748            }
    16811749
     
    18751943                {
    18761944                    $error = 'WOOCOMMERCE_ERROR: Payment to Razorpay Failed. ' . $e->getMessage();
     1945
     1946                    $trackObject = $this->newTrackPluginInstrumentation();
     1947                    $properties = [
     1948                        'error'         => $e->getMessage(),
     1949                        'order_id'      => $orderId,
     1950                        'payment_id'    => $_POST[self::RAZORPAY_PAYMENT_ID]
     1951                    ];
     1952                    $trackObject->rzpTrackDataLake('razorpay.callback.signature.verification.failed', $properties);
    18771953                }
    18781954            }
     
    19011977                    $sessionKey = $this->getOrderSessionKey($orderId);
    19021978
    1903                     //Check the transient data for razorpay order id, if it's not available then look into session data.
    1904                     if(get_transient($sessionKey))
     1979                    if ($this->isHposEnabled)
    19051980                    {
    1906                         $razorpayOrderId = get_transient($sessionKey);
     1981                        $razorpayOrderId = $order->get_meta($sessionKey);
    19071982                    }
    19081983                    else
    19091984                    {
    1910                         $razorpayOrderId = $woocommerce->session->get($sessionKey);
     1985                        $razorpayOrderId = get_post_meta($orderId, $sessionKey, true);
    19111986                    }
    19121987
     
    19392014                    $razorpayOrderId = '';
    19402015
    1941                     if(get_transient($sessionKey))
     2016                    $order = wc_get_order($orderId);
     2017                    if ($this->isHposEnabled)
    19422018                    {
    1943                         $razorpayOrderId = get_transient($sessionKey);
     2019                        $razorpayOrderId = $order->get_meta($sessionKey);
    19442020                    }
    19452021                    else
    19462022                    {
    1947                         $razorpayOrderId = $woocommerce->session->get($sessionKey);
     2023                        $razorpayOrderId = get_post_meta($orderId, $sessionKey, true);
    19482024                    }
    19492025
     
    19912067
    19922068            $sessionKey = $this->getOrderSessionKey($orderId);
    1993             //Check the transient data for razorpay order id, if it's not available then look into session data.
    1994             if(get_transient($sessionKey))
    1995             {
    1996                 $razorpayOrderId = get_transient($sessionKey);
     2069            $order = wc_get_order($orderId);
     2070            if ($this->isHposEnabled)
     2071            {
     2072                $razorpayOrderId = $order->get_meta($sessionKey);
    19972073            }
    19982074            else
    19992075            {
    2000                 $razorpayOrderId = $woocommerce->session->get($sessionKey);
     2076                $razorpayOrderId = get_post_meta($orderId, $sessionKey, true);
    20012077            }
    20022078
     
    20512127        public function updateOrder(& $order, $success, $errorMessage, $razorpayPaymentId, $virtualAccountId = null, $webhook = false)
    20522128        {
    2053             global $woocommerce;
    2054 
    2055             $orderId = $order->get_order_number();
    2056 
    2057             rzpLogInfo("updateOrder orderId: $orderId , razorpayPaymentId: $razorpayPaymentId , success: $success");
    2058 
    2059             if ($success === true)
    2060             {
    2061                 try
    2062                 {
    2063                     $wcOrderId = $order->get_id();
    2064 
    2065                     if ($this->isHposEnabled) {
    2066                         $is1ccOrder = $order->get_meta('is_magic_checkout_order');
    2067                     }else{
    2068                         $is1ccOrder = get_post_meta( $orderId, 'is_magic_checkout_order', true );
    2069                     }
    2070 
    2071                     rzpLogInfo("Order details check initiated step 1 for the orderId: $wcOrderId");
    2072 
    2073                     if (is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes')
     2129            try
     2130            {
     2131                global $woocommerce;
     2132
     2133                $orderId = $order->get_order_number();
     2134
     2135                rzpLogInfo("updateOrder orderId: $orderId , razorpayPaymentId: $razorpayPaymentId , success: $success");
     2136
     2137                if ($success === true)
     2138                {
     2139                    try
    20742140                    {
    2075                         rzpLogInfo("Order details update initiated step 1 for the orderId: $wcOrderId");
    2076 
    2077                         //To verify whether the 1cc update order function already under execution or not
    2078                         if(get_transient('wc_order_under_process_'.$wcOrderId) === false)
     2141                        $wcOrderId = $order->get_id();
     2142
     2143                        if ($this->isHposEnabled) {
     2144                            $is1ccOrder = $order->get_meta('is_magic_checkout_order');
     2145                        }else{
     2146                            $is1ccOrder = get_post_meta($wcOrderId, 'is_magic_checkout_order', true);
     2147                        }
     2148
     2149                        rzpLogInfo("Order details check initiated step 1 for the orderId: $wcOrderId");
     2150
     2151                        if (is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes')
    20792152                        {
    2080                             rzpLogInfo("Order details update initiated step 2 for the orderId: $wcOrderId");
    2081 
    2082                             $this->update1ccOrderWC($order, $wcOrderId, $razorpayPaymentId);
     2153                            rzpLogInfo("Order details update initiated step 1 for the orderId: $wcOrderId");
     2154
     2155                            //To verify whether the 1cc update order function already under execution or not
     2156                            if(get_transient('wc_order_under_process_'.$wcOrderId) === false)
     2157                            {
     2158                                rzpLogInfo("Order details update initiated step 2 for the orderId: $wcOrderId");
     2159
     2160                                $this->update1ccOrderWC($order, $wcOrderId, $razorpayPaymentId);
     2161                            }
     2162
    20832163                        }
    2084 
    2085                     }
    2086                 } catch (Exception $e) {
    2087                     $message = $e->getMessage();
    2088                     rzpLogError("Failed to update 1cc flow with error : $message");
    2089                 }
    2090 
    2091                 $payment_method=$order->get_payment_method();
    2092 
    2093                 // Need to set the status manually to processing incase of COD payment method.
    2094                 if ($payment_method == "cod")
    2095                 {
    2096                     $order->update_status( 'processing' );
     2164                    } catch (Exception $e) {
     2165                        $message = $e->getMessage();
     2166                        rzpLogError("Failed to update 1cc flow with error : $message");
     2167                    }
     2168
     2169                    $payment_method=$order->get_payment_method();
     2170
     2171                    // Need to set the status manually to processing incase of COD payment method.
     2172                    if ($payment_method == "cod")
     2173                    {
     2174                        $order->update_status( 'processing' );
     2175                    }
     2176                    else
     2177                    {
     2178                        $order->payment_complete($razorpayPaymentId);
     2179                    }
     2180
     2181                    if(is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes' && is_plugin_active('woo-save-abandoned-carts/cartbounty-abandoned-carts.php')){
     2182                        handleCBRecoveredOrder($orderId);
     2183                    }
     2184
     2185                    // Check Wati.io retargetting plugin is active or not
     2186                    if (is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes' && is_plugin_active('wati-chat-and-notification/wati-chat-and-notification.php')){
     2187                        handleWatiRecoveredOrder($orderId);
     2188                    }
     2189
     2190                    $order->add_order_note("Razorpay payment successful <br/>Razorpay Id: $razorpayPaymentId");
     2191
     2192                    if($this->getSetting('route_enable') == 'yes')
     2193                    {
     2194                        $razorpayRoute = new RZP_Route_Action();
     2195
     2196                        $wcOrderId = $order->get_id();
     2197
     2198                        $razorpayRoute->transferFromPayment($wcOrderId, $razorpayPaymentId); // creates transfers from payment
     2199                    }
     2200
     2201                    if($virtualAccountId != null)
     2202                    {
     2203                        $order->add_order_note("Virtual Account Id: $virtualAccountId");
     2204                    }
     2205
     2206                    if (isset($woocommerce->cart) === true)
     2207                    {
     2208                        $woocommerce->cart->empty_cart();
     2209                    }
    20972210                }
    20982211                else
    20992212                {
    2100                     $order->payment_complete($razorpayPaymentId);
    2101                 }
    2102 
    2103                 if(is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes' && is_plugin_active('woo-save-abandoned-carts/cartbounty-abandoned-carts.php')){
    2104                     handleCBRecoveredOrder($orderId);
    2105                 }
    2106 
    2107                 // Check Wati.io retargetting plugin is active or not
    2108                 if (is1ccEnabled() && !empty($is1ccOrder) && $is1ccOrder == 'yes' && is_plugin_active('wati-chat-and-notification/wati-chat-and-notification.php')){
    2109                     handleWatiRecoveredOrder($orderId);
    2110                 }
    2111 
    2112                 $order->add_order_note("Razorpay payment successful <br/>Razorpay Id: $razorpayPaymentId");
    2113 
    2114                 if($this->getSetting('route_enable') == 'yes')
    2115                 {
    2116                     $razorpayRoute = new RZP_Route_Action();
    2117 
    2118                     $wcOrderId = $order->get_id();
    2119 
    2120                     $razorpayRoute->transferFromPayment($wcOrderId, $razorpayPaymentId); // creates transfers from payment
    2121                 }
    2122 
    2123                 if($virtualAccountId != null)
    2124                 {
    2125                     $order->add_order_note("Virtual Account Id: $virtualAccountId");
    2126                 }
    2127 
    2128                 if (isset($woocommerce->cart) === true)
    2129                 {
    2130                     $woocommerce->cart->empty_cart();
    2131                 }
    2132             }
    2133             else
    2134             {
    2135                 $this->msg['class'] = 'error';
    2136                 $this->msg['message'] = $errorMessage;
    2137 
    2138                 if ($razorpayPaymentId)
    2139                 {
    2140                     $order->add_order_note("Payment Failed. Please check Razorpay Dashboard. <br/> Razorpay Id: $razorpayPaymentId");
    2141                 }
    2142 
    2143                 $order->add_order_note("Transaction Failed: $errorMessage<br/>");
    2144                 $order->update_status('failed');
    2145             }
    2146 
    2147             if ($webhook === false)
    2148             {
    2149                 $this->add_notice($this->msg['message'], $this->msg['class']);
    2150 
    2151                 rzpLogInfo("Woocommerce orderId: $orderId processed through callback");
    2152             }
    2153             else
    2154             {
    2155                 rzpLogInfo("Woocommerce orderId: $orderId processed through webhook");
     2213                    $this->msg['class'] = 'error';
     2214                    $this->msg['message'] = $errorMessage;
     2215
     2216                    if ($razorpayPaymentId)
     2217                    {
     2218                        $order->add_order_note("Payment Failed. Please check Razorpay Dashboard. <br/> Razorpay Id: $razorpayPaymentId");
     2219                    }
     2220
     2221                    $order->add_order_note("Transaction Failed: $errorMessage<br/>");
     2222                    $order->update_status('failed');
     2223                }
     2224
     2225                if ($webhook === false)
     2226                {
     2227                    $this->add_notice($this->msg['message'], $this->msg['class']);
     2228
     2229                    rzpLogInfo("Woocommerce orderId: $orderId processed through callback");
     2230                }
     2231                else
     2232                {
     2233                    rzpLogInfo("Woocommerce orderId: $orderId processed through webhook");
     2234                }
     2235            }
     2236            catch (\Exception $e)
     2237            {
     2238                $trackObject = $this->newTrackPluginInstrumentation();
     2239                $properties = [
     2240                    'error' => $e->getMessage()
     2241                ];
     2242                $trackObject->rzpTrackDataLake('razorpay.update.order.failed', $properties);
    21562243            }
    21572244        }
     
    21702257            $sessionKey = $this->getOrderSessionKey($wcOrderId);
    21712258
    2172             //Check the transient data for razorpay order id, if it's not available then look into session data.
    2173             if(get_transient($sessionKey))
    2174             {
    2175                 $razorpayOrderId = get_transient($sessionKey);
     2259            if ($this->isHposEnabled)
     2260            {
     2261                $razorpayOrderId = $order->get_meta($sessionKey);
    21762262            }
    21772263            else
    21782264            {
    2179                 $razorpayOrderId = $woocommerce->session->get($sessionKey);
     2265                $razorpayOrderId = get_post_meta($wcOrderId, $sessionKey, true);
    21802266            }
    21812267
     
    31153201
    31163202        $properties = [
    3117             'webhookCronCreationSuccess' => false
     3203            'error' => 'webhook cron creation failed' . $e->getMessage()
    31183204        ];
    31193205
    3120         $trackObject->rzpTrackDataLake('webhookCron.creation', $properties);
     3206        $trackObject->rzpTrackDataLake('razorpay.webhook.cron.creation.failed', $properties);
    31213207    }
    31223208
     
    31263212    function execRzpWooWebhookEvents()
    31273213    {
     3214        if (file_exists( ABSPATH . WPINC . '/certificates/ca-bundle.crt')) {
     3215            require_once ABSPATH . WPINC . '/Requests/src/Autoload.php';
     3216            WpOrg\Requests\Autoload::register();
     3217            WpOrg\Requests\Requests::set_certificate_path( ABSPATH . WPINC . '/certificates/ca-bundle.crt' );
     3218        }
     3219
    31283220        global $wpdb;
    31293221        rzpLogInfo("Running webhook cron.");
     
    31783270        {
    31793271            rzpLogError("Webhook cron execution failed: " . $e->getMessage());
     3272
     3273            $rzp = new WC_Razorpay();
     3274            $trackObject = $rzp->newTrackPluginInstrumentation();
     3275            $properties = [
     3276                'error' => $e->getMessage()
     3277            ];
     3278            $trackObject->rzpTrackDataLake('razorpay.webhook.cron.execution.failed', $properties);
    31803279        }
    31813280        rzpLogInfo("Webhook cron execution completed.");
     
    32213320            $trackObject = $rzp->newTrackPluginInstrumentation($key_id, '');
    32223321            $properties = [
    3223                 'webhookCronTableSetupSuccess' => false
     3322                'error' => 'webhook cron table setup failed' . $e->getMessage()
    32243323            ];
    32253324
    3226             $trackObject->rzpTrackDataLake('webhookCron.tableSetup', $properties);
     3325            $trackObject->rzpTrackDataLake('razorpay.webhook.cron.table.setup.failed', $properties);
    32273326        }
    32283327    }
Note: See TracChangeset for help on using the changeset viewer.