I have been fighting with the Magento SOAP web service for a week and I can not figure out why I can not create a product using the API.
Below is my PHP code:
$client = new SoapClient('http://mywebsie.com/wp/store/api/soap/?wsdl');
// If some stuff requires api authentification,
// then get a session token
$session = $client->login('apiuser', 'apikey');
// get attribute set
$attributeSets = $client->call($session, 'product_attribute_set.list');
$attributeSet = current($attributeSets);
$newProductData = array(
'name' => 'Test product',
'websites' => array(1),
'short_description' => 'This is the short desc',
'description' => 'This is the long desc',
'price' => 150.00,
'status' => 1,
'tax_class_id' => 0,
'visibility' => 4
);
try {
// product creation
$client->call($session, 'product.create', array('simple', $set['set_id'], $ItemNmbr, $newProductData));
}
catch(SoapFault $e)
{
$msg = "Error in inserting product with sku $ItemNmbr : ".$e->getMessage();
echo $msg;
}
I am getting the following error:
Error in inserting product with sku ING-ACCS-00009 : Invalid data given. Details in error message.
I think you got this code from http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalogProduct.html. There are some bugs. Here is a fixed version:
$client = new SoapClient('http://mywebsie.com/wp/store/api/soap/?wsdl');
// If some stuff requires api authentification,
// then get a session token
$session = $client->login('apiuser', 'apikey');
$newProductData = array(
'name' => 'Test product',
'websites' => array(1),
'short_description' => 'This is the short desc',
'description' => 'This is the long desc',
'price' => 150.00,
'status' => 1,
'tax_class_id' => 0,
'url_key' => 'product-url-key',
'url_path' => 'product-url-path',
'visibility' => '4',
);
$sku = 'Some unique sku';
$storeView = 1;
$attributeSetId = 4; // you can get this id from admin area
$productType = 'simple';
try {
// product creation
$client->call($session, 'catalog_product.create', array($productType, $attributeSetId, $sku, $newProductData, $storeView));
} catch (SoapFault $e) {
echo "Error in inserting product with sku $sku : " . $e->getMessage();
}
For Soap v2 this worked for me.
$client = new SoapClient('http://localhost/index.php/api/v2_soap/?wsdl'); // TODO : change url
$sessionId = $client->login('youruser', 'yourpasswd');
$attributeSets = $client->catalogProductAttributeSetList($sessionId);
$attributeSet = current($attributeSets);
$sku = 'COD002';
//catalogProductCreate( sessionId, type, setId, sku, productData, storeView )
try {
$result = $client->catalogProductCreate($sessionId, 'simple', $attributeSet->set_id, $sku, array(
'categories' => array(2),
'websites' => array(1),
'name' => 'producto de prueba',
'description' => 'Product description',
'short_description' => 'Product short description',
'weight' => '10',
'status' => '1',
'url_key' => 'product-url-key',
'url_path' => 'product-url-path',
'visibility' => '4',
'price' => '100',
'tax_class_id' => 1,
'meta_title' => 'Product meta title',
'meta_keyword' => 'Product meta keyword',
'meta_description' => 'Product meta description',
'stock_data' => array(
'qty' => '49',
'is_in_stock' => 1
)
),1);
$result2 = $client->catalogProductList($sessionId);
echo "<pre>";
print_r($result2);
echo "</pre>";
} catch (SoapFault $e) {
echo "Error in inserting product with sku $sku : " . $e->getMessage();
}
Related
I am using Laravel push notification library, for pushing notification.
However, i can easly get responses for GCM responses for Android Device.
But unable to get APNS response.
$message = PushNotification::Message("New Messages",$params['payload']);
$collection = PushNotification::app('appNameIOS')
->to($params['reg_id'])
->send($message);
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}
Make sure you have followed proper format as below:-
//iOS app
PushNotification::app(['environment' => 'development',
'certificate' => '/path/to/certificate.pem',
'passPhrase' => 'password',
'service' => 'apns']);
$devices = PushNotification::DeviceCollection(array(
PushNotification::Device('token', array('badge' => 5)),
PushNotification::Device('token1', array('badge' => 1)),
PushNotification::Device('token2')
));
$message = PushNotification::Message('Message Text',array(
'badge' => 1,
'sound' => 'example.aiff',
'actionLocKey' => 'Action button title!',
'locKey' => 'localized key',
'locArgs' => array(
'localized args',
'localized args',
),
'launchImage' => 'image.jpg',
'custom' => array('custom data' => array(
'we' => 'want', 'send to app'
))
));
$collection = PushNotification::app('appNameIOS')
->to($devices)
->send($message);
// get response for each device push
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}
I'm using code below to POST a product to Magento which works fine however I need know how to assign the product to a specific category. Anyone knows a solution?
Thanks in advance.
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$productData = json_encode(array(
'type_id' => 'simple',
'attribute_set_id' => 4,
'sku' => 'simple' . uniqid(),
'weight' => 1,
'status' => 1,
'visibility' => 4,
'name' => 'Name of the product',
'description' => 'Description',
'short_description' => 'Short Description',
'price' => 6.99,
'tax_class_id' => 0
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
Solved. This goes after adding the products into magento process.
$productId = 100; //Extracted from the previous response
$categoryId = 4;
$resourceUrl = "$apiUrl/products/$productId/categories";
$productData = json_encode(array('category_id' => $categoryId));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
$response = $oauthClient->getLastResponseInfo();
Hi I have a cart in Codeigniter that works well. I tried to look for a discount/coupon handling but can't.
This is my cart code:
public function addToCart($id){
$this->load->model('products_model');
$products = $this->products_model->getItemDetail($id);
foreach ($products as $product) {
$insert = array(
'id' => $product->id,
'name' => $product->name,
'qty' => '1',
'price' => $product->item_eur,
'image' => $product->image,
'options' => array(
'info' => $product->cart_description,
'qty_description' => $product->qty_description
)
);
$this->cart->insert($insert);
}
$last = end($this->cart->contents());
echo $last['rowid'];
}
I thought of making a Coupon Code read from the DB and insert a discount as an item in the cart:
public function addCoupon(){
$this->load->model('products_model');
$res = $this->products_model->getCoupon($_POST['value']);
if($res){
foreach($res as $result){
$coupon = array(
'id' => $result->id,
'name' => $result->name,
'qty' => '1',
'price' => $result->discount,
'options' => array(
'info' => 'coupon',
'qty_description' => ''
)
);
$this->cart->insert($coupon);
}
echo '1';
}else{
$this->lang->load('products');
echo $this->lang->line('cart_notok');
}
}
Where the DB is
[name:type] (example)
id:int (1)
name: varchar ('Discount of 20€')
code: varchar ('AFD1234')
discount: decimal (-20)
[Edit]
And the model:
public function getCoupon($code){
$results = $this->db->get_where('coupons', array('code' => $code));
return $results->result();
}
The item gets added to the cart but if the 'price' => $result->discount is set to -20 or a percentage it gets set as +20€ and not -20€.
Any way to do this?
Could you tell me how can I create Order using magento v2_soap api?
It's not possible with default single api you need to create you own custom api
OR
You need to call multiple api to place order as follows -
$proxy = new SoapClient('http://mywebside.com/api/v2_soap/?wsdl');
$sessionId = $proxy->login($user, $password);
$cartId = $proxy->shoppingCartCreate($sessionId, 1);
// load the customer list and select the first customer from the list
//$customerList = $proxy->customerCustomerList($sessionId, array());
//$customer = (array) $customerList[188];
//Do not change this credentials
$customer['customer_id'] = 199; // customer id
$customer['created_at'] = '2016-02-03 19:24:41';
$customer['updated_at'] = '2016-04-22 03:33:33';
$customer['store_id'] = 1;
$customer['website_id'] = 1;
$customer['created_in'] = 'Default Store View';
$customer['email'] = 'test#gmail.com';
$customer['firstname'] = 'test';
$customer['lastname'] = 'test';
$customer['group_id'] = 1;
$customer['password_hash'] = 'assassaXXXXO';
$customer['mode'] = 'customer';
$proxy->shoppingCartCustomerSet($sessionId, $cartId, $customer);
// load the product list and select the first product from the list
//$productList = $proxy->catalogProductList($sessionId);
// $product = (array) $productList[0];
$product= array(array(
'product_id' => '43001',
'sku' => 'SKU420',
'qty' => '2',
),
array(
'product_id' => '43002',
'sku' => 'SKUZ42B2',
'qty' => '1',
));
try{
$proxy->shoppingCartProductAdd($sessionId, $cartId, $product);
} catch (SoapFault $e) {
$error['product'] = $e->getMessage();
}
$address = array(
array(
'mode' => 'shipping',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => '',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
array(
'mode' => 'billing',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => '',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
);
// add customer address
try{
$proxy->shoppingCartCustomerAddresses($sessionId, $cartId, $address);
} catch (SoapFault $e) {
$error['shipping'] = $e->getMessage();
}
try{
// add shipping method
$proxy->shoppingCartShippingMethod($sessionId, $cartId, 'freeshipping_freeshipping');
} catch (SoapFault $e) {
$result = $e->getMessage();
}
// add payment method
enter code here
$paymentMethod = array(
'method' => 'cashondelivery'
);
$proxy->shoppingCartPaymentMethod($sessionId, $cartId, $paymentMethod);
// place the order
$orderId = $proxy->shoppingCartOrder($sessionId, $cartId, null, null);
There is a cart object where you can attach a customer and products.
information on cart_product.add (SOAP v1) or shoppingCartProductAdd (SOAP v2) is in Magento API documenattion
http://www.magentocommerce.com/api/soap/checkout/cartProduct/cart_product.add.html
I need to create a simple webpage that gets rate quotes from FedEx. Only thing is, I've never messed with an API before.
The XML is easy, but how do I send that XML to FedEx and view the response? API Request... Yes I know, but what is the code for an API request to FedEx? I just need some guidance. I know PHP to an extent - but, I'm no expert.
I understand that I need to send an API request but I need a simple working example using PHP. I want to be able to input my account information and then have a simple working rate quote.
I don't care if it only returns the simplest data. I just need to have something to get me started.
It seems as if FedEx only goes so far in providing information for doing this with PHP.
fedex offers acceleration packages in www.fedex.com/us/developer/ , you will find information about different types of calls to their webservices. as an example if you want to request a rate from fedex you will need to do something like this:
<?php
require_once('../../library/fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../../wsdl/RateService_v13.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v13 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '13',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array('Ammount'=>100,'Currency'=>'USD');
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT';
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}
else
{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US')
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75');
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array('Currency' => 'USD', 'Amount' => 150),
'CollectionType' => 'ANY')// ANY, GUARANTEED_FUNDS
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>
so go to fedex.com, download wsdl or xml with library and more. run this code and you will receive a quote. important to say that you need an account to access that area, where you will receive a test meter-account to try, and then move to production.. hope it helps.