Как мога да изпратя POST данни с curl към функция на контролер magento от външен сайт?

Имам персонализиран контролер с функция в моя сайт на magento, който програмно създава клиент, добавя продукт в неговата количка и го пренасочва към страницата за плащане. Всичко работи добре. Функцията на контролера е достъпна чрез URL mymagentopage.de/namespace/controllername/functionname и ще пренасочи потребителя към страницата за плащане на една страница на magento.

Сега трябва да предам данни (име, имейл и адрес от потребителя) от външна страница към тази функция. Мислех, че мога да направя това с къдрици. Но няма да работи. Винаги получавам празна страница без никакви грешки. Никога не съм работил с curl преди и също съм съвсем нов в magento, така че наистина не знам какъв може да е проблемът. Може ли някой да ми помогне или да ми даде съвет? Или има друг/по-добър начин за предаване на данни от външен сайт?

Използвам кода в този пример на моя външен сайт, за да публикувам потребителски данни към моята функция mageno, използвайки връзката mymagentopage.de/namespace/controllername/functionname. Curl кодът на външния сайт се изпълнява, когато потребителят изпрати формуляр, но получих само празна страница...

Функцията на контролера на magento:

class MyModule_Test_CustomController extends Mage_Core_Controller_Front_Action {

    // this is the action that loads the cart and redirects to the cart page
    public function cartAction() {

        // Get customer session
        $session = Mage::getSingleton('customer/session');
        $websiteId = Mage::app()->getWebsite()->getId();
        $store = Mage::app()->getStore();
        $customer = Mage::getModel("customer/customer");
        $email = '[email protected]'
        $price = '20';

        function IscustomerEmailExists($email, $websiteId = null){
            $customer = Mage::getModel('customer/customer');

            if ($websiteId) {
                $customer->setWebsiteId($websiteId);
            }
            $customer->loadByEmail($email);
            if ($customer->getId()) {
                return $customer->getId();
            }
            return false;
        }

        $cust_exist = IscustomerEmailExists($email,$websiteId);

        if($cust_exist){

            $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
            $customer->loadByEmail($email);
            $session_customer = Mage::getSingleton('customer/session')->loginById($customer->getId());

            $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
            if ($customerAddressId){
              $customAddress = Mage::getModel('customer/address')->load($customerAddressId);
              $customAddress->getData();
            }
        }
        else{

             $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
             $customer->loadByEmail($email);

             if(!$customer->getId()) {
               $customer->setStore($store);
               $customer->setEmail($email);
               $customer->setFirstname('John');
               $customer->setLastname('Doe');
               $customer->setPassword('somepassword');
             }

             try {
               $customer->save();
               $customer->setConfirmation(null);
               $customer->save();

               $session_customer = Mage::getSingleton('customer/session')->loginById($customer->getId());
             }

             catch (Exception $ex) {
             }

             //Build billing address for customer, for checkout
             $_custom_address = array (
                'firstname' => 'John',
                'lastname' => 'Doe',
                'street' => 'Sample address part1',
                'city' => 'Munich',
                'region_id' => 'BAY',
                'region' => 'BAY',
                'postcode' => '81234',
                'country_id' => 'DE', 
                'telephone' => '0123455677',
             );

             $customAddress = Mage::getModel('customer/address');
             $customAddress->setData($_custom_address)
                        ->setCustomerId($customer->getId())
                        ->setIsDefaultBilling('1')
                        ->setIsDefaultShipping('1')
                        ->setSaveInAddressBook('1');

             try {
                $customAddress->save();
             }
             catch (Exception $ex) {
             }
        }

        Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));

        // Get cart instance
        $cart = Mage::getSingleton('checkout/cart');

        $cart->init();

        $product = Mage::getModel('catalog/product');
        $product->load('2');
        $product->setPrice($price);
        $product->save();
        $cart->addProduct($product, array('qty' => 1));

        $session->setCartWasUpdated(true);
        $cart->save();

        Mage::app()->getResponse()->setRedirect(Mage::helper('checkout/url')->getCheckoutUrl()); //redirect to Checkout
    }
}

person iraira    schedule 21.02.2016    source източник
comment
Актуализирах публикацията си. ;)   -  person iraira    schedule 21.02.2016
comment
тъй като правите пренасочване, защо не насочите действието на формуляра директно към страницата magento, вместо да използвате curl за публикуване на данните?   -  person zokibtmkd    schedule 22.02.2016
comment
Защото.. Мисля, че е твърде сложно... ;D хаха.. благодаря ви, това свърши работа за мен! Беше твърде много часове работа, предполагам..   -  person iraira    schedule 22.02.2016


Отговори (2)


Добре, мислех твърде сложно... Просто трябваше да насоча формуляра „действие“ на моя външен сайт към страницата magento директно, която изпълнява моето действие magento. След това трябваше да хвана параметрите с

$this->getRequest()->getPost('email');

в магенто действието. И това е. Толкова просто...

person iraira    schedule 22.02.2016

Във вашия POST код полетата не са URL кодирани, което може да генерира лоши заявки или други грешки.

Опитайте тази:

public function post_to_url($url, $data) {
     $fields = http_build_query($fields); // encode array to POST string

     $post = curl_init();

     curl_setopt($post, CURLOPT_URL, $url);
     curl_setopt($post, CURLOPT_POST, 1);
     curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
     curl_setopt($post, CURLOPT_USERAGENT, 'Mozilla/5.0');
     curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
     //curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);

     $result = curl_exec($post);

     // for debugging
     var_dump(curl_getinfo($post), $result);

    //  if(false === $result) { // request failed
    //       die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
    // }

     curl_close($post);

  }
person drew010    schedule 21.02.2016