I want to fetch all products from Square Catalog.
Here is the code:
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::SANDBOX,
]);
//Providing SKU
$object_ids = ['GFLR20L', '232GGGD'];
$body = new \Square\Models\BatchRetrieveCatalogObjectsRequest($object_ids);
$body->setIncludeRelatedObjects(true);
$api_response = $client->getCatalogApi()->batchRetrieveCatalogObjects($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
Output:
object(Square\Models\BatchRetrieveCatalogObjectsResponse)#13 (3)
{
["errors":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["objects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["relatedObjects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
}
**> Post Suggestions by sjosey:
My PHP Code:
Looking for Products with name Paper in it.**
$object_types = ['ITEM'];
$prefix_query = new \Square\Models\CatalogQueryPrefix('name', 'paper');
$query = new \Square\Models\CatalogQuery();
$query->setPrefixQuery($prefix_query);
> Storing Values Here
$body = new \Square\Models\SearchCatalogObjectsRequest();
$body->setObjectTypes($object_types);
$body->setQuery($query);
$body->setLimit(100);
$api_response = $client->getCatalogApi()->searchCatalogObjects($body);
> Fetching the api response here
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
> Echo Result
var_dump($result);
Here is the output:
object(Square\Models\SearchCatalogObjectsResponse)#15 (5) { ["errors":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["cursor":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["objects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["relatedObjects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["latestTime":"Square\Models\SearchCatalogObjectsResponse":private]=> string(20) "1776-07-04T00:00:00Z" }
object_ids are not the same as SKU; they are unique generated ids on Square's side. You would want to use the SearchCatalogObjects (POST /v2/catalog/search) endpoint instead to search by SKU. An example query using one of your SKUs would be:
{
"query": {
"exact_query": {
"attribute_name": "sku",
"attribute_value": "GFLR20L"
}
}
}
This will get your catalog object ids, but if you're interested in the inventory you would still need to use another endpoint to get the inventory, such as RetrieveInventoryCount (which takes the catalog_object_id's as the parameter).
Figured out the solution. The following codes fetches a list of all the products by Product IDS. The array can be used to set data as per requirements (By SKU or Anything)
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::PRODUCTION,
]);
$bag = [];
$cursor = null;
$ctr = 1;
$api_response = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
$g1 = $result;
$g2 = json_encode($g1);
$g3 = json_decode($g2);
$cursor = $g3->cursor;
$objects = $g3->objects;
$g4 = json_encode($objects);
$g5 = json_decode($g4);
foreach($g5 as $g51){
$bag[$g51->id] = $g51;
}
while($cursor != null){
$api_response2 = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response2->isSuccess()) {
$result2 = $api_response2->getResult();
} else {
$errors2 = $api_response2->getErrors();
}
$g6 = $result2;
$g7 = json_encode($g6);
$g8 = json_decode($g7);
$cursor = $g8->cursor;
$objects2 = $g8->objects;
$g9 = json_encode($objects2);
$g10 = json_decode($g9);
foreach($g10 as $g101){
$bag[$g101->id] = $g101;
}
}
var_dump(count($bag));
Related
I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
I'm new in solr and I've been using this thread to do a atomic update
How do I update a document in Solr PHP?
Basically im doing an mysql query then update a document on solr
Question: How to do an atomic update where a specific field matches a field should be matched inside an if statement like this:
if(solr(username.field) == 'john'))
{
//execute atomic update
}
so far my code is messy like these:
$query = "SELECT * from User";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH,
);
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_assoc($result))
{
$querySearch = '+username:*'; //query all user that is on solr
$query = new SolrQuery();
$query->setQuery($querySearch);
$query->setStart(0);
$query->setRows(10000);
$client = new SolrClient($options);
$query_response = $client->query($query);
$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$response = $query_response->getResponse();
$doc = new SolrInputDocument();
$counter = $response->response->numFound;
for($x = 0; $x < $counter; $x++)
{
$doc = $response->response->docs[$x]->getInputDocument(); //this gets the old value (refer to thread)
$docs = $query_response->getResponse()->response->docs[$x]->username->values; //how I get the value of users
$second_doc = new SolrInputDocument();
if($docs == get_product($row['USERNAME']))
{
$second_doc->addField('points', $row['POINTS']); //this suppose to update my solr document with those username found
}
else
{
$second_doc->addField('points', "0");
}
$second_doc->merge($doc);
$updateResponse = $client->addDocument($second_doc);
$client->commit();
}
}
It should have been
if(!empty($response->response->docs[$x]->username->values[$x]) == get_product($row['USERNAME']))
{
$doc = $response->response->docs[$x]->getInputDocument();
$second_doc->addField('point', $row['POINT']);
}
else
{
//do other update here
}
//$response->response->docs[$x]->username->values[$x] => get the usernames in the document
I'm running a social network and right now my search.php shows results for people, and tags. How can I add an RSS Feed? I own a blog and I wanted to add my RSS Feed to the search so whenever someone searches for a topic it will show up on the search page.
Here's the search.php code:
$feed = new feed();
$feed->db = $db;
$feed->url = $CONF['url'];
if(isset($_SESSION['username']) && isset($_SESSION['password']) || isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$feed->user = $verify;
$feed->username = $verify['username'];
$feed->id = $verify['idu'];
if(isset($_GET['tag'])) {
$skin = new skin('shared/top'); $top = '';
$TMPL['theme_url'] = $CONF['theme_url'];
$TMPL['private_message'] = $verify['privacy'];
$TMPL['avatar'] = $verify['image'];
$TMPL['url'] = $CONF['url'];
$top = $skin->make();
}
}
}
$feed->per_page = $settings['perpage'];
$feed->time = $settings['time'];
$feed->censor = $settings['censor'];
$feed->smiles = $settings['smiles'];
$feed->c_per_page = $settings['cperpage'];
$feed->c_start = 0;
$feed->l_per_post = $settings['lperpost'];
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('shared/rows'); $rows = '';
if(empty($_GET['filter'])) {
$_GET['filter'] = '';
}
// Allowed types
if(isset($_GET['tag'])) {
// If the $_GET keyword is empty [hashtag]
if($_GET['tag'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$hashtags = $feed->getHashtags(0, $settings['qperpage'], $_GET['tag'], null);
$TMPL['messages'] = $hashtags[0];
} else {
// If the $_GET keyword is empty [user]
if($_GET['q'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['messages'] = $feed->getSearch(0, $settings['qperpage'], $_GET['q'], $_GET['filter']);
}
$rows = $skin->make();
$skin = new skin('search/sidebar'); $sidebar = '';
if(isset($_GET['tag'])) {
$TMPL['trending'] = $feed->sidebarTrending($_GET['tag'], 10);
} else {
$TMPL['genre'] = $feed->sidebarGender($_GET['filter'], $_GET['q']);
}
$TMPL['ad'] = generateAd($settings['ad6']);
$sidebar = $skin->make();
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['top'] = $top;
$TMPL['rows'] = $rows;
$TMPL['sidebar'] = $sidebar;
if(isset($_GET['logout']) == 1) {
$loggedIn->logOut();
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['url'] = $CONF['url'];
if(isset($_GET['tag'])) {
$TMPL['title'] = '#'.$_GET['tag'].' - '.$settings['title'];
} else {
$TMPL['title'] = $LNG['title_search'].' - '.$_GET['q'].' - '.$settings['title'];
}
$skin = new skin('shared/timeline_x');
return $skin->make();
Please help :)
Try this example
<?php
$articles = $pages->find('blog')->children()->visible()->flip()->limit(10);
snippet('feed', array(
'link' => url('blog'),
'items' => $articles,
'descriptionField' => 'text',
'descriptionLength' => 300
));
?>
link:
This is the main link in our feed, which takes the visitor back to our site. In this case we want them to get back to our blog, so we build an url to our blog with the url() helper function.
items:
As items for our feed, we pass the set of $articles we found in the first line. The feed snippet will automatically take care of getting the right info out of those $articles (like title, url, etc.)
descriptionField:
If you want to show a description for each item in your feed, you need to specify a field, which is available in any item and should be used for the description.
descriptionLength:
This is maximum number of characters the description will have. An excerpt is automatically generated by the feed snippet.
I'm using these two methods to create orders programmatically in Magento.
The first one creates a Quote:
public function prepareCustomerOrder($customerId, array $shoppingCart, array $shippingAddress, array $billingAddress,
$shippingMethod, $couponCode = null)
{
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$storeId = $customerObj->getStoreId();
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeObj = $quoteObj->getStore()->load($storeId);
$quoteObj->setStore($storeObj);
// add products to quote
foreach($shoppingCart as $part) {
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->setStore($storeId)->setStoreId($storeId)->load($part['PartId']);
$productObj->setSkipCheckRequiredOption(true);
try{
$quoteItem = $quoteObj->addProduct($productObj);
$quoteItem->setPrice(20);
$quoteItem->setQty(3);
$quoteItem->setQuote($quoteObj);
$quoteObj->addItem($quoteItem);
} catch (exception $e) {
return false;
}
$productObj->unsSkipCheckRequiredOption();
$quoteItem->checkData();
}
// addresses
$quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
$quoteShippingAddress->setData($shippingAddress);
$quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setShippingAddress($quoteShippingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);
// coupon code
if(!empty($couponCode)) $quoteObj->setCouponCode($couponCode);
// shipping method an collect
$quoteObj->getShippingAddress()->setShippingMethod($shippingMethod);
$quoteObj->getShippingAddress()->setCollectShippingRates(true);
$quoteObj->getShippingAddress()->collectShippingRates();
$quoteObj->collectTotals(); // calls $address->collectTotals();
$quoteObj->setIsActive(0);
$quoteObj->save();
return $quoteObj->getId();
}
And the second one uses that Quote to create Order:
public function createOrder($quoteId, $paymentMethod, $paymentData)
{
$quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if ($paymentData) {
$orderObj->getPayment()->setCcNumber($paymentData->ccNumber);
$orderObj->getPayment()->setCcType($paymentData->ccType);
$orderObj->getPayment()->setCcExpMonth($paymentData->ccExpMonth);
$orderObj->getPayment()->setCcExpYear($paymentData->ccExpYear);
$orderObj->getPayment()->setCcLast4(substr($paymentData->ccNumber,-4));
}
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
try {
$orderObj->place();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
$orderObj->save();
//$orderObj->sendNewOrderEmail();
return $orderObj->getId();
}
The process works fine, no errors, and the order is created. But the total is 0 and there are no products in it no matter what I put.
I've traced it and I can confirm that the rows are added to the sales_flat_quote and sales_flat_quote_item tables, so that is ok. But when running the createOrder and calling
$items = $quoteObj->getAllItems();
an empty array is always returned, and I have no idea why. I have configurable and simple products in my shop. This happens when I add simple, when I add configurable the error appears as the method
$quoteItem = $quoteObj->addProduct($productObj);
returns null.
It seems to me, you didn't load product collection, therefore, the cart always return empty. Try this link, it will give you more clear help. Create order programmatically
// this is get only one product, you can refactor the code
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
// load product data
$this->_product->load($this->_product->getId());
This code worked for me,
public function createorder(array $orderdata)
{
$quoteId = $orderdata['quoteId'];
$paymentMethod = $orderdata['paymentMethod'];
$paymentData = $orderdata['paymentData'];
$quoteObj = Mage::getModel('sales/quote')->load($quoteId);
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
$quotePaymentObj = $quoteObj->getPayment();
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
foreach ($items as $item)
{
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()))
{
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options'))
{
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options)
{
$orderItem->setProductOptions($options);
}
if ($item->getParentItem())
{
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$quoteObj->collectTotals();
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
$orderObj->setCanShipPartiallyItem(false);
try
{
$last_order_increment_id = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
return $last_order_increment_id;
}
catch (Exception $e)
{
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
return "Exception:".$e;
} }
I had the same problem and delved into the API to find a solution. I changed the way that I loaded a product by using :
$productEntityId = '123456';
$store_code = 'my_store_code';
$product = Mage::helper('catalog/product')->getProduct($productEntityId,Mage::app()->getStore($store_code)->getId());
I found this tutorial to be very useful too :
http://www.classyllama.com/content/unravelling-magentos-collecttotals
If you are looking for a script on order creation this is a very good start :
http://pastebin.com/8cft4d8v
Hope that this helps someone ;)