4

I'm creating a mobile app using the Ionic 2 framework. Can anybody please point me in the direction of getting started or some boilerplate code for using Magento's XML_Connect through Javascript?

I have searched but haven't come up with anything.

Thank you!


EDIT

I apologise if this question seems rather broad, but I honestly am drawing a blank with getting started with XML_Connect. As I am building a mobile app, my understanding is that XML_Connect is better to use than the SOAP or REST APIs, as it already provides all the necessary functions. At a very basic I need to learn how to:

  1. Create a new session;
  2. Login/Create a customer;
  3. Pull in categories;
  4. Render products from a category;
  5. Render the Product detail (Simple and Configurable products);
  6. Add products to a cart; and
  7. Checkout

Additionally, as I'm building my app using the Ionic Framework, the only scripting language I'm able to use is Javascript.

I should add that I have already activated the module in Magento, have the new Mobile menu available, and have generated a new app code.

The article: http://inchoo.net/ecommerce/magento/develop-your-own-magento-mobile-application/ didn't help much.

1

2 Answers 2

1

Using a JQuery XML-RPC library you should have no troubles talking with Magento's API, see the answer below from an existing Q/A:

Yes, you can

you can call magento's xmlrpc apis using jQuery XML-RPC library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="js/jquery.xmlrpc.js"></script>

first is simple jquery library and second library file you can get from here:

http://jquery-xml-rpc.readthedocs.io/en/latest/index.html

Here is two type of example of this call.

1. Login Call

$.xmlrpc({
    url: 'Your_magento_root/index.php/api/xmlrpc',
    methodName: 'login',
    params: ['api_user', "api_key"],
    success: function(response, status, jqXHR) {
        alert('Sucsses');       
        Session = response[0]; // this session key is important for next transaction                 
    },
    error: function(jqXHR, status, error) {
        alert('error');
        console.log(status);  
    }
});

2. After Login Calls

$.xmlrpc({
    url: 'Your_magento_root/index.php/api/xmlrpc',
    methodName: 'call',
    params: [Session, 'Your_methode_name',[0,'any other parameter',1]],
    success: function(response, status, jqXHR) {
        alert('Sucsses');
        var data = response[0];  // Here is your data.
    },
    error: function(jqXHR, status, error) {
        alert('error-inside');
        console.log(error);
    }
});

If you are looking for a purely Javascript way:

Or with Ionic as you mentioned:

3
  • 1
    Hi Boomer. Thank u for your answer. It works really well. Unfortunately I've been quite ill the past few days, so haven't had a chance to se this answer until now. Is there any way to award the bounty seeing that it has expired?
    – maGz
    Sep 7, 2016 at 9:38
  • @maGz I'm not sure other than talking to a moderator here, if its a big hassle no worries. Hope you're feeling better!
    – B00MER
    Sep 7, 2016 at 16:54
  • @Boomer, let me enquire
    – maGz
    Sep 7, 2016 at 17:21
0

This Might be helpful. Please take a look.

Magento XML Connect Demo

<?php
// Initialize
$app = new SimpleHttpClient('http://www.demo.local/xmlconnect/');
$app->addCookie('app_code', 'INSERT APP CODE HERE');
$app->addCookie('screen_size', '600x400');
// get products in category 3
echo "\n[REQUEST] Fetching product catalog...\n";
$response = $app->request('catalog/category/id/3/offset/0/count/100');
if ((string)$response->status == 'error') {
    echo "Error: " . (string)$response->text . "\n";
    exit(1);
}
$productId = (int)$response->xpath('/category/products/item[1]/entity_id')[0];
// add this product to the cart
echo "\n[REQUEST] Adding product $productId to cart...\n";
$response = $app->request('cart/add/product/' . $productId);
if ((string)$response->status != 'success') {
    echo "Error while adding product to cart";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
// get cart content and verify the item we just added is there
echo "\n[REQUEST] Fetching cart content...\n";
$cart = $app->request('cart');
if ((int)$cart->products->item[0]->entity_id != $productId) {
    echo "Could not find product in cart";
    exit(1);
}
echo "Verified that product is in cart now.\n";
// get billing address form fields
echo "\n[REQUEST] Getting billing address form fields...\n";
$response = $app->request('checkout/newBillingAddressForm');
foreach ($response->field as $field) {
    echo " - {$field['name']}\n";
}
$address = array(
    'firstname' => 'John',
    'lastname' => 'Doe',
    'email' => '[email protected]',
    'street' => array('Street 1'),
    'city' => 'San Francisco',
    'country_id' => 'US',
    'region_id' => '12', // California
    'postcode' => '94015',
    'telephone' => '4152300694',
    'fax' => '',
    'save_in_address_book' => ''
);
// billing address
echo "\n[REQUEST] Posting billing address...\n";
$response = $app->request('checkout/saveBillingAddress', 'POST', array('billing' => $address));
if ((string)$response->status != 'success') {
    echo "Error while saving billing address";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
// shipping address
echo "\n[REQUEST] Posting shipping address...\n";
$response = $app->request('checkout/saveShippingAddress', 'POST', array('shipping' => $address));
if ((string)$response->status != 'success') {
    echo "Error while saving shipping address";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
// get shipping methods
echo "\n[REQUEST] Fetching available shipping methods...\n";
$response = $app->request('checkout/shippingMethodsList');
$shippingMethods = array();
foreach ($response->method->rates->rate as $rate) {
    $shippingMethods[] = (string)$rate['code'];
    echo " - {$rate['code']}\n";
}
// save shipping method
echo "\n[REQUEST] Saving shipping method...\n";
$response = $app->request('checkout/saveShippingMethod', 'POST', array('shipping_method' => $shippingMethods[0]));
if ((string)$response->status != 'success') {
    echo "Error while saving shipping method";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
// get payment methods
echo "\n[REQUEST] Fetching available payment methods...\n";
$response = $app->request('checkout/paymentMethodList');
$paymentMethods = array();
foreach ($response->method_list->method as $method) {
    $paymentMethods[] = (string)$method['code'];
    echo " - {$method['code']}\n";
}
if (!in_array('checkmo', $paymentMethods)) {
    echo "This demo only supports 'checkmo'. Please enable 'Check / Money Order' in configuration.";
}
// save payment method
echo "\n[REQUEST] Saving payment method...\n";
$response = $app->request('checkout/savePayment', 'POST', array('payment' => array('method' => 'checkmo')));
if ((string)$response->status != 'success') {
    echo "Error while saving payment method";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
// order review
echo "\n[REQUEST] Fetching order review...\n";
$response = $app->request('checkout/orderReview');
echo "Products:\n";
foreach ($response->products->item as $item) {
    echo " - {$item->qty}x {$item->name}\n";
}
echo "Totals:\n";
foreach ($response->totals->children() as $total) {
    echo " - {$total->title}: {$total->formated_value}\n";
}
// place order
echo "\n[REQUEST] Place order...\n";
$response = $app->request('checkout/saveOrder', 'POST', array('payment' => array('method' => 'checkmo')));
if ((string)$response->status != 'success') {
    echo "Error while saving order";
    exit(1);
}
echo "Message: " . (string)$response->text . "\n";
echo "Order ID: " . (string)$response->order_id . "\n";
/**
 * Simple HTTP client for demonstration purposes
 *
 * @author Fabrizio Branca
 * @since 2015-05-21
 */
class SimpleHttpClient
{
    /**
     * @var array
     */
    protected $cookieJar = array();
    /**
     * @var string
     */
    protected $baseUrl;
    /**
     * @var resource
     */
    protected $ch;
    /**
     * Constructor
     *
     * @param string $baseUrl
     */
    public function __construct($baseUrl)
    {
        $this->baseUrl = rtrim($baseUrl, '/') . '/';
        $this->ch = curl_init();
    }
    /**
     * Request (and store cookies from response in cookie jar)
     *
     * @param string $url
     * @return SimpleXMLElement response
     */
    public function request($url, $method = 'GET', array $data = array())
    {
        $url = ltrim($url, '/');
        curl_setopt($this->ch, CURLOPT_URL, $this->baseUrl . $url);
        curl_setopt($this->ch, CURLOPT_HEADER, false);
        curl_setopt($this->ch, CURLOPT_COOKIE, $this->getCookieString());
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->ch, CURLOPT_HEADER, 1);
        if ($method == 'POST') {
            curl_setopt($this->ch, CURLOPT_POST, 1);
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        $response = curl_exec($this->ch);
        $header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $this->addCookiesToJarFromHeader($header);
        return simplexml_load_string($body);
    }
    /**
     * Add cookie
     *
     * @param string $name
     * @param string $value
     */
    public function addCookie($name, $value)
    {
        $this->cookieJar[$name] = $value;
    }
    /**
     * Extract cookies from header and add them to the cookie jar
     *
     * @param string $header
     */
    protected function addCookiesToJarFromHeader($header)
    {
        preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
        $cookies = array();
        foreach ($matches[1] as $item) {
            parse_str($item, $cookie);
            $cookies = array_merge($cookies, $cookie);
        }
        $this->cookieJar = array_merge($this->cookieJar, $cookies);
    }
    /**
     * Return all cookies as a string
     *
     * @return string
     */
    protected function getCookieString()
    {
        $tmp = array();
        foreach ($this->cookieJar as $name => $value) {
            $tmp[] = "$name=$value";
        }
        return implode('; ', $tmp);
    }
    /**
     * Destruct
     */
    public function __destruct()
    {
        curl_close($this->ch);
    }
}
2
  • Hi Bilal. Thank you, but I have seen this. However my issue is working with XmlConnect using Javascript.
    – maGz
    Aug 29, 2016 at 23:25
  • I must be missing something as I am really struggling to interact with XMLConnect...even for something as simple as fetching product data from a specified category :(
    – maGz
    Aug 30, 2016 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.