Plugin Directory

Changeset 2916822


Ignore:
Timestamp:
05/24/2023 12:31:39 PM (3 years ago)
Author:
breadintegrations
Message:

Admin Bread carts support for Woocomerce

Location:
bread-finance
Files:
2 added
6 edited
19 copied

Legend:

Unmodified
Added
Removed
  • bread-finance/tags/release-3.3.4/README.md

    r2907371 r2916822  
    44Requires at least: 4.9
    55Tested up to: 6.1.1
    6 Stable tag: 3.3.3
     6Stable tag: 3.3.4
    77Requires PHP: 5.6
    88WC requires at least: 3.0
     
    7272
    7373== Changelog ==
     74= 3.3.4
     75* Current release
     76* Bread Admin carts support
    7477
    7578= 3.3.3
    76 * Current release
    7779* Bug fix for discount codes applied with Avatax enabled
    7880
  • bread-finance/tags/release-3.3.4/bread-finance.php

    r2907371 r2916822  
    66 * Author: Bread Pay
    77 * Author URI: https://payments.breadfinancial.com/
    8  * Version: 3.3.3
     8 * Version: 3.3.4
    99 * Text Domain: bread-finance
    1010 * Domain Path: /i18n/languages/
     
    2222
    2323//Require minimums and constants
    24 define('WC_BREAD_FINANCE_VERSION', '3.3.3');
     24define('WC_BREAD_FINANCE_VERSION', '3.3.4');
    2525define('WC_BREAD_FINANCE_MIN_PHP_VER', '5.6.0');
    2626define('WC_BREAD_FINANCE_MIN_WC_VER', '3.4.0');
     
    190190
    191191            //Classes
     192            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-admin-carts-helper.php';
    192193            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-utilities.php';
    193194            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-form-fields.php';
  • bread-finance/tags/release-3.3.4/classes/class-bread-finance-form-fields.php

    r2870595 r2916822  
    308308        );
    309309       
     310        $admin_carts = array(
     311            'admin_cart_settings' => array(
     312                'title' => esc_html__('Bread Admin Carts', $text_domain),
     313                'type' => 'title'
     314            ),
     315            'sandbox_platform_merchantId' => array(
     316                'title' => esc_html__('Sandbox Platform MerchantId', $text_domain),
     317                'type' => 'text',
     318                'desc_tip' => esc_html__('Your Bread Sandbox MerchantId. Contact your Bread representative')
     319            ),
     320            'sandbox_platform_programId' => array(
     321                'title' => esc_html__('Sandbox Platform ProgramId', $text_domain),
     322                'type' => 'text',
     323                'desc_tip' => esc_html__('Your Bread Sandbox ProgramId. Contact your Bread representative')
     324            ),
     325            'production_platform_merchantId' => array(
     326                'title' => esc_html__('Production Platform MerchantId', $text_domain),
     327                'type' => 'text',
     328                'desc_tip' => esc_html__('Your Bread Production MerchantId. Contact your Bread representative')
     329            ),
     330            'production_platform_programId' => array(
     331                'title' => esc_html__('Production Platform ProgramId', $text_domain),
     332                'type' => 'text',
     333                'desc_tip' => esc_html__('Your Bread Production ProgramId. Contact your Bread representative')
     334            ),
     335        );
     336
    310337        $advanced = array(
    311338            'advanced_settings_title' => array(
     
    318345        );
    319346
    320         $settings = array_merge($general, $environment, $platform_credentials, $classic_credentials, $button_appearance, $button_defaults, $advanced);
     347        $settings = array_merge($general, $environment, $platform_credentials, $classic_credentials, $button_appearance, $admin_carts, $button_defaults, $advanced);
    321348        return apply_filters('bread_finance_wc_gateway_settings', $settings);
    322349    }   
  • bread-finance/tags/release-3.3.4/classes/class-bread-finance-gateway.php

    r2897614 r2916822  
    129129            add_action('woocommerce_order_action_create_bread_cart_link', array($this, 'create_bread_cart_link'));
    130130            add_action('woocommerce_order_action_email_bread_cart_link', array($this, 'email_bread_cart_link'));
     131           
     132            add_filter( 'query_vars', array($this, 'custom_bread_vars'));
    131133
    132134            //Enable Sentry logging
     
    12941296         */
    12951297        public function send_bread_cart_link($order, $method) {
     1298            $env = $this->load_bread_env();
    12961299            $bread_cart_id = $order->get_meta("bread_cart_id");
     1300            $bread_api = $this->load_bread_api_version();
    12971301            $endpoint = '/carts/' . $bread_cart_id . '/' . $method;
    12981302            $payload = ( $method === 'text' ) ? array("phone" => $order->get_billing_phone()) : array(
     
    13001304                "email" => $order->get_billing_email()
    13011305            );
    1302 
    1303             $bread_api = $this->load_bread_api_version();
    1304             $response = $bread_api->sendBreadCartLink($endpoint, $payload);
     1306            $response = null;
     1307            if ($env === 'bread_2') {
     1308                $response = $bread_api->sendBreadCartLink($bread_cart_id, array());
     1309            } else {
     1310                $response = $bread_api->sendBreadCartLink($endpoint, $payload);
     1311            }
    13051312            if (is_wp_error($response)) {
    13061313                $order->add_order_note("Error: " . json_encode($response));
     
    17991806                return;
    18001807            }
    1801 
     1808           
     1809            $env = $this->load_bread_env();
    18021810            $order_id = get_query_var('orderRef');
    1803             $tx_id = get_query_var('transactionId');
    1804 
    1805             if (strlen($tx_id) > 0 && strlen($order_id) > 0) {
    1806                 /* Complete URL Route */
    1807 
    1808                 $tx = $this->get_transaction($tx_id);
    1809                 $order = wc_get_order($order_id);
    1810                 $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
    1811 
    1812                 $response = $this->process_bread_cart_payment($order_id, $tx_id);
    1813                 $bread_api = $this->load_bread_api_version();
    1814                 $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
    1815                 $order->update_meta_data('bread_cart_link', 'Bread cart link has expired');
    1816 
    1817                 if ($response['result'] === 'error') {
    1818                     $order->update_status('failed');
    1819                     $order->add_order_note($response['message']);
     1811            $order = wc_get_order($order_id);
     1812            if($env === 'bread_2') {
     1813                $action = get_query_var('action');
     1814                //Do we have a checkout error?
     1815                if($action == 'checkout-error') {
     1816                    /* Error URL Route */
     1817                    wc_get_logger()->debug('Checkout error');
     1818                    $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
     1819                    $order = wc_get_order($order_id);
     1820                    $order->add_order_note($errorMessage);
    18201821                    $order->save();
    18211822
    1822                     $errorInfo = array(
    1823                         'response' => $response,
    1824                         'txId' => $tx_id,
    1825                         'orderId' => $order_id
    1826                     );
    1827 
    1828                     $this->log_Bread_issue("error", "[Plugin] " . $response['message'], $errorInfo);
    1829                 }
    1830 
    1831                 wp_redirect($order->get_checkout_order_received_url());
    1832                 ob_flush();
    1833                 exit;
    1834             } else if (strlen($order_id) > 0) {
    1835                 /* Error URL Route */
    1836 
    1837                 $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
    1838                 $order = wc_get_order($order_id);
    1839                 $order->add_order_note($errorMessage);
    1840                 $order->save();
    1841 
    1842                 $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
    1843 
    1844                 wp_redirect(home_url());
    1845                 ob_flush();
    1846                 exit;
    1847             }
     1823                    $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
     1824
     1825                    wp_redirect(home_url());
     1826                    ob_flush();
     1827                    exit;
     1828                }
     1829               
     1830                //Do we have a checkout complete
     1831                if($action == 'checkout-complete') {
     1832                    wc_get_logger()->debug('Checkout complete');
     1833                    $message = 'Note: Customer checkout action complete';
     1834                    $order = wc_get_order($order_id);
     1835                    $order->add_order_note($message);
     1836                    $order->save();
     1837                    wp_redirect($order->get_checkout_order_received_url());
     1838                    ob_flush();
     1839                    exit;
     1840                }
     1841               
     1842                //Do we have a success checkout callback
     1843                if($action == 'callback') {
     1844                    wc_get_logger()->debug('Success callback');
     1845                    $tx_id = null;
     1846                    $data = json_decode(file_get_contents('php://input'), true);
     1847                    if(isset($data['transactionId'])) {
     1848                        $tx_id = trim($data['transactionId']);
     1849                    }
     1850                    $tx = $this->get_transaction($tx_id);
     1851                    $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
     1852                    $response = $this->process_bread_platform_cart_payment($order_id, $tx_id);
     1853                    $bread_api = $this->load_bread_api_version();
     1854                    $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
     1855                    wp_redirect($order->get_checkout_order_received_url());
     1856                    ob_flush();
     1857                    exit;
     1858                }
     1859            } else {
     1860                $tx_id = get_query_var('transactionId');
     1861                if (strlen($tx_id) > 0 && strlen($order_id) > 0) {
     1862                    /* Complete URL Route */
     1863
     1864                    $tx = $this->get_transaction($tx_id);
     1865                   
     1866                    $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
     1867
     1868                    $response = $this->process_bread_cart_payment($order_id, $tx_id);
     1869                    $bread_api = $this->load_bread_api_version();
     1870                    $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
     1871                    $order->update_meta_data('bread_cart_link', 'Bread cart link has expired');
     1872
     1873                    if ($response['result'] === 'error') {
     1874                        $order->update_status('failed');
     1875                        $order->add_order_note($response['message']);
     1876                        $order->save();
     1877
     1878                        $errorInfo = array(
     1879                            'response' => $response,
     1880                            'txId' => $tx_id,
     1881                            'orderId' => $order_id
     1882                        );
     1883
     1884                        $this->log_Bread_issue("error", "[Plugin] " . $response['message'], $errorInfo);
     1885                    }
     1886
     1887                    wp_redirect($order->get_checkout_order_received_url());
     1888                    ob_flush();
     1889                    exit;
     1890                } else if (strlen($order_id) > 0) {
     1891                    /* Error URL Route */
     1892
     1893                    $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
     1894                    $order = wc_get_order($order_id);
     1895                    $order->add_order_note($errorMessage);
     1896                    $order->save();
     1897
     1898                    $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
     1899
     1900                    wp_redirect(home_url());
     1901                    ob_flush();
     1902                    exit;
     1903                }
     1904            }
    18481905        }
    18491906
     
    18551912        public function process_bread_cart_payment($order_id, $tx_id) {
    18561913            $order = wc_get_order($order_id);
    1857 
    18581914            $tx = $this->get_transaction($tx_id);
    18591915            if ($this->has_error($tx)) {
     
    18911947                'result' => 'success',
    18921948            );
     1949        }
     1950       
     1951        /**
     1952         * Process bread platform cart payment
     1953         */
     1954        public function process_bread_platform_cart_payment($order_id, $tx_id) {
     1955            $order = wc_get_order($order_id);
     1956            $env = $this->load_bread_env();
     1957            $transaction = $this->get_transaction($tx_id);
     1958            if ($this->has_error($transaction)) {
     1959                return array(
     1960                    'result' => 'error',
     1961                    'message' => 'Error retrieving transaction',
     1962                    'tx' => $transaction,
     1963                );
     1964            }
     1965            $order->add_meta_data('bread_tx_id', $transaction['id']);
     1966            $order->save();
     1967           
     1968            $this->bread_finance_api = Bread_Finance_V2_Api::instance();
     1969           
     1970            $authorized_transaction = $this->parse_api_response($this->bread_finance_api->authorizeTransaction($tx_id, $transaction['totalAmount']['value'], $transaction['totalAmount']['currency'], $order_id));
     1971            $this->log(
     1972                    __FUNCTION__,
     1973                    'Authorisation request details. #' . json_encode($authorized_transaction)
     1974            );
     1975            if ($this->has_error($authorized_transaction)) {
     1976                return $this->error_result($authorized_transaction);
     1977            }
     1978
     1979            // Validate Transaction Status / set order status
     1980            if (strtoupper($authorized_transaction['status']) !== 'AUTHORIZED') {
     1981                $message = esc_html__('Transaction status is not currently AUTHORIZED. Order Status: ' . $authorized_transaction['status'], self::TEXT_DOMAIN);
     1982                $order->update_status('failed', $message);
     1983                $order->save();
     1984                return $this->error_result($message);
     1985            }
     1986            $this->add_order_note($order, $authorized_transaction);
     1987            $order->update_status('on-hold');
     1988
     1989            // Update billing contact from bread transaction
     1990            $contact = array_merge(
     1991                    array(
     1992                        'lastName' => $authorized_transaction['billingContact']['name']['familyName'],
     1993                        'firstName' => $authorized_transaction['billingContact']['name']['givenName'],
     1994                        'address2' => '',
     1995                        'country' => $order->get_billing_country()
     1996                    ),
     1997                    $authorized_transaction['billingContact']
     1998            );
     1999
     2000            $order->set_address(array(
     2001                'first_name' => $contact['firstName'],
     2002                'last_name' => $contact['lastName'],
     2003                'address_1' => $contact['address']['address1'],
     2004                'address_2' => $contact['address']['address2'],
     2005                'city' => $contact['address']['locality'],
     2006                'state' => $contact['address']['region'],
     2007                'postcode' => $contact['address']['postalCode'],
     2008                'country' => $contact['address']['country'],
     2009                'email' => $contact['email'],
     2010                'phone' => $contact['phone']
     2011                    ), 'billing');
     2012
     2013            $this->updateOrderTxStatus($order, $authorized_transaction);
     2014           
     2015            //Attach orderId to the breadTranasction
     2016            $merchantOrderId = $order->get_id();
     2017            $updateOrderDetails = $this->bread_finance_api->updateTransactionMerchantOrderId($tx_id, $merchantOrderId);
     2018           
     2019            //Set Payment method as Bread
     2020            $payment_gateways = WC()->payment_gateways->payment_gateways();
     2021            $order->set_payment_method(self::WC_BREAD_GATEWAY_ID);
     2022
     2023           
     2024            $order->save();
    18932025        }
    18942026
     
    21062238        public function add_create_cart_options($actions) {
    21072239            $env = $this->load_bread_env();
    2108             if($env === 'classic') {
     2240            if ($env === 'bread_2') {
     2241                global $theorder;
     2242
     2243                if ($theorder->is_paid()) {
     2244                    return $actions;
     2245                }
     2246                $actions['create_bread_cart_link'] = __('Create Bread cart link', self::TEXT_DOMAIN);
     2247                $actions['email_bread_cart_link'] = __('Email Bread cart link', self::TEXT_DOMAIN);
     2248                return $actions;
     2249            } else {
    21092250                global $theorder;
    21102251
     
    21162257                $actions['text_bread_cart_link'] = __('Text Bread cart link', self::TEXT_DOMAIN);
    21172258                return $actions;
    2118             } else {
    2119                 return $actions;
    2120             }
    2121            
     2259            }
     2260        }
     2261       
     2262        /**
     2263         *
     2264         * @param array $qvars
     2265         * @return string
     2266         */
     2267        public function custom_bread_vars($qvars) {
     2268            $qvars[] = 'action';
     2269            return $qvars;
    21222270        }
    21232271       
     
    21302278            $this->bread_finance_utilities = Bread_Finance_Utilities::instance();
    21312279            $env = $this->load_bread_env();
    2132             if($env === 'classic') {
     2280            $bread_api = $this->load_bread_api_version();
     2281           
    21332282            if ($this->bread_finance_utilities->isAvataxEnabled()) {
    21342283                wc_avatax()->get_order_handler()->calculate_order_tax($order);
     
    21362285            // Recalculate totals, incl tax
    21372286            $order->calculate_totals(true);
     2287            if($env === 'bread_2') {
     2288                //Check if bread_cart_meta exists
     2289                //@todo. Fix this on 3.4. This hook gets called twice hence making the bread create cart action run twice
     2290                if(!$order->get_meta('bread_cart_link')) {
     2291                    $admin_carts_helper = Bread_Finance_Admin_Carts_Helper::instance();
     2292                    $opts = $admin_carts_helper->create_cart_opts_platform($order, $this->getPlatformMerchantId(), $this->getPlatformProgramId());
     2293                    $validate_cart_opts = $admin_carts_helper->validate_cart_opts_platform($opts);
     2294                    if (strlen($validate_cart_opts) > 0) {
     2295                        $errorMessage = "Error: Missing " . $validate_cart_opts . ". Please check order information and try again.";
     2296                        $order->add_order_note($errorMessage);
     2297                        $order->save();
     2298
     2299                        $errorInfo = array(
     2300                            'orderId' => strval($order->get_id()),
     2301                            'opts' => $opts,
     2302                            'missingInfo' => $validate_cart_opts,
     2303                        );
     2304                        $this->log_Bread_issue("debug", "[Plugin] Cannot create Bread cart. Missing information", $errorInfo);
     2305                        return;
     2306                    }
     2307                    $bread_cart = $this->parse_api_response($bread_api->createBreadCart($opts));
     2308                    $admin_carts_helper->update_platform_cart_custom_fields($order, $bread_cart, $bread_api);
     2309                }
     2310                return;
     2311            } else {
     2312                if ($this->bread_finance_utilities->isAvataxEnabled()) {
     2313                    wc_avatax()->get_order_handler()->calculate_order_tax($order);
     2314                }
     2315                // Recalculate totals, incl tax
     2316                $order->calculate_totals(true);
    21382317                $opts = $this->create_cart_opts($order);
    21392318                $validate = $this->validate_cart_opts($opts);
    2140                 if ( strlen( $validate ) > 0 ) {
     2319                if (strlen($validate) > 0) {
    21412320                    $errorMessage = "Error: Missing " . $validate . ". Please check order information and try again.";
    21422321                    $order->add_order_note($errorMessage);
     
    21632342         */
    21642343        public function email_bread_cart_link($order) {
    2165             $env = $this->load_bread_env();
    2166             if($env === 'classic') {
    2167                 $this->create_bread_cart_link($order);
    2168                 if ($order->meta_exists("bread_cart_link")) {
    2169                     $this->send_bread_cart_link($order, 'email');
    2170                 }
    2171             }
    2172        
    2173         }
    2174        
     2344            $this->create_bread_cart_link($order);
     2345            if ($order->meta_exists("bread_cart_link")) {
     2346                $this->send_bread_cart_link($order, 'email');
     2347            }
     2348        }
     2349
    21752350        /**
    21762351         *
     
    21902365       
    21912366        /**
     2367         * Get platform merchantId
     2368         *
     2369         * @param null
     2370         * @return string
     2371         * @since 3.3.0
     2372         */
     2373        public function getPlatformMerchantId() {
     2374            return $this->get_option($this->get_environment() . '_platform_merchantId');
     2375        }
     2376
     2377        /**
     2378         * Get platform programId
     2379         *
     2380         * @param null
     2381         * @return string
     2382         * @since 3.3.0
     2383         */
     2384        public function getPlatformProgramId() {
     2385            return $this->get_option($this->get_environment() . '_platform_programId');
     2386        }
     2387       
     2388        /**
    21922389         * Logs action
    21932390         *
  • bread-finance/tags/release-3.3.4/classes/class-bread-finance-options-checkout.php

    r2907371 r2916822  
    6464            //Get tax
    6565            $taxResponse = $this->getTax($shippingCost);
    66             $taxTotal = isset($taxResponse['tax']) ? $taxResponse['tax'] : 0;
     66            $taxTotal = $taxResponse['tax'];
    6767         
    6868            //Get items
     
    174174    public function getTax($shippingCost) {
    175175        $taxHelperResponse = $this->bread_finance_utilities->getTaxHelper($shippingCost);
    176         return (wc_tax_enabled()) ? array('tax' => $taxHelperResponse['tax']) : array();
     176        return (wc_tax_enabled()) ? array('tax' => $taxHelperResponse['tax']) : array('tax'=>0);
    177177    }
    178178
  • bread-finance/tags/release-3.3.4/classes/class-bread-finance-v2-api.php

    r2897614 r2916822  
    187187                }
    188188            }
    189 
     189           
    190190            $result = call_user_func($wp_remote, $api_url, array(
    191191                'method' => $method,
     
    195195                'body' => $wp_payload,
    196196            ));
     197           
     198            if (is_wp_error($response) || empty($result['body'])) {
     199                Bread_Finance_Logger::log(
     200                        'Error response: ' . print_r($result, true) . PHP_EOL . 'Failed request: ' . print_r(
     201                                [
     202                                    'api_url' => $api_url,
     203                                    'request' => $request
     204                                ],
     205                                true
     206                        )
     207                );
     208            }
    197209
    198210            $authorization_error_check = wp_remote_retrieve_response_code($result);
     
    202214                    'description' => 'Token validation error'
    203215                );
    204             }
    205         }
    206 
    207         if ( is_wp_error( $response ) || empty( $result['body'] ) ) {
    208             Bread_Finance_Logger::log(
    209                 'Error response: ' . print_r( $result, true ) . PHP_EOL . 'Failed request: ' . print_r(
    210                     [
    211                         'api_url'         => $api_url,
    212                         'request'         => $request
    213                     ],
    214                     true
    215                 )
    216             );
     216            }   
    217217        }
    218218
     
    224224        return $result;
    225225    }
     226   
     227    /**
     228     *
     229     * @param type $payload
     230     * @param type $order
     231     * @return type
     232     */
     233    public function createBreadCart($payload) {
     234        $token = get_option('bread_auth_token');
     235       
     236        //Load items into a JSON payload string
     237        $items = "";
     238        foreach($payload['items'] as $item) {
     239            $items .= '{';
     240            $items .= '"name":"' . $item['name'] . '",';
     241            $items .= '"quantity":' . $item['quantity'] . ',';
     242            $items .= '"sku":"' . $item['sku'] . '",';
     243            $items .= '"itemUrl":"' . $item['itemUrl'] . '",';
     244            $items .= '"imageUrl":"' . $item['imageUrl'] . '",';
     245            $items .= '"description":"' . $item['description'] . '",';
     246            $items .= '"unitPrice":{"currency":"' . $item['unitPrice']['currency'] . '","value":' . $item['unitPrice']['value'] . '},';
     247            $items .= '"shippingCost":{"currency":"' . $item['unitPrice']['currency'] . '","value":0},';
     248            $items .= '"unitTax":{"currency":"' . $item['unitTax']['currency'] . '","value":' . $item['unitTax']['value'] . '}';
     249            $items .= '},';
     250        }
     251        $items = rtrim($items,',');
     252       
     253        //Format timestamp
     254        $datetime = \DateTime::createFromFormat("Y-m-d H:i:s", date('Y-m-d H:i:s'));
     255        $timestamp = $datetime->format(\DateTime::RFC3339);
     256       
     257        $params = '{'
     258                . '"callbackUrl":"' . $payload['callbackURL'] . '",'
     259                . '"checkoutCompleteUrl":"' . $payload['checkoutCompleteUrl'] . '",'
     260                . '"checkoutErrorUrl":"' . $payload['checkoutErrorUrl'] . '",'
     261                . '"isHipaaRestricted":true,'
     262                . '"orderReference":"' . $payload['orderReference'] . '",'
     263                . '"merchantID":"' . $payload['merchantID'] . '",'
     264                . '"programID":"' . $payload['programID'] . '",'
     265                . '"disclosures":[{'
     266                    . '"name":"one-time",'
     267                    . '"acceptedAt":"' . $timestamp . '"'
     268                . '}],'
     269                . '"contact":{'
     270                    . '"name":{'
     271                        . '"givenName":"' . $payload['contact']['name']['givenName'] . '",'
     272                        . '"familyName":"' . $payload['contact']['name']['familyName'] . '"'
     273                    . '},'
     274                    . '"phone":"' . $payload['contact']['phone'] . '",'
     275                    . '"shippingAddress":{'
     276                        . '"address1":"' . $payload['contact']['shippingAddress']['address1'] . '",'
     277                        . '"address2":"' . $payload['contact']['shippingAddress']['address2'] . '",'
     278                        . '"locality":"' . $payload['contact']['shippingAddress']['locality'] . '",'
     279                        . '"postalCode":"' . $payload['contact']['shippingAddress']['postalCode'] . '",'
     280                        . '"region":"' . $payload['contact']['shippingAddress']['region'] . '",'
     281                        . '"country":"' . $payload['contact']['shippingAddress']['country'] . '"},'
     282                    . '"billingAddress":{'
     283                        . '"address1":"' . $payload['contact']['billingAddress']['address1'] . '",'
     284                        . '"address2":"' . $payload['contact']['billingAddress']['address2'] . '",'
     285                        . '"locality":"' . $payload['contact']['billingAddress']['locality'] . '",'
     286                        . '"postalCode":"' . $payload['contact']['billingAddress']['postalCode'] . '",'
     287                        . '"region":"' . $payload['contact']['billingAddress']['region'] . '",'
     288                        . '"country":"' . $payload['contact']['billingAddress']['country'] . '"},'
     289                    . '"email":"' . $payload['contact']['email'] . '"'
     290                . '},'
     291                . '"order":{'
     292                    . '"subTotal":{'
     293                        . '"currency":"' . $payload['order']['subTotal']['currency'] . '",'
     294                        . '"value":' . $payload['order']['subTotal']['value'] . ''
     295                    . '},'
     296                    . '"totalDiscounts":{'
     297                        . '"currency":"' . $payload['order']['totalDiscounts']['currency'] . '",'
     298                        . '"value":' . $payload['order']['totalDiscounts']['value'] . ''
     299                    . '},'
     300                    . '"totalPrice":{'
     301                        . '"currency":"' . $payload['order']['totalPrice']['currency'] . '",'
     302                        . '"value":' . $payload['order']['totalPrice']['value'] . ''
     303                    . '},'
     304                    . '"totalShipping":{'
     305                        . '"currency":"' . $payload['order']['totalShipping']['currency'] . '",'
     306                        . '"value":' . $payload['order']['totalShipping']['value'] . ''
     307                    . '},'
     308                    . '"totalTax":{'
     309                        . '"currency":"' . $payload['order']['totalTax']['currency'] . '",'
     310                        . '"value":' . $payload['order']['totalTax']['value'] . ''
     311                    . '},'
     312                    . '"discountCode":"' . $payload['order']['discountCode'] . '",'               
     313                    . '"items":[' . $items . ']'
     314                . '}'
     315                . '}';
     316        $response = $this->makeRequest('POST', $token, $this->api_base_url, "cart", $params, false);
     317        return $response;
     318    }
     319   
     320    public function expireBreadCart($cartId) {
     321        $token = get_option('bread_auth_token');
     322        $params = '{"cartdId":" ' . $cartId . '"}';
     323        $this->makeRequest('POST', $token, $this->api_base_url, "cart/$cartId/expire", $params, false);
     324    }
     325
     326    public function sendBreadCartLink($cartId, $payload) {
     327        $token = get_option('bread_auth_token');
     328        return $this->makeRequest('POST', $token, $this->api_base_url, "cart/$cartId/notify", $payload, false);
     329    }
     330   
    226331}
  • bread-finance/trunk/README.md

    r2907371 r2916822  
    44Requires at least: 4.9
    55Tested up to: 6.1.1
    6 Stable tag: 3.3.3
     6Stable tag: 3.3.4
    77Requires PHP: 5.6
    88WC requires at least: 3.0
     
    7272
    7373== Changelog ==
     74= 3.3.4
     75* Current release
     76* Bread Admin carts support
    7477
    7578= 3.3.3
    76 * Current release
    7779* Bug fix for discount codes applied with Avatax enabled
    7880
  • bread-finance/trunk/bread-finance.php

    r2907371 r2916822  
    66 * Author: Bread Pay
    77 * Author URI: https://payments.breadfinancial.com/
    8  * Version: 3.3.3
     8 * Version: 3.3.4
    99 * Text Domain: bread-finance
    1010 * Domain Path: /i18n/languages/
     
    2222
    2323//Require minimums and constants
    24 define('WC_BREAD_FINANCE_VERSION', '3.3.3');
     24define('WC_BREAD_FINANCE_VERSION', '3.3.4');
    2525define('WC_BREAD_FINANCE_MIN_PHP_VER', '5.6.0');
    2626define('WC_BREAD_FINANCE_MIN_WC_VER', '3.4.0');
     
    190190
    191191            //Classes
     192            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-admin-carts-helper.php';
    192193            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-utilities.php';
    193194            include_once WC_BREAD_FINANCE_PLUGIN_PATH . '/classes/class-bread-finance-form-fields.php';
  • bread-finance/trunk/classes/class-bread-finance-form-fields.php

    r2870595 r2916822  
    308308        );
    309309       
     310        $admin_carts = array(
     311            'admin_cart_settings' => array(
     312                'title' => esc_html__('Bread Admin Carts', $text_domain),
     313                'type' => 'title'
     314            ),
     315            'sandbox_platform_merchantId' => array(
     316                'title' => esc_html__('Sandbox Platform MerchantId', $text_domain),
     317                'type' => 'text',
     318                'desc_tip' => esc_html__('Your Bread Sandbox MerchantId. Contact your Bread representative')
     319            ),
     320            'sandbox_platform_programId' => array(
     321                'title' => esc_html__('Sandbox Platform ProgramId', $text_domain),
     322                'type' => 'text',
     323                'desc_tip' => esc_html__('Your Bread Sandbox ProgramId. Contact your Bread representative')
     324            ),
     325            'production_platform_merchantId' => array(
     326                'title' => esc_html__('Production Platform MerchantId', $text_domain),
     327                'type' => 'text',
     328                'desc_tip' => esc_html__('Your Bread Production MerchantId. Contact your Bread representative')
     329            ),
     330            'production_platform_programId' => array(
     331                'title' => esc_html__('Production Platform ProgramId', $text_domain),
     332                'type' => 'text',
     333                'desc_tip' => esc_html__('Your Bread Production ProgramId. Contact your Bread representative')
     334            ),
     335        );
     336
    310337        $advanced = array(
    311338            'advanced_settings_title' => array(
     
    318345        );
    319346
    320         $settings = array_merge($general, $environment, $platform_credentials, $classic_credentials, $button_appearance, $button_defaults, $advanced);
     347        $settings = array_merge($general, $environment, $platform_credentials, $classic_credentials, $button_appearance, $admin_carts, $button_defaults, $advanced);
    321348        return apply_filters('bread_finance_wc_gateway_settings', $settings);
    322349    }   
  • bread-finance/trunk/classes/class-bread-finance-gateway.php

    r2897614 r2916822  
    129129            add_action('woocommerce_order_action_create_bread_cart_link', array($this, 'create_bread_cart_link'));
    130130            add_action('woocommerce_order_action_email_bread_cart_link', array($this, 'email_bread_cart_link'));
     131           
     132            add_filter( 'query_vars', array($this, 'custom_bread_vars'));
    131133
    132134            //Enable Sentry logging
     
    12941296         */
    12951297        public function send_bread_cart_link($order, $method) {
     1298            $env = $this->load_bread_env();
    12961299            $bread_cart_id = $order->get_meta("bread_cart_id");
     1300            $bread_api = $this->load_bread_api_version();
    12971301            $endpoint = '/carts/' . $bread_cart_id . '/' . $method;
    12981302            $payload = ( $method === 'text' ) ? array("phone" => $order->get_billing_phone()) : array(
     
    13001304                "email" => $order->get_billing_email()
    13011305            );
    1302 
    1303             $bread_api = $this->load_bread_api_version();
    1304             $response = $bread_api->sendBreadCartLink($endpoint, $payload);
     1306            $response = null;
     1307            if ($env === 'bread_2') {
     1308                $response = $bread_api->sendBreadCartLink($bread_cart_id, array());
     1309            } else {
     1310                $response = $bread_api->sendBreadCartLink($endpoint, $payload);
     1311            }
    13051312            if (is_wp_error($response)) {
    13061313                $order->add_order_note("Error: " . json_encode($response));
     
    17991806                return;
    18001807            }
    1801 
     1808           
     1809            $env = $this->load_bread_env();
    18021810            $order_id = get_query_var('orderRef');
    1803             $tx_id = get_query_var('transactionId');
    1804 
    1805             if (strlen($tx_id) > 0 && strlen($order_id) > 0) {
    1806                 /* Complete URL Route */
    1807 
    1808                 $tx = $this->get_transaction($tx_id);
    1809                 $order = wc_get_order($order_id);
    1810                 $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
    1811 
    1812                 $response = $this->process_bread_cart_payment($order_id, $tx_id);
    1813                 $bread_api = $this->load_bread_api_version();
    1814                 $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
    1815                 $order->update_meta_data('bread_cart_link', 'Bread cart link has expired');
    1816 
    1817                 if ($response['result'] === 'error') {
    1818                     $order->update_status('failed');
    1819                     $order->add_order_note($response['message']);
     1811            $order = wc_get_order($order_id);
     1812            if($env === 'bread_2') {
     1813                $action = get_query_var('action');
     1814                //Do we have a checkout error?
     1815                if($action == 'checkout-error') {
     1816                    /* Error URL Route */
     1817                    wc_get_logger()->debug('Checkout error');
     1818                    $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
     1819                    $order = wc_get_order($order_id);
     1820                    $order->add_order_note($errorMessage);
    18201821                    $order->save();
    18211822
    1822                     $errorInfo = array(
    1823                         'response' => $response,
    1824                         'txId' => $tx_id,
    1825                         'orderId' => $order_id
    1826                     );
    1827 
    1828                     $this->log_Bread_issue("error", "[Plugin] " . $response['message'], $errorInfo);
    1829                 }
    1830 
    1831                 wp_redirect($order->get_checkout_order_received_url());
    1832                 ob_flush();
    1833                 exit;
    1834             } else if (strlen($order_id) > 0) {
    1835                 /* Error URL Route */
    1836 
    1837                 $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
    1838                 $order = wc_get_order($order_id);
    1839                 $order->add_order_note($errorMessage);
    1840                 $order->save();
    1841 
    1842                 $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
    1843 
    1844                 wp_redirect(home_url());
    1845                 ob_flush();
    1846                 exit;
    1847             }
     1823                    $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
     1824
     1825                    wp_redirect(home_url());
     1826                    ob_flush();
     1827                    exit;
     1828                }
     1829               
     1830                //Do we have a checkout complete
     1831                if($action == 'checkout-complete') {
     1832                    wc_get_logger()->debug('Checkout complete');
     1833                    $message = 'Note: Customer checkout action complete';
     1834                    $order = wc_get_order($order_id);
     1835                    $order->add_order_note($message);
     1836                    $order->save();
     1837                    wp_redirect($order->get_checkout_order_received_url());
     1838                    ob_flush();
     1839                    exit;
     1840                }
     1841               
     1842                //Do we have a success checkout callback
     1843                if($action == 'callback') {
     1844                    wc_get_logger()->debug('Success callback');
     1845                    $tx_id = null;
     1846                    $data = json_decode(file_get_contents('php://input'), true);
     1847                    if(isset($data['transactionId'])) {
     1848                        $tx_id = trim($data['transactionId']);
     1849                    }
     1850                    $tx = $this->get_transaction($tx_id);
     1851                    $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
     1852                    $response = $this->process_bread_platform_cart_payment($order_id, $tx_id);
     1853                    $bread_api = $this->load_bread_api_version();
     1854                    $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
     1855                    wp_redirect($order->get_checkout_order_received_url());
     1856                    ob_flush();
     1857                    exit;
     1858                }
     1859            } else {
     1860                $tx_id = get_query_var('transactionId');
     1861                if (strlen($tx_id) > 0 && strlen($order_id) > 0) {
     1862                    /* Complete URL Route */
     1863
     1864                    $tx = $this->get_transaction($tx_id);
     1865                   
     1866                    $this->bread_finance_utilities->validateCalculatedTotals($order, $tx);
     1867
     1868                    $response = $this->process_bread_cart_payment($order_id, $tx_id);
     1869                    $bread_api = $this->load_bread_api_version();
     1870                    $bread_api->expireBreadCart($order->get_meta("bread_cart_id"));
     1871                    $order->update_meta_data('bread_cart_link', 'Bread cart link has expired');
     1872
     1873                    if ($response['result'] === 'error') {
     1874                        $order->update_status('failed');
     1875                        $order->add_order_note($response['message']);
     1876                        $order->save();
     1877
     1878                        $errorInfo = array(
     1879                            'response' => $response,
     1880                            'txId' => $tx_id,
     1881                            'orderId' => $order_id
     1882                        );
     1883
     1884                        $this->log_Bread_issue("error", "[Plugin] " . $response['message'], $errorInfo);
     1885                    }
     1886
     1887                    wp_redirect($order->get_checkout_order_received_url());
     1888                    ob_flush();
     1889                    exit;
     1890                } else if (strlen($order_id) > 0) {
     1891                    /* Error URL Route */
     1892
     1893                    $errorMessage = 'Note: Customer was not approved for financing or attempted to use an expired Bread cart link';
     1894                    $order = wc_get_order($order_id);
     1895                    $order->add_order_note($errorMessage);
     1896                    $order->save();
     1897
     1898                    $this->log_Bread_issue("warning", "[Plugin] " . $errorMessage, array('orderId' => $order_id));
     1899
     1900                    wp_redirect(home_url());
     1901                    ob_flush();
     1902                    exit;
     1903                }
     1904            }
    18481905        }
    18491906
     
    18551912        public function process_bread_cart_payment($order_id, $tx_id) {
    18561913            $order = wc_get_order($order_id);
    1857 
    18581914            $tx = $this->get_transaction($tx_id);
    18591915            if ($this->has_error($tx)) {
     
    18911947                'result' => 'success',
    18921948            );
     1949        }
     1950       
     1951        /**
     1952         * Process bread platform cart payment
     1953         */
     1954        public function process_bread_platform_cart_payment($order_id, $tx_id) {
     1955            $order = wc_get_order($order_id);
     1956            $env = $this->load_bread_env();
     1957            $transaction = $this->get_transaction($tx_id);
     1958            if ($this->has_error($transaction)) {
     1959                return array(
     1960                    'result' => 'error',
     1961                    'message' => 'Error retrieving transaction',
     1962                    'tx' => $transaction,
     1963                );
     1964            }
     1965            $order->add_meta_data('bread_tx_id', $transaction['id']);
     1966            $order->save();
     1967           
     1968            $this->bread_finance_api = Bread_Finance_V2_Api::instance();
     1969           
     1970            $authorized_transaction = $this->parse_api_response($this->bread_finance_api->authorizeTransaction($tx_id, $transaction['totalAmount']['value'], $transaction['totalAmount']['currency'], $order_id));
     1971            $this->log(
     1972                    __FUNCTION__,
     1973                    'Authorisation request details. #' . json_encode($authorized_transaction)
     1974            );
     1975            if ($this->has_error($authorized_transaction)) {
     1976                return $this->error_result($authorized_transaction);
     1977            }
     1978
     1979            // Validate Transaction Status / set order status
     1980            if (strtoupper($authorized_transaction['status']) !== 'AUTHORIZED') {
     1981                $message = esc_html__('Transaction status is not currently AUTHORIZED. Order Status: ' . $authorized_transaction['status'], self::TEXT_DOMAIN);
     1982                $order->update_status('failed', $message);
     1983                $order->save();
     1984                return $this->error_result($message);
     1985            }
     1986            $this->add_order_note($order, $authorized_transaction);
     1987            $order->update_status('on-hold');
     1988
     1989            // Update billing contact from bread transaction
     1990            $contact = array_merge(
     1991                    array(
     1992                        'lastName' => $authorized_transaction['billingContact']['name']['familyName'],
     1993                        'firstName' => $authorized_transaction['billingContact']['name']['givenName'],
     1994                        'address2' => '',
     1995                        'country' => $order->get_billing_country()
     1996                    ),
     1997                    $authorized_transaction['billingContact']
     1998            );
     1999
     2000            $order->set_address(array(
     2001                'first_name' => $contact['firstName'],
     2002                'last_name' => $contact['lastName'],
     2003                'address_1' => $contact['address']['address1'],
     2004                'address_2' => $contact['address']['address2'],
     2005                'city' => $contact['address']['locality'],
     2006                'state' => $contact['address']['region'],
     2007                'postcode' => $contact['address']['postalCode'],
     2008                'country' => $contact['address']['country'],
     2009                'email' => $contact['email'],
     2010                'phone' => $contact['phone']
     2011                    ), 'billing');
     2012
     2013            $this->updateOrderTxStatus($order, $authorized_transaction);
     2014           
     2015            //Attach orderId to the breadTranasction
     2016            $merchantOrderId = $order->get_id();
     2017            $updateOrderDetails = $this->bread_finance_api->updateTransactionMerchantOrderId($tx_id, $merchantOrderId);
     2018           
     2019            //Set Payment method as Bread
     2020            $payment_gateways = WC()->payment_gateways->payment_gateways();
     2021            $order->set_payment_method(self::WC_BREAD_GATEWAY_ID);
     2022
     2023           
     2024            $order->save();
    18932025        }
    18942026
     
    21062238        public function add_create_cart_options($actions) {
    21072239            $env = $this->load_bread_env();
    2108             if($env === 'classic') {
     2240            if ($env === 'bread_2') {
     2241                global $theorder;
     2242
     2243                if ($theorder->is_paid()) {
     2244                    return $actions;
     2245                }
     2246                $actions['create_bread_cart_link'] = __('Create Bread cart link', self::TEXT_DOMAIN);
     2247                $actions['email_bread_cart_link'] = __('Email Bread cart link', self::TEXT_DOMAIN);
     2248                return $actions;
     2249            } else {
    21092250                global $theorder;
    21102251
     
    21162257                $actions['text_bread_cart_link'] = __('Text Bread cart link', self::TEXT_DOMAIN);
    21172258                return $actions;
    2118             } else {
    2119                 return $actions;
    2120             }
    2121            
     2259            }
     2260        }
     2261       
     2262        /**
     2263         *
     2264         * @param array $qvars
     2265         * @return string
     2266         */
     2267        public function custom_bread_vars($qvars) {
     2268            $qvars[] = 'action';
     2269            return $qvars;
    21222270        }
    21232271       
     
    21302278            $this->bread_finance_utilities = Bread_Finance_Utilities::instance();
    21312279            $env = $this->load_bread_env();
    2132             if($env === 'classic') {
     2280            $bread_api = $this->load_bread_api_version();
     2281           
    21332282            if ($this->bread_finance_utilities->isAvataxEnabled()) {
    21342283                wc_avatax()->get_order_handler()->calculate_order_tax($order);
     
    21362285            // Recalculate totals, incl tax
    21372286            $order->calculate_totals(true);
     2287            if($env === 'bread_2') {
     2288                //Check if bread_cart_meta exists
     2289                //@todo. Fix this on 3.4. This hook gets called twice hence making the bread create cart action run twice
     2290                if(!$order->get_meta('bread_cart_link')) {
     2291                    $admin_carts_helper = Bread_Finance_Admin_Carts_Helper::instance();
     2292                    $opts = $admin_carts_helper->create_cart_opts_platform($order, $this->getPlatformMerchantId(), $this->getPlatformProgramId());
     2293                    $validate_cart_opts = $admin_carts_helper->validate_cart_opts_platform($opts);
     2294                    if (strlen($validate_cart_opts) > 0) {
     2295                        $errorMessage = "Error: Missing " . $validate_cart_opts . ". Please check order information and try again.";
     2296                        $order->add_order_note($errorMessage);
     2297                        $order->save();
     2298
     2299                        $errorInfo = array(
     2300                            'orderId' => strval($order->get_id()),
     2301                            'opts' => $opts,
     2302                            'missingInfo' => $validate_cart_opts,
     2303                        );
     2304                        $this->log_Bread_issue("debug", "[Plugin] Cannot create Bread cart. Missing information", $errorInfo);
     2305                        return;
     2306                    }
     2307                    $bread_cart = $this->parse_api_response($bread_api->createBreadCart($opts));
     2308                    $admin_carts_helper->update_platform_cart_custom_fields($order, $bread_cart, $bread_api);
     2309                }
     2310                return;
     2311            } else {
     2312                if ($this->bread_finance_utilities->isAvataxEnabled()) {
     2313                    wc_avatax()->get_order_handler()->calculate_order_tax($order);
     2314                }
     2315                // Recalculate totals, incl tax
     2316                $order->calculate_totals(true);
    21382317                $opts = $this->create_cart_opts($order);
    21392318                $validate = $this->validate_cart_opts($opts);
    2140                 if ( strlen( $validate ) > 0 ) {
     2319                if (strlen($validate) > 0) {
    21412320                    $errorMessage = "Error: Missing " . $validate . ". Please check order information and try again.";
    21422321                    $order->add_order_note($errorMessage);
     
    21632342         */
    21642343        public function email_bread_cart_link($order) {
    2165             $env = $this->load_bread_env();
    2166             if($env === 'classic') {
    2167                 $this->create_bread_cart_link($order);
    2168                 if ($order->meta_exists("bread_cart_link")) {
    2169                     $this->send_bread_cart_link($order, 'email');
    2170                 }
    2171             }
    2172        
    2173         }
    2174        
     2344            $this->create_bread_cart_link($order);
     2345            if ($order->meta_exists("bread_cart_link")) {
     2346                $this->send_bread_cart_link($order, 'email');
     2347            }
     2348        }
     2349
    21752350        /**
    21762351         *
     
    21902365       
    21912366        /**
     2367         * Get platform merchantId
     2368         *
     2369         * @param null
     2370         * @return string
     2371         * @since 3.3.0
     2372         */
     2373        public function getPlatformMerchantId() {
     2374            return $this->get_option($this->get_environment() . '_platform_merchantId');
     2375        }
     2376
     2377        /**
     2378         * Get platform programId
     2379         *
     2380         * @param null
     2381         * @return string
     2382         * @since 3.3.0
     2383         */
     2384        public function getPlatformProgramId() {
     2385            return $this->get_option($this->get_environment() . '_platform_programId');
     2386        }
     2387       
     2388        /**
    21922389         * Logs action
    21932390         *
  • bread-finance/trunk/classes/class-bread-finance-options-checkout.php

    r2907371 r2916822  
    6464            //Get tax
    6565            $taxResponse = $this->getTax($shippingCost);
    66             $taxTotal = isset($taxResponse['tax']) ? $taxResponse['tax'] : 0;
     66            $taxTotal = $taxResponse['tax'];
    6767         
    6868            //Get items
     
    174174    public function getTax($shippingCost) {
    175175        $taxHelperResponse = $this->bread_finance_utilities->getTaxHelper($shippingCost);
    176         return (wc_tax_enabled()) ? array('tax' => $taxHelperResponse['tax']) : array();
     176        return (wc_tax_enabled()) ? array('tax' => $taxHelperResponse['tax']) : array('tax'=>0);
    177177    }
    178178
  • bread-finance/trunk/classes/class-bread-finance-v2-api.php

    r2897614 r2916822  
    187187                }
    188188            }
    189 
     189           
    190190            $result = call_user_func($wp_remote, $api_url, array(
    191191                'method' => $method,
     
    195195                'body' => $wp_payload,
    196196            ));
     197           
     198            if (is_wp_error($response) || empty($result['body'])) {
     199                Bread_Finance_Logger::log(
     200                        'Error response: ' . print_r($result, true) . PHP_EOL . 'Failed request: ' . print_r(
     201                                [
     202                                    'api_url' => $api_url,
     203                                    'request' => $request
     204                                ],
     205                                true
     206                        )
     207                );
     208            }
    197209
    198210            $authorization_error_check = wp_remote_retrieve_response_code($result);
     
    202214                    'description' => 'Token validation error'
    203215                );
    204             }
    205         }
    206 
    207         if ( is_wp_error( $response ) || empty( $result['body'] ) ) {
    208             Bread_Finance_Logger::log(
    209                 'Error response: ' . print_r( $result, true ) . PHP_EOL . 'Failed request: ' . print_r(
    210                     [
    211                         'api_url'         => $api_url,
    212                         'request'         => $request
    213                     ],
    214                     true
    215                 )
    216             );
     216            }   
    217217        }
    218218
     
    224224        return $result;
    225225    }
     226   
     227    /**
     228     *
     229     * @param type $payload
     230     * @param type $order
     231     * @return type
     232     */
     233    public function createBreadCart($payload) {
     234        $token = get_option('bread_auth_token');
     235       
     236        //Load items into a JSON payload string
     237        $items = "";
     238        foreach($payload['items'] as $item) {
     239            $items .= '{';
     240            $items .= '"name":"' . $item['name'] . '",';
     241            $items .= '"quantity":' . $item['quantity'] . ',';
     242            $items .= '"sku":"' . $item['sku'] . '",';
     243            $items .= '"itemUrl":"' . $item['itemUrl'] . '",';
     244            $items .= '"imageUrl":"' . $item['imageUrl'] . '",';
     245            $items .= '"description":"' . $item['description'] . '",';
     246            $items .= '"unitPrice":{"currency":"' . $item['unitPrice']['currency'] . '","value":' . $item['unitPrice']['value'] . '},';
     247            $items .= '"shippingCost":{"currency":"' . $item['unitPrice']['currency'] . '","value":0},';
     248            $items .= '"unitTax":{"currency":"' . $item['unitTax']['currency'] . '","value":' . $item['unitTax']['value'] . '}';
     249            $items .= '},';
     250        }
     251        $items = rtrim($items,',');
     252       
     253        //Format timestamp
     254        $datetime = \DateTime::createFromFormat("Y-m-d H:i:s", date('Y-m-d H:i:s'));
     255        $timestamp = $datetime->format(\DateTime::RFC3339);
     256       
     257        $params = '{'
     258                . '"callbackUrl":"' . $payload['callbackURL'] . '",'
     259                . '"checkoutCompleteUrl":"' . $payload['checkoutCompleteUrl'] . '",'
     260                . '"checkoutErrorUrl":"' . $payload['checkoutErrorUrl'] . '",'
     261                . '"isHipaaRestricted":true,'
     262                . '"orderReference":"' . $payload['orderReference'] . '",'
     263                . '"merchantID":"' . $payload['merchantID'] . '",'
     264                . '"programID":"' . $payload['programID'] . '",'
     265                . '"disclosures":[{'
     266                    . '"name":"one-time",'
     267                    . '"acceptedAt":"' . $timestamp . '"'
     268                . '}],'
     269                . '"contact":{'
     270                    . '"name":{'
     271                        . '"givenName":"' . $payload['contact']['name']['givenName'] . '",'
     272                        . '"familyName":"' . $payload['contact']['name']['familyName'] . '"'
     273                    . '},'
     274                    . '"phone":"' . $payload['contact']['phone'] . '",'
     275                    . '"shippingAddress":{'
     276                        . '"address1":"' . $payload['contact']['shippingAddress']['address1'] . '",'
     277                        . '"address2":"' . $payload['contact']['shippingAddress']['address2'] . '",'
     278                        . '"locality":"' . $payload['contact']['shippingAddress']['locality'] . '",'
     279                        . '"postalCode":"' . $payload['contact']['shippingAddress']['postalCode'] . '",'
     280                        . '"region":"' . $payload['contact']['shippingAddress']['region'] . '",'
     281                        . '"country":"' . $payload['contact']['shippingAddress']['country'] . '"},'
     282                    . '"billingAddress":{'
     283                        . '"address1":"' . $payload['contact']['billingAddress']['address1'] . '",'
     284                        . '"address2":"' . $payload['contact']['billingAddress']['address2'] . '",'
     285                        . '"locality":"' . $payload['contact']['billingAddress']['locality'] . '",'
     286                        . '"postalCode":"' . $payload['contact']['billingAddress']['postalCode'] . '",'
     287                        . '"region":"' . $payload['contact']['billingAddress']['region'] . '",'
     288                        . '"country":"' . $payload['contact']['billingAddress']['country'] . '"},'
     289                    . '"email":"' . $payload['contact']['email'] . '"'
     290                . '},'
     291                . '"order":{'
     292                    . '"subTotal":{'
     293                        . '"currency":"' . $payload['order']['subTotal']['currency'] . '",'
     294                        . '"value":' . $payload['order']['subTotal']['value'] . ''
     295                    . '},'
     296                    . '"totalDiscounts":{'
     297                        . '"currency":"' . $payload['order']['totalDiscounts']['currency'] . '",'
     298                        . '"value":' . $payload['order']['totalDiscounts']['value'] . ''
     299                    . '},'
     300                    . '"totalPrice":{'
     301                        . '"currency":"' . $payload['order']['totalPrice']['currency'] . '",'
     302                        . '"value":' . $payload['order']['totalPrice']['value'] . ''
     303                    . '},'
     304                    . '"totalShipping":{'
     305                        . '"currency":"' . $payload['order']['totalShipping']['currency'] . '",'
     306                        . '"value":' . $payload['order']['totalShipping']['value'] . ''
     307                    . '},'
     308                    . '"totalTax":{'
     309                        . '"currency":"' . $payload['order']['totalTax']['currency'] . '",'
     310                        . '"value":' . $payload['order']['totalTax']['value'] . ''
     311                    . '},'
     312                    . '"discountCode":"' . $payload['order']['discountCode'] . '",'               
     313                    . '"items":[' . $items . ']'
     314                . '}'
     315                . '}';
     316        $response = $this->makeRequest('POST', $token, $this->api_base_url, "cart", $params, false);
     317        return $response;
     318    }
     319   
     320    public function expireBreadCart($cartId) {
     321        $token = get_option('bread_auth_token');
     322        $params = '{"cartdId":" ' . $cartId . '"}';
     323        $this->makeRequest('POST', $token, $this->api_base_url, "cart/$cartId/expire", $params, false);
     324    }
     325
     326    public function sendBreadCartLink($cartId, $payload) {
     327        $token = get_option('bread_auth_token');
     328        return $this->makeRequest('POST', $token, $this->api_base_url, "cart/$cartId/notify", $payload, false);
     329    }
     330   
    226331}
Note: See TracChangeset for help on using the changeset viewer.