function cw_fedex_get_meter_number($userinfo, &$error)
{
    global $config;
    // FedEx host
    $fedex_host = $config['shipping_fedex']['is_test_mode'] == 'Y' ? 'gatewaybeta.fedex.com/GatewayDC' : 'gateway.fedex.com/GatewayDC';
    $xml_contact_fields = array();
    $xml_address_fields = array();
    $userinfo = array_map('htmlspecialchars', $userinfo);
    if (!empty($userinfo['company_name'])) {
        $xml_contact_fields[] = "<CompanyName>{$userinfo['company_name']}</CompanyName>";
    }
    if (!empty($userinfo['pager_number'])) {
        $xml_contact_fields[] = "<PagerNumber>{$userinfo['pager_number']}</PagerNumber>";
    }
    if (!empty($userinfo['fax_number'])) {
        $xml_contact_fields[] = "<FaxNumber>{$userinfo['fax_number']}</FaxNumber>";
    }
    if (!empty($userinfo['email'])) {
        $xml_contact_fields[] = "<E-MailAddress>{$userinfo['email']}</E-MailAddress>";
    }
    if (!empty($userinfo['address_2'])) {
        $xml_address_fields[] = "<Line2>{$userinfo['address_2']}</Line2>";
    }
    $xml_contact_fields_str = implode("\n\t\t", $xml_contact_fields);
    $xml_address_fields_str = implode("\n\t\t", $xml_address_fields);
    if (!empty($userinfo['state']) && in_array($userinfo['country'], array("US", "CA", "PR"))) {
        $state = "<StateOrProvinceCode>{$userinfo['state']}</StateOrProvinceCode>";
    } else {
        $state = '';
    }
    $xml_query = <<<OUT
<?xml version="1.0" encoding="UTF-8" ?>
<FDXSubscriptionRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXSubscriptionRequest.xsd">
    <RequestHeader>
        <CustomerTransactionIdentifier>1</CustomerTransactionIdentifier>
        <AccountNumber>{$config['shipping_fedex']['account_number']}</AccountNumber>
    </RequestHeader>
    <Contact>
        <PersonName>{$userinfo['person_name']}</PersonName>
        <PhoneNumber>{$userinfo['phone_number']}</PhoneNumber>
{$xml_contact_fields_str}
    </Contact>
    <Address>
        <Line1>{$userinfo['address_1']}</Line1>
{$xml_address_fields_str}
        <City>{$userinfo['city']}</City>
        {$state}
        <PostalCode>{$userinfo['zipcode']}</PostalCode>
        <CountryCode>{$userinfo['country']}</CountryCode>
    </Address>
</FDXSubscriptionRequest>
OUT;
    $data = explode("\n", $xml_query);
    $host = "https://" . $fedex_host;
    list($header, $result) = cw_https_request('POST', $host, $data, '', '', 'text/xml');
    $parse_error = false;
    $options = array('XML_OPTION_CASE_FOLDING' => 1, 'XML_OPTION_TARGET_ENCODING' => 'UTF-8');
    $parsed = cw_xml_parse($result, $parse_error, $options);
    $error = array();
    if (empty($parsed)) {
        $error['msg'] = cw_get_langvar_by_name("msg_fedex_meter_number_incorrect_data_err");
        return false;
    }
    $type = key($parsed);
    $meter_number = cw_array_path($parsed, $type . "/METERNUMBER/0/#");
    if (empty($meter_number)) {
        $error['code'] = cw_array_path($parsed, $type . "/ERROR/CODE/0/#");
        $error['msg'] = cw_array_path($parsed, $type . "/ERROR/MESSAGE/0/#");
        if (empty($error['code'])) {
            $error['code'] = cw_array_path($parsed, "ERROR/CODE/0/#");
            $error['msg'] = cw_array_path($parsed, "ERROR/MESSAGE/0/#");
        }
        if (!empty($error['code'])) {
            $error['msg'] = "FedEx addon error: [{$error['code']}] {$error['msg']}";
        } else {
            $error['msg'] = cw_get_langvar_by_name("msg_fedex_meter_number_empty_err");
        }
        return false;
    }
    return $meter_number;
}
function cw_ups_process($request, $tool)
{
    $post = explode("\n", $request);
    list($a, $result) = cw_https_request('POST', 'https://www.ups.com:443/ups.app/xml/' . $tool, $post, '', '', 'text/xml');
    /*
    header('Content-type: text/xml');
    echo $result;
    die;
    */
    $parse_error = false;
    $options = array('XML_OPTION_CASE_FOLDING' => 1, 'XML_OPTION_TARGET_ENCODING' => 'ISO-8859-1');
    return cw_xml_parse($result, $parse_error, $options);
}
Ejemplo n.º 3
0
 $skey = $request_prepared["custom"];
 $payment_data = cw_call('cw_payment_get_data', array($skey));
 $bill_output['sess_id'] = $payment_data['session_id'];
 $cur = $config['paypal']['pp_currency'];
 $testmode = $config['paypal']['test_mode'];
 $pp_host = $testmode == 'N' ? "www.paypal.com" : "www.sandbox.paypal.com";
 $payment_status = $request_prepared['payment_status'];
 $https_success = true;
 $https_msg = "";
 if ($config['paypal_solution'] != 'uk') {
     # do PayPal (IPN) background request...
     $post = array();
     foreach ($_POST as $key => $val) {
         $post[] = "{$key}=" . stripslashes($val);
     }
     list($a, $result) = cw_https_request("POST", "https://{$pp_host}:443/cgi-bin/webscr?cmd=_notify-validate", $post);
     $is_verified = preg_match("/VERIFIED/i", $result);
     if (empty($a)) {
         // HTTPS client error
         $https_success = false;
         $https_msg = $result;
     }
 } else {
     $is_verified = true;
 }
 cw_call('cw_payment_put_data', array($skey, array('state' => 'END', 'status' => $payment_status, 'is_callback' => true, 'is_verified' => $is_verified)));
 if (!$https_success) {
     $bill_message = "Queued: HTTPS client error ({$https_msg}).";
     $bill_output["code"] = 3;
 } elseif (!$is_verified) {
     $bill_output["code"] = 2;
function cw_payment_paypal_adaptive_run_processor($params, $return)
{
    if ($params['payment_data']['processor'] == 'paypal_adaptive') {
        extract($params);
        global $config, $current_location, $top_message;
        $cart =& cw_session_register('cart');
        $skey = cw_call('cw_payment_start');
        $secure_oid =& cw_session_register('secure_oid');
        $memo = implode(',', $params['doc_ids']) . "!" . rand(10, 99);
        $debug = 0;
        $u_phone = preg_replace('![^\\d]+!', '', $params['userinfo']['current_address']['phone']);
        cw_load('http');
        # why so?..
        $pp_url = "https://svcs." . ($config['paypal_adaptive']['test_mode'] == "Y" ? "sandbox." : "") . "paypal.com/AdaptivePayments";
        $post_headers = array("X-PAYPAL-SECURITY-USERID" => $config['paypal_adaptive']['api_access'], "X-PAYPAL-SECURITY-PASSWORD" => $config['paypal_adaptive']['api_password'], "X-PAYPAL-SECURITY-SIGNATURE" => $config['paypal_adaptive']['api_signature'], "X-PAYPAL-DEVICE-IPADDRESS" => $_SERVER["REMOTE_ADDR"], "X-PAYPAL-REQUEST-DATA-FORMAT" => "JSON", "X-PAYPAL-RESPONSE-DATA-FORMAT" => "JSON", "X-PAYPAL-APPLICATION-ID" => "APP-54K5660378319012U");
        $receivers = array();
        $recs = cw_seller_get_payment_shares($cart);
        $amount2admin = $recs[0];
        unset($recs[0]);
        # default amount to admin
        $pp_type = $config['paypal_adaptive']['pp_method'] == "C";
        # true - chain/C; false - parallel/P
        $setdetails = array();
        if ($recs) {
            foreach ($recs as $customer_id => $amount) {
                if ($amount > 0) {
                    $custom = cw_user_get_custom_fields($customer_id, 0, '', 'field');
                    $email = $custom["pp_account"];
                    # // rename??
                    if ($email) {
                        $receivers[] = array("primary" => false, "amount" => $amount, "email" => $email, "invoiceId" => $memo);
                        /*
                                                list($ship,$items,$products) = cw_ppadapt_products($customer_id,$amount,$products);
                                                if(empty($items))
                                                $setdetails[] = array(
                                                        "receiver" => array(
                                                                "email" => $email
                                                        ),
                                                        "invoiceData" => array(
                                                                "totalTax" => 0,
                                                                "totalShipping" => $ship,
                                                                "item" => $items,
                                                        ),
                                                );
                        */
                    }
                    if ($pp_type || !$email) {
                        $amount2admin += $amount;
                    }
                }
            }
        }
        if ($amount2admin > 0) {
            $receivers[] = array("primary" => $pp_type && !empty($receivers), "amount" => $amount2admin, "invoiceId" => $memo, "email" => $config['paypal_adaptive']['email_acc']);
            /*
                            list($ship,$items,$products) = cw_ppadapt_products($customer_id,$amount,$products);
                            if(empty($items))
                            $setdetails[] = array(
                                    "receiver" => array(
                                            "email" => $email
                                    ),
                                    "invoiceData" => array(
                                            "totalTax" => 0,
                                            "totalShipping" => $ship,
                                            "item" => $items,
                                    ),
                            );
            */
        }
        $pp_cancel_url = $current_location . '/index.php?target=cart';
        $post = array("actionType" => $pp_type ? "PAY_PRIMARY" : "PAY", "currencyCode" => $config['paypal_adaptive']['currency'], "feesPayer" => $config['paypal_adaptive']['fee_payer'], "receiverList" => array("receiver" => $receivers), "ipnNotificationUrl" => $current_location . '/index.php?target=paypal_adaptive', "memo" => $memo, "trackingId" => $skey, "returnUrl" => $current_location . '/index.php?target=order-message&doc_ids=' . implode(',', $params['doc_ids']), "cancelUrl" => $pp_cancel_url, "requestEnvelope" => array("errorLanguage" => "en_US", "detailLevel" => "ReturnAll"));
        list($headers, $response) = cw_https_request("POST", $pp_url . "/Pay", array(json_encode($post)), "", "", "application/json", "", "", "", $post_headers);
        if ($debug) {
            print "<pre>";
            print_r(array($recs, $pp_url, $post_headers, $post, json_encode($post), $headers, $response));
        }
        if ($headers == "0") {
            $result = array('success' => false, 'error' => array('ShortMessage' => $response));
        } else {
            $ret = json_decode($response, 1);
            if ($ret["error"]) {
                $err = array();
                foreach ($ret["error"] as $e) {
                    $err[] = $e["severity"] . ": " . $e["message"];
                }
                $result = array('success' => false, 'error' => array('ShortMessage' => join(";", $err)));
            } elseif ($ret["payKey"]) {
                # It's ok. Now let's add options...
                $post = array("payKey" => $ret["payKey"], "requestEnvelope" => array("errorLanguage" => "en_US", "detailLevel" => "ReturnAll"));
                if (!empty($setdetails)) {
                    # should not fire...
                    $post["receiverOptions"] = $setdetails;
                }
                $post["senderOptions"] = array("addressOverride" => true, "shippingAddress" => array());
                foreach (array("addresseeName" => $params['userinfo']['current_address']['firstname'] . " " . $params['userinfo']['current_address']['lastname'], "street1" => $params['userinfo']['current_address']['address'], "street2" => $params['userinfo']['current_address']['address_2'], "city" => $params['userinfo']['current_address']['city'], "state" => $params['userinfo']['current_address']['country'] == 'US' || $params['userinfo']['current_address']['country'] == 'CA' || $params['userinfo']['current_address']['state'] != '' ? $params['userinfo']['current_address']['state'] : 'Other', "zip" => $params['userinfo']['current_address']['zipcode'], "country" => $params['userinfo']['current_address']['country']) as $k => $v) {
                    # filter empty values
                    if ($v) {
                        $post["senderOptions"]["shippingAddress"][$k] = $v;
                    }
                }
                list($headers, $response) = cw_https_request("POST", $pp_url . "/SetPaymentOptions", array(json_encode($post)), "", "", "application/json", "", "", "", $post_headers);
                if ($debug) {
                    print "<hr><hr>";
                    print_r(array($post, json_decode($response, 1), $headers));
                }
                $result = array('success' => true, 'payKey' => $ret["payKey"]);
            }
        }
        $pp_customer_url = "https://www." . ($config['paypal_adaptive']['test_mode'] == "Y" ? "sandbox." : "") . "paypal.com";
        if ($debug) {
            print_r(array($ret, $result));
            if ($result['success'] && !empty($result['payKey'])) {
                die("<h1>" . $pp_customer_url . '/webscr?cmd=_ap-payment&paykey=' . $result['payKey'] . "</h1>");
            }
            die($result['error']['ShortMessage']);
        }
        if ($result['success'] && !empty($result['payKey'])) {
            cw_header_location($pp_customer_url . '/webscr?cmd=_ap-payment&paykey=' . $result['payKey']);
        }
        $top_message = array('type' => 'E', 'content' => $result['error']['ShortMessage']);
        cw_header_location($pp_cancel_url);
    }
    return $return;
}
</DeliveryConfirmationV3.0Request>
EOT;
# Delete previous existing test labels
cw_rm_dir_files($app_main_dir . "/var/tmp/usps_test_labels/");
$labels = 0;
$error = array();
$_log = '';
foreach ($usps_methods as $method => $data) {
    foreach ($data['xml_requests'] as $xml_id => $xml_data) {
        $_log .= "************************************************************************************************\n\n";
        $_log .= "[{$method}]\n\n";
        $_log .= "[REQUEST {$xml_id}]:\n\n" . $xml_data['xml_request'] . "\n\n";
        $request = $server . "?API=" . $data['api'] . "&XML=" . urlencode($xml_data['xml_request']);
        $_log .= "[SEND REQUEST TO URL]:\n\n" . $request . "\n\n";
        # Sending secure GET request to USPS (for first-type image)
        list($header, $return) = cw_https_request("GET", $request);
        $_log .= "[RESPONSE]:\n\n" . $header . "\n\n" . $return . "\n\n";
        # Parcing first USPS response
        $response = cw_usps_parce_result($return, $data['xml_head'], $xml_data['file_type']);
        if ($response['error'] && $response['error_code'] != $xml_data['ignore']) {
            $error[$method . " #" . $xml_id] = $response['data'];
        }
        if ($response['error']) {
            $_log .= "[ERROR]:\n\n" . $method . " " . $xml_id . " = " . $response['data'] . "\n\n";
        } else {
            # Saving labels or messages
            cw_usps_save_response($response, $method, $xml_id);
        }
    }
}
if (defined('USPS_DEBUG')) {
function ab_int_ratings($allowed_shipping_methods, $address, $weight, $debug, $params)
{
    global $config, $tables;
    if ($config['Company']['country'] != 'US' || $address['country'] == 'US') {
        return array();
    }
    cw_load('xml', 'http');
    # Define transaction parameters
    $siteid = $params['id'];
    $pass = $params['password'];
    $skey = $params['skey'];
    $anumber = $params['account'];
    $sh_email = $config['Company']['orders_department'];
    $sh_address = $config['Company']['address'];
    $sh_city = $config['Company']['city'];
    $sh_state = $config['Company']['state'];
    $sh_zipcode = $config['Company']['zipcode'];
    $sh_country = $config['Company']['country'];
    $rc_address = $address['address'];
    $rc_address_2 = $address['address_2'];
    $rc_city = $address['city'];
    $rc_state = $address['state'];
    $rc_zipcode = $address['zipcode'];
    $rc_country = $address['country'];
    $rc_phone = $address['phone'];
    $rc_email = $address['email'];
    $p_width = intval($params['length']);
    $p_height = intval($params['height']);
    $p_depth = intval($params['width']);
    $p_type = $params['package'];
    $c_name = $config['Company']['company_name'];
    $c_phone = $config['Company']['company_phone'];
    $c_fax = $config['Company']['company_fax'];
    $ship_date = $params['ship_date'];
    # Correct United Kingdom code - UK
    if ($rc_country == 'GB') {
        $rc_country = 'UK';
    }
    # Define request header
    $post = <<<REQ
<?xml version='1.0'?><ECommerce action='Request' version='1.1'>
\t<Requestor>
\t\t<ID>{$siteid}</ID>
\t\t<Password>{$pass}</Password>
\t</Requestor>
REQ;
    $ship_weight = $params['weight'];
    $ship_weight_oz = $params['weight_oz'];
    if ($ship_weight_oz > 8 && $p_type == 'L') {
        return;
    }
    # Define request body
    $i = 0;
    foreach ($allowed_shipping_methods as $method) {
        if ($method['code'] != "ARB" || $params['weight'] > $method['weight_limit'] && $method['weight_limit'] > 0 || empty($method['subcode']) || $method['destination'] == 'L' || !isset($mod_AB_ship_flags[$method['subcode']])) {
            continue;
        }
        $scode = $mod_AB_ship_flags[$method['subcode']]['code'];
        $i++;
        $dims = '';
        if ($p_type == 'P') {
            $dims = <<<DIMS
\t\t<Weight>{$ship_weight}</Weight>
\t\t<Dimensions>
\t\t\t<Length>{$p_width}</Length>
\t\t\t<Width>{$p_height}</Width>
\t\t\t<Height>{$p_depth}</Height>
\t\t</Dimensions>
DIMS;
        }
        $post .= <<<REQ
 <IntlShipment action = 'RateEstimate' version = '1.0'>
\t<ShippingCredentials>
\t\t<ShippingKey>{$skey}</ShippingKey>
\t\t<AccountNbr>{$anumber}</AccountNbr>
\t</ShippingCredentials>
\t<ShipmentDetail>
\t\t<ShipDate>{$ship_date}</ShipDate>
\t\t<Service>
\t\t\t<Code>{$scode}</Code>
\t\t</Service>
\t\t<ShipmentType>
\t\t\t<Code>{$p_type}</Code>
\t\t</ShipmentType>
\t\t<ContentDesc>Big Box</ContentDesc>
\t\t{$dims}
\t</ShipmentDetail>
\t<Dutiable>
\t\t<DutiableFlag>N</DutiableFlag>
\t\t<CustomsValue>0</CustomsValue>
\t</Dutiable>
\t<Billing>
\t\t<Party>
\t\t\t<Code>S</Code>
\t\t</Party>
\t\t<DutyPaymentType>S</DutyPaymentType>
\t</Billing>
\t<Sender>
\t\t<Address>
\t\t\t<CompanyName>{$c_name}</CompanyName>
\t\t\t<Street>{$sh_address}</Street>
\t\t\t<City>{$sh_city}</City>
\t\t\t<State>{$sh_state}</State>
\t\t\t<PostalCode>{$sh_zipcode}</PostalCode>
\t\t\t<Country>{$sh_country}</Country>
\t\t</Address>
\t\t<PhoneNbr>{$c_phone}</PhoneNbr>
\t\t<Email>{$sh_email}</Email>
\t</Sender>
\t<Receiver>
\t\t<Address>
\t\t\t<Street>{$rc_address}</Street>
\t\t\t<StreetLine2>{$rc_address_2}</StreetLine2>
\t\t\t<City>{$rc_city}</City>
\t\t\t<PostalCode>{$rc_zipcode}</PostalCode>
\t\t\t<State>{$rc_state}</State>
\t\t\t<Country>{$rc_country}</Country>
\t\t</Address>
\t\t<PhoneNbr>{$rc_phone}</PhoneNbr>
\t\t<Email>{$rc_email}</Email>
\t</Receiver>
</IntlShipment>
</ECommerce>
REQ;
    }
    if (empty($i)) {
        return array();
    }
    # Request
    list($a, $result) = cw_https_request("POST", $params['url'], array($post), "", "", "text/xml");
    $parse_errors = false;
    $options = array('XML_OPTION_CASE_FOLDING' => 1, 'XML_OPTION_TARGET_ENCODING' => 'ISO-8859-1');
    $parsed = cw_xml_parse($result, $parse_errors, $options);
    # Detect common errors
    $errors = cw_array_path($parsed, "ECOMMERCE/FAULT");
    if (!empty($errors)) {
        if ($debug == 'Y') {
            echo "<h1>DHL/Airborne request faults</h1>\n";
        }
        foreach ($errors as $k => $v) {
            $errors[$k] = cw_array_path($v, "#/CODE/0/#") . ": " . cw_array_path($v, "#/DESCRIPTION/0/#");
            if ($debug == 'Y') {
                echo $errors[$k] . "<br />\n";
            }
        }
        return array();
    }
    # Detect rates
    $methods = cw_array_path($parsed, "ECOMMERCE/INTLSHIPMENT");
    if (empty($methods)) {
        return array();
    }
    foreach ($methods as $m) {
        # Detect rate error
        $errs = cw_array_path($m, "#/FAULTS");
        if (!empty($errs)) {
            $errors = array();
            foreach ($errs as $e) {
                $suberrors = cw_array_path($e, "#/FAULT");
                if (!empty($suberrors)) {
                    foreach ($suberrors as $se) {
                        $errors[] = cw_array_path($se, "#/CODE/0/#") . ": " . cw_array_path($se, "#/DESC/0/#");
                    }
                }
            }
            continue;
        }
        # Detect rate
        $id = trim(cw_array_path($m, "ESTIMATEDETAIL/SERVICE/CODE/0/#"));
        $rate = doubleval(trim(cw_array_path($m, "ESTIMATEDETAIL/RATEESTIMATE/0/#/TOTALCHARGEESTIMATE/0/#")));
        # Save rate
        foreach ($allowed_shipping_methods as $method) {
            if ($method['code'] != "ARB" || $weight > $method['weight_limit'] && $method['weight_limit'] > 0 || $mod_AB_ship_flags[$method['subcode']]['code'] != $id || $method['destination'] == 'L') {
                continue;
            }
            $rates[] = array("methodid" => $method['subcode'], "rate" => $rate, "shipping_time" => trim(cw_array_path($m, "ESTIMATEDETAIL/SERVICELEVELCOMMITMENT/DESC/0/#")));
        }
    }
}
cw_load('http');
#
# Get $merchant_password from command line
#
$merchant_password = '';
if (is_array($_SERVER['argv']) && !empty($_SERVER['argv'])) {
    foreach ($_SERVER['argv'] as $v) {
        if (preg_match("/merchant_password=(\\S+)/S", $v, $preg)) {
            $merchant_password = $preg[1];
            break;
        }
    }
}
#
# Get $merchant_password from GET parametrs
#
if ($_GET['merchant_password']) {
    $merchant_password = $_GET['merchant_password'];
}
#
# Get $merchant_password from hardcoded variables
#
if (!$merchant_password) {
    $merchant_password = "";
}
if ($config['mpassword'] != md5($merchant_password) || !$merchant_password) {
    die(cw_get_langvar_by_name("err_mpassword_wrong"));
}
$res = cw_https_request("POST", $app_catalogs_secure['admin'] . "/recrypt.php", array("merchant_password="******"Result: " . $res[1]);
function cw_paypal_pro_payflow_do($post)
{
    global $config;
    $str = array();
    $str['vendor'] = $config['paypal_pro_payflow']['vendor'];
    $str['partner'] = $config['paypal_pro_payflow']['partner'];
    $str['user'] = $config['paypal_pro_payflow']['user'];
    $str['pwd'] = $config['paypal_pro_payflow']['password'];
    $requestid = isset($post['requestid']) ? $post['requestid'] : time();
    cw_unset($post, "requestid");
    if ($config['paypal_pro_payflow']['currency']) {
        $post['currency'] = $config['paypal_pro_payflow']['currency'];
    }
    if (isset($post['invnum'])) {
        $post['invnum'] = $config['paypal_pro_payflow']['prefix'] . $post['invnum'];
    }
    $post['reqconfirmshipping'] = $config['paypal_pro_payflow']['is_confirmed_address'] == 'Y' ? 1 : 0;
    if ($config['paypal_pro_payflow']['page_style']) {
        $post['page_style'] = $config['paypal_pro_payflow']['page_style'];
    }
    if ($config['paypal_pro_payflow']['header_image_url']) {
        $post['hdrimg'] = $config['paypal_pro_payflow']['header_image_url'];
    }
    if (isset($post['notifyurl'])) {
        global $current_location;
        $post['notifyurl'] = $current_location . '/payment/index.php?target=paypal_pro-vendor';
    }
    $str = cw_array_merge($str, $post);
    $data = array();
    foreach ($str as $k => $v) {
        $data[] = strtoupper($k) . "=" . $v;
    }
    #$url = $config['paypal_pro_payflow']['test_mode'] ? "https://pilot-payflowpro.verisign.com:443/transaction" : "https://payflowpro.verisign.com:443/transaction";
    $url = $config['paypal_pro_payflow']['test_mode'] == 'Y' ? "https://pilot-payflowpro.paypal.com:443/" : "https://payflowpro.paypal.com:443/";
    $headers = array("X-VPS-REQUEST-ID" => $requestid, "X-VPS-VIT-CLIENT-CERTIFICATION-ID" => "7894b92104f04ffb4f38a8236ca48db3");
    //cw_log_add('payflow_pro', array('url'=>$url, 'data'=>$data, 'headers'=>$headers));
    # kornev, we are making the implode here - because we don't need the urlencode
    list($headers, $response) = cw_https_request("POST", $url, array(implode('&', $data)), "", "", "application/x-www-form-urlencoded", "", "", "", $headers);
    //cw_log_add('payflow_pro', array('headers'=>$headers, 'response'=>$response));
    if (empty($response)) {
        return array($headers, $response);
    }
    $result = array();
    $tmp = array();
    parse_str($response, $tmp);
    if (empty($tmp) || !is_array($tmp)) {
        return array($headers, $response);
    }
    foreach ($tmp as $k => $v) {
        $result[strtolower($k)] = urldecode($v);
    }
    return array($headers, $response, $result);
}
function cw_paypal_express_request($params)
{
    //$request, $regexp=false) {
    extract($params);
    global $config, $app_dir;
    if ($config['paypal_express']['test_mode'] == "N") {
        $pp_url = $config['paypal_express']['auth_type'] == 'C' ? "https://api.paypal.com:443/2.0/" : "https://api-3t.paypal.com:443/2.0/";
    } else {
        $pp_url = $config['paypal_express']['auth_type'] == 'C' ? "https://api.sandbox.paypal.com:443/2.0/" : "https://api-3t.sandbox.paypal.com:443/2.0/";
    }
    $post = explode("\n", $request);
    if ($config['paypal_express']['auth_type'] == 'C') {
        list($headers, $response) = cw_https_request("POST", $pp_url, $post, "", "", "text/xml", "", $app_dir . '/payment/certs/' . $config['paypal_express']['api_cert_path']);
    } else {
        list($headers, $response) = cw_https_request("POST", $pp_url, $post, "", "", "text/xml", "");
    }
    if ($headers == "0") {
        return array('success' => false, 'error' => array('ShortMessage' => $response));
    }
    $result = array('headers' => $headers, 'response' => $response);
    if (!empty($regexp)) {
        $matches = array();
        preg_match($regexp, $response, $matches);
        $result['matches'] = $matches;
    }
    #
    # Parse and fill common fields
    #
    $result['success'] = false;
    $ord_fields = array('Ack', 'TransactionID', 'Token', 'AVSCode', 'CVV2Code', 'PayerID', 'PayerStatus', 'FirstName', 'LastName', 'ContactPhone', 'TransactionType', 'PaymentStatus', 'PendingReason', 'ReasonCode', 'GrossAmount', 'FeeAmount', 'SettleAmount', 'TaxAmount', 'ExchangeRate');
    foreach ($ord_fields as $field) {
        if (preg_match('!<' . $field . '(?: [^>]*)?>([^>]+)</' . $field . '>!', $response, $out)) {
            $result[$field] = $out[1];
        }
    }
    if (!strcasecmp($result['Ack'], 'Success') || !strcasecmp($result['Ack'], 'SuccessWithWarning')) {
        $result['success'] = true;
    }
    if (preg_match('!<Payer(?:\\s[^>]*)?>([^>]+)</Payer>!', $response, $out)) {
        $result['Payer'] = $out[1];
        # e-mail address
    }
    if (preg_match('!<Errors[^>]*>(.+)</Errors>!', $response, $out_err)) {
        $error = array();
        if (preg_match('!<SeverityCode[^>]*>([^>]+)</SeverityCode>!', $out_err[1], $out)) {
            $error['SeverityCode'] = $out[1];
        }
        if (preg_match('!<ErrorCode[^>]*>([^>]+)</ErrorCode>!', $out_err[1], $out)) {
            $error['ErrorCode'] = $out[1];
        }
        if (preg_match('!<ShortMessage[^>]*>([^>]+)</ShortMessage>!', $out_err[1], $out)) {
            $error['ShortMessage'] = $out[1];
        }
        if (preg_match('!<LongMessage[^>]*>([^>]+)</LongMessage>!', $out_err[1], $out)) {
            $error['LongMessage'] = $out[1];
        }
        $result['error'] = $error;
    }
    if (preg_match('!<Address[^>]*>(.+)</Address>!', $response, $out)) {
        $out_addr = $out[1];
        $address = array();
        if (preg_match('!<Name[^>]*>([^>]+)</Name>!', $out_addr, $out)) {
            $__name = explode(' ', $out[1], 2);
            $address['FirstName'] = $__name[0];
            $address['LastName'] = $__name[1];
            unset($__name);
        }
        if (preg_match('!<Street1[^>]*>([^>]+)</Street1>!', $out_addr, $out)) {
            $address['Street1'] = $out[1];
        }
        if (preg_match('!<Street2[^>]*>([^>]+)</Street2>!', $out_addr, $out)) {
            $address['Street2'] = $out[1];
        }
        if (preg_match('!<CityName[^>]*>([^>]+)</CityName>!', $out_addr, $out)) {
            $address['CityName'] = $out[1];
        }
        if (preg_match('!<StateOrProvince[^>]*>([^>]+)</StateOrProvince>!', $out_addr, $out)) {
            $address['StateOrProvince'] = $out[1];
        }
        if (preg_match('!<Country[^>]*>([^>]+)</Country>!', $out_addr, $out)) {
            $address['Country'] = $out[1];
        }
        if (preg_match('!<PostalCode[^>]*>([^>]+)</PostalCode>!', $out_addr, $out)) {
            $address['PostalCode'] = $out[1];
        }
        if (preg_match('!<AddressOwner[^>]*>([^>]+)</AddressOwner>!', $out_addr, $out)) {
            $address['AddressOwner'] = $out[1];
        }
        if (preg_match('!<AddressStatus[^>]*>([^>]+)</AddressStatus>!', $out_addr, $out)) {
            $address['AddressStatus'] = $out[1];
        }
        $result['address'] = $address;
    }
    return $result;
}
Ejemplo n.º 10
0
function cw_payment_sagepaygo_server_run_processor($params, $return)
{
    if ($params['payment_data']['processor'] == sagepaygo_server_addon_name) {
        global $config, $tables, $current_location, $cart, $REMOTE_ADDR;
        cw_load('http');
        $payment_data = $params['payment_data'];
        $userinfo = $params['userinfo'];
        $doc_ids = $params['doc_ids'];
        $addon_name = str_replace("-", "_", sagepaygo_server_addon_name);
        $cart =& cw_session_register('cart');
        $skey = cw_call('cw_payment_start');
        $bill_name = cw_payment_sagepaygo_server_get_bill_name($userinfo);
        $ship_name = cw_payment_sagepaygo_server_get_ship_name($userinfo);
        $pp_merch = $config[$addon_name]['sps_vendor_name'];
        $pp_curr = $config[$addon_name]['sps_currency'];
        // Determine request URL (simulator, test server or live server)
        switch ($config[$addon_name]['sps_test_live_mode']) {
            case 'S':
                $pp_test = 'https://test.sagepay.com:443/Simulator/VSPServerGateway.asp?Service=VendorRegisterTx';
                break;
            case 'Y':
                $pp_test = 'https://test.sagepay.com:443/gateway/service/vspserver-register.vsp';
                break;
            default:
                $pp_test = 'https://live.sagepay.com:443/gateway/service/vspserver-register.vsp';
        }
        $pp_shift = $config[$addon_name]['sps_order_prefix'];
        $post = array();
        $post['VPSProtocol'] = '2.23';
        $post['TxType'] = $config[$addon_name]['sps_action_on_order_placement'] == 'Y' ? 'DEFERRED' : 'PAYMENT';
        $post['Vendor'] = substr($pp_merch, 0, 15);
        $post['VendorTxCode'] = substr($pp_shift, 0, 8) . $skey;
        $post['ReferrerID'] = sagepaygo_server_addon_partner_id;
        $post['Amount'] = $cart['info']['total'];
        $post['Currency'] = $pp_curr;
        $post['Description'] = 'Your Cart';
        $post['NotificationURL'] = $current_location . '/index.php?target=' . sagepaygo_server_addon_target;
        $post['Profile'] = 'LOW';
        // Billing information
        $post['BillingSurname'] = $bill_name['lastname'];
        $post['BillingFirstnames'] = $bill_name['firstname'];
        $post['BillingAddress1'] = $userinfo['main_address']['address'];
        if (!empty($userinfo['main_address']['address_2'])) {
            $post['BillingAddress2'] = $userinfo['main_address']['address_2'];
        }
        $post['BillingCity'] = $userinfo['main_address']['city'];
        $post['BillingPostCode'] = $userinfo['main_address']['zipcode'];
        $post['BillingCountry'] = $userinfo['main_address']['country'];
        if ($userinfo['main_address']['country'] == 'US' && !empty($userinfo['main_address']['state'])) {
            $post['BillingState'] = $userinfo['main_address']['state'];
        }
        // Shipping information
        $post['DeliverySurname'] = $ship_name['lastname'];
        $post['DeliveryFirstnames'] = $ship_name['firstname'];
        $post['DeliveryAddress1'] = $userinfo['current_address']['address'];
        if (!empty($userinfo['current_address']['address_2'])) {
            $post['DeliveryAddress2'] = $userinfo['current_address']['address_2'];
        }
        $post['DeliveryCity'] = $userinfo['current_address']['city'];
        $post['DeliveryPostCode'] = $userinfo['current_address']['zipcode'];
        $post['DeliveryCountry'] = $userinfo['current_address']['country'];
        if ($userinfo['current_address']['country'] == 'US' && !empty($userinfo['current_address']['state'])) {
            $post['DeliveryState'] = $userinfo['current_address']['state'];
        }
        $post['CustomerEMail'] = $userinfo['email'];
        $post['GiftAidPayment'] = '0';
        $post['ApplyAVSCV2'] = $config[$addon_name]['sps_avs_cv2_checks'];
        $post['Apply3DSecure'] = $config[$addon_name]['sps_3d_secure_checks'];
        // Tide up the entire values
        $post = cw_payment_sagepaygo_server_clean_post($post);
        // Send initial request and obtain the key
        list($a, $return) = cw_https_request('POST', $pp_test, $post);
        // Parse response
        $ret = str_replace("\r\n", '&', $return);
        $ret_arr = explode('&', $ret);
        $response = array();
        foreach ($ret_arr as $ret) {
            if (preg_match('/([^=]+?)=(.+)/', $ret, $matches)) {
                $response[$matches[1]] = $matches[2];
            }
        }
        if ($response['Status'] == 'OK' && $response['NextURL']) {
            // Redirect to SagePay
            cw_header_location($response['NextURL']);
            exit;
        } else {
            global $app_catalogs;
            $data = cw_call('cw_payment_get_data', array($skey));
            // Return with error
            $bill_output['code'] = 2;
            $bill_output['sessid'] = $data['session_id'];
            $bill_output['skey'] = $skey;
            $bill_output['billmes'] = 'Status: ' . $response['StatusDetail'] . ' (' . $response['Status'] . ')';
            if (!empty($response['VPSTxID'])) {
                $bill_output['billmes'] .= ' (TxID: ' . $response['VPSTxID'] . ')';
            }
            $return = cw_call('cw_payment_check_results', array($bill_output));
            $top_message =& cw_session_register('top_message');
            $top_message = array('type' => 'E', 'content' => $return['bill_error'] . ' ' . $return['reason']);
            $request = $app_catalogs['customer'] . '/index.php?target=cart&mode=checkout';
            cw_header_location($request);
            exit;
        }
    }
    return $return;
}
Ejemplo n.º 11
0
<ServiceType>{$service_type}</ServiceType>
<SeparateReceiptPage></SeparateReceiptPage>
<POZipCode></POZipCode>
<ImageType>{$image_type}</ImageType>
<LabelDate></LabelDate>
<CustomerRefNo></CustomerRefNo>
<AddressServiceRequested></AddressServiceRequested>
<SenderName></SenderName>
<SenderEMail></SenderEMail>
<RecipientName></RecipientName>
<RecipientEMail></RecipientEMail>
</{$xml_head}>
EOT;
    }
    $query_prepared = urlencode($query);
    list($header, $return) = cw_https_request("GET", $usps_server . "?API={$api}&XML=" . $query_prepared);
    if (defined('USPS_DEBUG')) {
        cw_log_add('usps', $query . "\n\n" . $header . "\n\n" . $return);
    }
    $response = array("result" => 'http_error');
    $res = cw_xml2hash($return);
    if ($res['Error']) {
        $response['result'] = 'error';
        $response['error'] = $res['Error']['Description'];
    } elseif ($res[$head . 'Response']) {
        $response['result'] = 'ok';
        if ($service_type == "GlobalAir" || $service_type == "GlobalExpress" || $service_type == "GlobalPriority") {
            $response['image'] = base64_decode(str_replace(array("\n"), array(""), $res[$head . 'Response']['LabelImage']));
        } elseif ($service_type == "ExpressMail") {
            $response['image'] = base64_decode(str_replace(array("\n"), array(""), $res[$head . 'Response']['EMLabel']));
        } else {
function cw_shipper_USPS($weight, $customer_id, $address, $debug, $cart)
{
    global $config, $tables, $current_language;
    $USPS_username = $config['Shipping']['USPS_username'];
    $USPS_password = $config['Shipping']['USPS_password'];
    $USPS_servername = $config['Shipping']['USPS_servername'];
    $use_usps_https = false;
    if (empty($USPS_username) || empty($USPS_servername)) {
        return;
    }
    $USPS_FOUND = false;
    if (is_array($allowed_shipping_methods)) {
        foreach ($allowed_shipping_methods as $key => $value) {
            if ($value['code'] == "USPS") {
                $USPS_FOUND = true;
                break;
            }
        }
    }
    if (!$USPS_FOUND) {
        return;
    }
    cw_load('http', 'xml');
    $pounds = 0;
    $ounces = ceil(round(cw_weight_in_grams($weight) / 28.35, 3));
    if ($ounces < 1) {
        $ounces = 1;
    }
    $mailtype = $params['param00'];
    $package_size = $params['param01'];
    $machinable = $params['param02'];
    $container_express = $params['param03'];
    $container_priority = $params['param04'];
    if (!empty($container_express) && $container_express != 'None') {
        $container_express = "<Container>" . $container_express . "</Container>";
    } else {
        $container_express = "";
    }
    if (!empty($container_priority) && $container_priority != 'None') {
        $container_priority = "<Container>" . $container_priority . "</Container>";
    } else {
        $container_priority = "";
    }
    if ($address['country'] == 'PR' || $address['country'] == 'GU' || $address['country'] == 'VI') {
        $address['country'] = 'US';
    }
    $dst_country = USPS_get_country($address['country']);
    if (empty($dst_country)) {
        $dst_country = cw_query_first_cell("SELECT value FROM {$tables['languages']} WHERE name = 'country_" . $address['country'] . "' AND code = '{$current_language}'");
    }
    $USPS_file = $USPS_servername == "testing.shippingapis.com" ? "/ShippingAPITest.dll" : "/ShippingAPI.dll";
    $hash = array();
    if ($address['country'] != $config['Company']['country']) {
        # International shipping
        $query = <<<EOT
<IntlRateRequest USERID="{$USPS_username}" PASSWORD="******">
<Package ID="0">
<Pounds>{$pounds}</Pounds>
<Ounces>{$ounces}</Ounces>
<MailType>{$mailtype}</MailType>
<Country>{$dst_country}</Country>
</Package>
</IntlRateRequest>
EOT;
        $md5_request = md5($query);
        if (cw_is_shipping_result_in_cache($md5_request) && $debug != "Y") {
            $rates = cw_get_shipping_result_from_cache($md5_request);
            return;
        }
        if ($use_usps_https) {
            $post = array("API=IntlRate", "XML=" . urlencode($query));
            list($header, $result) = cw_https_request("GET", "https://" . $USPS_servername . ":443" . $USPS_file . "?API=IntlRate&XML=" . urlencode($query));
        } else {
            list($header, $result) = cw_http_get_request($USPS_servername, $USPS_file, "API=IntlRate&XML=" . urlencode($query));
        }
        $xml = cw_xml_parse($result, $err);
        # Get <Error> elemenet
        $err = cw_array_path($xml, "IntlRateResponse/Package/Error");
        if (empty($err)) {
            # Get <Service> elements
            $packages = cw_array_path($xml, "IntlRateResponse/Package/Service");
            if (!empty($packages) && is_array($packages)) {
                foreach ($packages as $p) {
                    # Get shipping method name
                    $sname = cw_array_path($p, "SvcDescription/0/#");
                    # Get rate
                    $rate = cw_array_path($p, "Postage/0/#");
                    # Get comment
                    #$comment = cw_array_path($p, "SvcCommitments/0/#");
                    if (empty($sname) || zerolen($rate)) {
                        continue;
                    }
                    # Define shipping method
                    $is_found = false;
                    foreach ($allowed_shipping_methods as $sm) {
                        if ($sm['code'] == "USPS" && $sm['destination'] == "I" && preg_match("/^" . preg_quote($sm['shipping'], "/") . "/S", "USPS " . $sname)) {
                            if (!in_array($sm['subcode'], $hash)) {
                                $rates[] = array("methodid" => $sm['subcode'], "rate" => $rate, "warning" => "");
                                $hash[] = $sm['subcode'];
                            }
                            $is_found = true;
                            break;
                        }
                    }
                    if (!$is_found) {
                        # Add new shipping method
                        cw_add_new_smethod("USPS " . $sname, "USPS", array("destination" => "I"));
                    }
                }
                if ($debug != "Y") {
                    cw_save_shipping_result_to_cache($md5_request, $rates);
                }
            }
        }
    } else {
        # Domestic shipping
        $ZO = $config['Company']['zipcode'];
        $ZD = $address['zipcode'];
        $query = <<<EOT
<RateV2Request USERID="{$USPS_username}">
\t<Package ID="0">
\t\t<Service>EXPRESS</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t{$container_express}
\t\t<Size>{$package_size}</Size>
\t</Package>
\t<Package ID="1">
\t\t<Service>FIRST CLASS</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t<Container>None</Container>
\t\t<Size>{$package_size}</Size>
\t</Package>
\t<Package ID="2">
\t\t<Service>PRIORITY</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t{$container_priority}
\t\t<Size>{$package_size}</Size>
\t</Package>
\t<Package ID="3">
\t\t<Service>PARCEL</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t<Container>None</Container>
\t\t<Size>{$package_size}</Size>
\t\t<Machinable>{$machinable}</Machinable>
\t</Package>
\t<Package ID="4">
\t\t<Service>BPM</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t<Container>None</Container>
\t\t<Size>{$package_size}</Size>
\t</Package>
\t<Package ID="5">
\t\t<Service>LIBRARY</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t<Container>None</Container>
\t\t<Size>{$package_size}</Size>
\t</Package>
\t<Package ID="6">
\t\t<Service>MEDIA</Service>
\t\t<ZipOrigination>{$ZO}</ZipOrigination>
\t\t<ZipDestination>{$ZD}</ZipDestination>
\t\t<Pounds>{$pounds}</Pounds>
\t\t<Ounces>{$ounces}</Ounces>
\t\t<Container>None</Container>
\t\t<Size>{$package_size}</Size>
\t</Package>
</RateV2Request>
EOT;
        $md5_request = md5($query);
        if (cw_is_shipping_result_in_cache($md5_request) && $debug != "Y") {
            $rates = cw_get_shipping_result_from_cache($md5_request);
            return;
        }
        if ($use_usps_https) {
            $post = array("API=RateV2", "XML=" . urlencode($query));
            list($header, $result) = cw_https_request("GET", "https://" . $USPS_servername . ":443" . $USPS_file . "?API=RateV2&XML=" . urlencode($query));
        } else {
            list($header, $result) = cw_http_get_request($USPS_servername, $USPS_file, "API=RateV2&XML=" . urlencode($query));
        }
        $xml = cw_xml_parse($result, $err);
        # Get <Package> elements
        $packages = cw_array_path($xml, "RateV2Response/Package");
        if (is_array($packages)) {
            foreach ($packages as $p) {
                # Get <Error> element
                $err = cw_array_path($p, "Error");
                if (!empty($err)) {
                    continue;
                }
                # Get shipping method name
                $sname = cw_array_path($p, "Postage/MailService/0/#");
                # Get rate
                $rate = cw_array_path($p, "Postage/Rate/0/#");
                if (empty($sname) || zerolen($rate)) {
                    continue;
                }
                # Define shipping method
                $is_found = false;
                foreach ($allowed_shipping_methods as $sm) {
                    if ($sm['code'] == "USPS" && $sm['destination'] == "L" && preg_match("/^" . preg_quote($sm['shipping'], "/") . "/S", "USPS " . $sname)) {
                        if (!in_array($sm['subcode'], $hash)) {
                            $rates[] = array("methodid" => $sm['subcode'], "rate" => $rate, "warning" => "");
                            $hash[] = $sm['subcode'];
                        }
                        $is_found = true;
                        break;
                    }
                }
                if (!$is_found) {
                    # Add new shipping method
                    cw_add_new_smethod("USPS " . $sname, "USPS", array("destination" => "L"));
                }
            }
            if ($debug != "Y") {
                cw_save_shipping_result_to_cache($md5_request, $rates);
            }
        }
        // if (is_array($packages))
    }
}