How can we check by code in Opencart 2.0.3 that Cart contains Gift Certificate?
I want to disable cash on delivery (cod) payment mode if cart has Gift Certificate (opencart 2.0.3). Any code or idea to achieve this?
Yes you can do that , In products you can set a status that you product is Gift Certificate or not , after that some case will arrive while order:
Customer can order products with Gift Certificate so you have to check if any product is with Gift Certificate status that shipped will not be COD
You can edit the cod.php model (catalog/model/payment/cod.php) and add condition if gift certificates exist.
Do you mean "voucher" with "gift certificate"
This is the actual model
<?php
class ModelPaymentCOD extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/cod');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cod_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('cod_total') > 0 && $this->config->get('cod_total') > $total) {
$status = false;
} elseif (!$this->config->get('cod_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'cod',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('cod_sort_order')
);
}
return $method_data;
}
}
You can add this condition:
if(isset($this->session->data['vouchers'])){
$status = false;
}
It works for me.
If you don't have experience with php replace the code from file with this :
<?php
class ModelPaymentCOD extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/cod');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cod_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('cod_total') > 0 && $this->config->get('cod_total') > $total) {
$status = false;
} elseif (!$this->config->get('cod_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
if(isset($this->session->data['vouchers'])){
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'cod',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('cod_sort_order')
);
}
return $method_data;
}
}
Related
So I am trying to manually update the Subscription Dates and show a notice on the for the subsrriptions here. The goal is to make all the subscriptions trigger on the 1st of every month let's say.
So in the wp_posts meta we have post_date and post_date_gmt
class ChiChi_SubscriptionMetaBoxes
{
/**
* To load Schedule meta box
* */
public static function redateSchedule()
{
add_meta_box('chichi-redate-schedule', _x('Redate Schedule', 'meta box title'), 'ChiChi_SubscriptionMetaBoxes::output', 'shop_subscription', 'side', 'default');
}
/**
* To display Redate Schedule
*
* #param object $post
* */
public static function output($post)
{
global $theorder;
if (wcs_is_subscription($theorder) && !$theorder->has_status(wcs_get_subscription_ended_statuses())) {
include(get_theme_file_path('/lib/woocommerce/templates/html-redate-schedule.php'));
}
}
public static function save($order_id)
{
global $wpdb;
if (!isset($_POST['redate_schedule_date_nonce']) || !isset($_POST['redate_schedule'])) {
return $order_id;
}
$nonce = $_REQUEST['redate_schedule_date_nonce'];
if (!is_numeric($_POST['redate_schedule'])) {
return $order_id;
}
$newDay = (int)$_POST['redate_schedule'];
//Verify that the nonce is valid.
if (!wp_verify_nonce($nonce) || wp_is_post_revision($order_id)) {
return $order_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $order_id;
}
// Check the user's permissions.
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $order_id)) {
return $order_id;
}
} else {
if (!current_user_can('edit_post', $order_id)) {
return $order_id;
}
}
// Update the meta field in the database.
$subscription = wcs_get_subscription($order_id);
$pending_status = 'pending';
if (class_exists('ActionScheduler_Store')) {
$pending_status = ActionScheduler_Store::STATUS_PENDING;
}
$amSchedule = '_action_manager_schedule';
try {
$redatedShedule = [];
$schedules = as_get_scheduled_actions([
'hook' => 'woocommerce_subscription_upfront_renewal',
'args' => [
'subscription_id' => $subscription->get_id()
],
'status' => $pending_status,
'per_page' => 100
]);
if (!empty($schedules)) {
foreach ($schedules as $key => $schedule) {
$scheduledPost = get_post($key);
if (!empty($scheduledPost)) {
$originalDateTs = strtotime($scheduledPost->post_date);
$originalGmtDateTs = strtotime($scheduledPost->post_date_gmt);
$newDate = date("Y-m-" . $newDay . " H:i:s", $originalDateTs);
$gmtDate = get_gmt_from_date($newDate);
// Update Post
wp_update_post([
'ID' => $key,
'post_date' => $newDate,
'post_date_gmt' => $gmtDate
]);
// Update meta time stamps
$sql = "UPDATE " . $wpdb->postmeta . " SET meta_value = REPLACE(meta_value, '" . $_schedule_start . "', '" . strtotime($gmtDate) . "') WHERE `post_id` = '" . esc_sql($key) . "' AND `meta_key` = '" . $wpdb->escape($amSchedule) . "'";
$wpdb->get_results($sql);
$redatedShedule[] = $gmtDate;
}
}
if (count($redatedShedule) > 0) {
// Update End Date
$dates['end'] = date('Y-m-d H:i:s', strtotime(end($redatedShedule) . '+1 month'));
$subscription->update_dates($dates);
$order = new WC_Order($order_id);
$order->add_order_note("Subscription has been manually re-dated to: <br/>" . implode('<br>', $redatedShedule));
}
}
return $order_id;
// wp_cache_delete($post_id, 'posts');
} catch (Exception $e) {
wcs_add_admin_notice($e->getMessage(), 'error');
}
}
}
add_action('add_meta_boxes', 'ChiChi_SubscriptionMetaBoxes::redateSchedule', 26);
add_action('woocommerce_before_save_order_items', 'ChiChi_SubscriptionMetaBoxes::save', 10, 1);
let me know please if someone spots any issue. The code itself is commented so you know what the specific sections of code are doing.
thanks
I have Yii2 project. And there I also have api written by Symfony.
In Symfony part I have method in the class which send request to Yii controller.
$buzz = $this->container->get('buzz');
$buzz->getClient()->setVerifyHost(false);
$buzz->getClient()->setVerifyPeer(false);
$buzz->getClient()->setTimeOut(false);
$url = $this->container->getParameter('integra_sync_prices');
$sendResult = $buzz->post($url, array('authorization' => $this->container->getParameter('load_token')), array('products' =>
json_encode($productPrices)));
$resultJson = json_decode($sendResult->getContent(), true);
if (isset($resultJson['error']))
throw new \Exception('Site: '.$resultJson['error'], 500);
class IntegraController extends Controller{
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$headers = Yii::$app->request->getHeaders();
foreach ($headers as $key => $value) {
if(strtolower(trim($key)) == 'authorization') {
$token = trim($value[0]);
break;
}
}
$products = json_decode(Yii::$app->request->post('products'));
$post_products = Yii::$app->request->post('products');
if('111' == $token) {
if(isset($post_products) && $products) {
foreach ($products as $product) {
echo $product->price." = ".$product->productId."<br>";
Yii::$app->db->createCommand("UPDATE oc_product SET quantity = '" . (int)$product->quantity . "', price = '" . (float)$product->price . "' WHERE product_id = '" . (int)$product->productId . "'")->execute();
}
$json['success'] = 'complete';
} else {
$json['error'] = 'empty data';
}
} else {
$json['error'] = 'authorization error';
}
Yii::$app->controller->enableCsrfValidation = false;
echo json_encode($json);
}
I expect that data in my database will be updated by this controller. But there in nothing changes.
What do I do wrong? Maybe I should send some another headers? Thanks a lot )
please see the demo problem at Here i have created my own plugin that can make the video be seen when user share the video. I have made three files , one is hook, the next one is class and other one is for update. My plugins 99% function works here. see
<?php
class VideoLock {
protected static $running = false;
const PLUGIN_PREFIX = "VL";
const SLUG = 'videolock';
protected $sharesTableName;
protected $viewsTableName;
protected $_key;
public function __construct() {
//create the correctly prefixed table name
global $wpdb;
$this->sharesTableName = $wpdb->prefix."videolock_shares";
$this->viewsTableName = $wpdb->prefix."videolock_views";
}
public function tinymceShortcodePlugin($plugin_array) {
$plugin_array['videolock'] = $this->file('/assets/js/shortcodeplugin.js');
return $plugin_array;
}
public function tinymceShortcodeButton($buttons) {
array_push($buttons, "separator", "videolock");
return $buttons;
}
public function init() {
if ( ( current_user_can('edit_posts') || current_user_can('edit_pages') ) &&
get_user_option('rich_editing') ) {
//register admin editor shortcode creator
add_filter("mce_external_plugins", $this->callback('tinymceShortcodePlugin'));
add_filter('mce_buttons', $this->callback('tinymceShortcodeButton'));
}
//register admin tinymce shortcode insert plugin
wp_enqueue_style($this->prefix('locker-style'), $this->file('/assets/css/blocker.css'));
wp_enqueue_script($this->prefix('locker-script'), $this->file('/assets/js/blocker.js?v=2'),
array('jquery','swfobject'));
//enqueue swfobject if not present
if( wp_script_is('swfobject') ) {
wp_enqueue_script('swfobject', $this->file('/assets/js/swfobject.js'));
}
//register plugin options
add_option('facebook-id');
add_option('share-message', 'Unlock this video by sharing it on facebook !');
add_option('video-size', '560x315');
new VideoLockUpdate( $this->getKey() );
}
public static function getVersion() {
$file = dirname(__FILE__) . '/version';
if( file_exists($file)) {
return trim(file_get_contents($file));
}
return '0';
}
public function getKey() {
if( $this->_key ) {
return $this->_key;
}
$file = dirname(__FILE__) . '/licence.php';
if( file_exists($file)) {
include $file;
$this->_key = defined('VIDEOLOCK_LICENCE_KEY') ? VIDEOLOCK_LICENCE_KEY : null;
return $this->_key;
}
return false;
}
public function install() {
global $wpdb;
$key = $this->getKey();
if( !$key ) {
wp_die('Fail to activate this plugin. You need a valid licence key for activation. For more informations contact us at support#wpvideolock.com or the online form<br/>If you bought this plugin, please send your email address used for buying the plugin to resend a functional version.<br/>Thank you!');
}
$request = wp_remote_post('http://update.wpvideolock.com/', array('body' => array('action' => 'validate-key', 'key'=>$key)));
if (!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) {
$response = trim($request['body']);
if( $response != 'ok' ) {
wp_die($response);
}
}
update_option('facebook-id', '');
update_option('share-message', 'Share on facebook to unlock this video .');
update_option('video-size', '560x315');
if(!in_array($this->sharesTableName,$wpdb->tables())) {
$sql = "CREATE TABLE `" . $this->sharesTableName . "` (
id INT(11) NOT NULL AUTO_INCREMENT,
url VARCHAR(255) NOT NULL,
ip VARCHAR(40) NOT NULL,
post INT(11) NOT NULL,
time DATETIME,
`share_id` VARCHAR( 255 ) NOT NULL,
`gender` ENUM( 'female', 'male' ),
PRIMARY KEY ( id )
)";
$wpdb->query($sql);
}
if(!in_array($this->viewsTableName,$wpdb->tables())) {
$sql = "CREATE TABLE IF NOT EXISTS `" . $this->viewsTableName . "` (
`post_id` int(11) NOT NULL,
`views` int(11) NOT NULL,
`date` date NOT NULL,
UNIQUE KEY `post_id` (`post_id`,`date`)
)";
$wpdb->query($sql);
}
}
public function uninstall() {
global $wpdb;
$backup = false; // Take it from options after user change settings for the plugin to create backup
if( $backup ) {
$sql = "SELECT * FROM `" . $this->sharesTableName . "`";
$results = $wpdb->get_results($sql);
if( count($results) ) {
$uploads_dir = wp_upload_dir();
$backup_file = $uploads_dir['basedir'].'/videolock_backup.txt';
file_put_contents($backup_file,serialize($results));
}
}
$wpdb->query("DROP TABLE `" . $this->sharesTableName . "`");
$wpdb->query("DROP TABLE `" . $this->viewsTableName . "`");
delete_option('facebook-id', '');
delete_option('share-message', 'Share on facebook to unlock this video .');
delete_option('video-size', '560x315');
}
public function getYoutubeId( $url ) {
$url = strip_tags($url);
$url = parse_url($url);
$query = $url['query'];
//If video is in a format like this
// http://www.youtube.com/watch?v=fKmuUDQdcXc
if($query) {
$id = str_replace("v=","",$query);
return $id;
}
//if video is in a format like this
// http://youtu.be/fKmuUDQdcXc
else {
$path = $url['path'];
$id = str_replace("/","",$path);
return $id;
}
}
public function shortcode( $atts ) {
global $wpdb;
//extract attributes to function scope
extract( shortcode_atts( array(
'url' => false,
'id' => false,
'width' => '420',
'height' => '315',
'expire' => 0,
'message' => get_option('share-message'),
), $atts ) );
//do not show anything if to id or url
if( $url === false && $id === false ) {
return null;
}
//extract the video id in case url is passed
if( $url ) {
$id = $this->getYoutubeId($url);
}
$image = 'http://img.youtube.com/vi/' . $id . '/0.jpg';
$view = new View( dirname(__FILE__) . '/views/blocker.php' );
$view->image = $image;
$view->id = $id;
$view->url = $url;
$view->width = $width;
$view->height = $height;
$view->message = $message;
$view->expire = $expire;
//if there werent any views today insert it
//else increment it
$sql = "INSERT INTO `" . $this->viewsTableName . "`
(`post_id`,`views`,`date`)
VALUES
('" . get_the_ID() . "',1,CURDATE())
ON DUPLICATE KEY UPDATE views=views+1;";
$wpdb->query($sql);
$view->helper('isLocked', $this->callback('isLocked'));
return $view->render();
}
public function actionLinks( $links, $file ) {
$url = admin_url( 'admin.php?page=videolock/dashboard.php' );
if ( $file == plugin_basename( dirname(__FILE__).'/videolock.php' ) ) {
$links[] = ''.__( 'Dashboard' ).'';
}
return $links;
}
public function isLocked( $postid = null ) {
global $wpdb;
$postid = is_numeric($postid) ? $postid : get_the_ID();
$sql = "SELECT COUNT(*) AS total FROM `" . $this->sharesTableName . "` WHERE `post`=%d AND `ip`=%s AND `url`=%s LIMIT 1";
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$sql = $wpdb->prepare($sql, $postid, $_SERVER['REMOTE_ADDR'], $url);
$result = $wpdb->get_results($sql);
if( isset($result[0]) ) {
return $result[0]->total == '0';
}
return true;
}
public function share() {
global $wpdb; // this is how you get access to the database
$url= $wpdb->escape($_POST['link']);
$ip = $_SERVER['REMOTE_ADDR'];
$postId = intval($_POST['post']);
$share = $_POST['share'];
$gender = null;
$share_parts=explode('_', $share);
if(count($share_parts)) {
$share_user = $share_parts[0];
if($share_user) {
try {
$user_data = json_decode(#file_get_contents('http://graph.facebook.com/' . $share_user));
$gender = isset($user_data->gender) ? $user_data->gender : null;
}catch(Exception $e) {}
}
}
$result = $wpdb->insert($this->sharesTableName,array(
'url' => $url,
'ip' => $ip,
'post' => $postId,
'time' => current_time('mysql', 1),
'share_id' => $share,
'gender' => $gender
));
echo $result ? '1':'0';
die();
}
public function shareLogged() {
//not implemented yet for logged users
$this->share();
}
public function queueAdminScripts() {
wp_localize_script( $this->prefix('blocker-jsobj'), 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
wp_enqueue_script($this->prefix('dashboard-script'), $this->file('/assets/js/dashboard.js'), array('jquery', $this->prefix('flot')));
wp_enqueue_script($this->prefix('flot'), $this->file('/assets/js/flot/jquery.flot.js'));
wp_enqueue_script($this->prefix('flot.time'), $this->file('/assets/js/flot/jquery.flot.time.js'));
}
public function createDashboard() {
global $wpdb;
$sql = "SELECT SUM(views) as views, post_id FROM `" . $this->viewsTableName . "` GROUP BY post_id";
$postsViews = $wpdb->get_results($sql);
wp_enqueue_style($this->prefix('fresh'), '/wp-admin/css/colors-fresh.min.css?ver=3.7.1');
wp_enqueue_style($this->prefix('dashboard-theme'), $this->file('/assets/css/dashboard.css'));
include dirname(__FILE__) . '/views/dashboard.php';
}
public function createAdminMenu() {
$menu_icon = $this->file('/assets/images/logo.png');
$content_callback = $this->callback('createDashboard');
//add admin left pannel menu
add_menu_page( __('Video Lock'),
__('Video Lock'),
__('manage_options'),
'videolock/dashboard.php', $content_callback , $menu_icon );
}
private function _getShares($post,$date) {
global $wpdb;
//get timestamp from date
$timestamp = strtotime($date);
//calculate start and end of the day
$startTime = date('Y-m-d 00:00:00',$timestamp);
$endTime = date('Y-m-d 23:59:59',$timestamp);
//select the shares for the day of the timestamp
$sql = "SELECT COUNT(*) as shares FROM `" . $this->sharesTableName . "`
WHERE `post` = %d AND `time` BETWEEN '$startTime' AND '$endTime'";
$sql = $wpdb->prepare($sql, $post);
$result = $wpdb->get_results($sql);
if( isset($result[0]) ) {
return $result[0]->shares;
}
else return 0;
}
public function shareStats() {
global $wpdb;
$response = array();
$postId = $_POST['post'];
//get views per day
$sql = "SELECT views,`date` AS `date` FROM `" . $this->viewsTableName . "` WHERE `post_id`=%d";
$sql = $wpdb->prepare($sql, $postId);
$dates = $wpdb->get_results($sql);
$today = date('Y-m-d');
$hasToday = false;
//generate response
foreach($dates as $date) {
//check if today exists (if not we can add it later)
if($date->date == $today) {
$hasToday = true;
}
$jsDate = strtotime($date->date)*1000;
$response['views'][] = array($jsDate ,$date->views);
$response['shares'][] = array($jsDate , $this->_getShares( $postId, $date->date ));
}
//if we don't have today,
//add it as 0 to the graph
if(!$hasToday) {
$today = strtotime($today) * 1000;
$response['views'][] = array( $today , 0 );
$response['shares'][] = array( $today , 0 );
}
echo json_encode($response);
exit();
}
public function saveSettings() {
$settings = $_POST['data'];
update_option('facebook-id', $settings[0]['value']);
update_option('share-message', $settings[1]['value']);
update_option('video-size', $settings[2]['value']);
if($settings[2]['value'] == 'custom') {
update_option('video-width', $settings[3]['value']);
update_option('video-height', $settings[4]['value']);
}
else {
delete_option('video-height');
delete_option('video-width');
}
}
private function _noFacebookId(){
$facebookId = get_option('facebook-id');
if(empty($facebookId) || !$facebookId )
return true;
else
return false;
}
function adminNotice() {
echo '<div class="updated">
<p>You have successfully installed WordPress Video Lock Plugin.
Please take a minute to add your facebook API key and get started</p>
</div>
';
}
private function file( $name ) {
if( strpos($name, '/') !== 0 ) {
$name = '/' . $name;
}
return plugins_url() . '/videolock' . $name;
}
private function prefix( $string ) {
return VideoLock::PLUGIN_PREFIX . $string;
}
private function callback($method) {
return array($this, $method);
}
public function run() {
if( self::$running ) {
throw new Exception("The Youtube Locker already running!");
}
//get the plugin script name for install/uninstall hooks
$pluginFile = dirname(__FILE__) . '/videolock.php';
//installation / dezinstalation hooks
register_activation_hook( $pluginFile, $this->callback('install') );
register_deactivation_hook( $pluginFile,$this->callback('uninstall') );
//short codes
add_shortcode( 'youtubelocker', $this->callback('shortcode') );
add_shortcode( 'videolock', $this->callback('shortcode') );
//filters
add_filter('plugin_action_links', $this->callback('actionLinks'), 10, 2 );
//add ajax callback
add_action('wp_ajax_nopriv_video_share',$this->callback('share') );
add_action('wp_ajax_video_share', $this->callback('shareLogged') );
add_action('wp_ajax_videolock_save_settings', $this->callback('saveSettings') );
add_action('wp_ajax_videolock_share_stats', $this->callback('shareStats'));
add_action('admin_enqueue_scripts', $this->callback('queueAdminScripts') );
add_action('admin_menu', $this->callback('createAdminMenu') );
if($this->_noFacebookId()) {
add_action('admin_notices', $this->callback('adminNotice') );
}
add_action('init', $this->callback('init'), 0);
self::$running = true;
}
}
But somehow it's not working as expected. When user first share the video it works like charm but it makes error when the same user share another. it doesnt open the sharer.php it opens a fb dialog box and load for infinity time. I hope you guys can help me to solve that. FYI after the completation of the plugin the plugin will be freeware in wp.org
I am trying to download all my listings from ebay into my database using following code:
$client = new eBaySOAP($session);
$ebay_items_array = array();
try {
$client = new eBaySOAP($session);
$params = array(
'Version' => $Version,
'GranularityLevel' => "Fine",
'OutputSelector' => "ItemID,SKU,Title",
'EndTimeFrom' => date("c", mktime(date("H"), date("i")+10, date("s"), date("n"), date("j"), date("Y"))),
'EndTimeTo' => date("c", mktime(date("H"), date("i"), date("s"), date("n"), date("j")+120, date("Y"))),
'Pagination' => array(
'PageNumber' => $_GET['linkebaynum'],
'EntriesPerPage' => "20"
)
);
$results = $client->GetSellerList($params);
if($results->Ack == "Success")
{
$c = 0;
if(is_array($results->ItemArray->Item))
{
foreach($results->ItemArray->Item as $key => $value)
{
array_push($ebay_items_array, $value->ItemID);
$Qcheck = tep_db_query('select ebay_productstoitems_items_id from ' . TABLE_EBAY_PRODUCTS_TO_ITEMS . ' where ebay_productstoitems_items_id = ' . $value->ItemID);
$check = tep_db_fetch_array($Qcheck);
if($check == 0) {
if($check['ebay_productstoitems_items_id'] = $value->ItemID) {
echo 'Not in Database - Inserting ' . $value->ItemID . '<br>';
tep_db_query("insert ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}else{
echo 'Found - ' . $value->ItemID . ' Nothing to Change<br>';
tep_db_query("update ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "' where ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}
$c++;
}
}
} catch (SOAPFault $f) {
print "error<br>";
}
print "Request:<br>".ebay_formatxmlstring($client->__getLastRequest())."<br><br>";
print "Response:<br>".ebay_formatxmlstring($client->__getLastResponse())."<br><br>";
But it will not recover the SKU (or CustomLabel).
Can anyone explain what I am missing to get the SKU into the database along with the ItemID.
Or would I have to recover lists of ItemID and then do a second call to recover the SKU or CustomLabel?
Found out what the problem was the Sandbox does not appear to pass the SKU back. I switched to the live site and hey presto the SKU is being retrieved along with the Itemid.
Some former programmers wrote this program using the Magento SOAP API V1 to mark shipped orders as shipped. On the former Magento vs 1.5 platform it worked okay but now on vs 1.7 the tracking numbers themselves are not being imported. As you can see half way down I have my name commented out //Caitlin. The line above that is what the former programmers put, and the two lines after that are what I think the code is supposed to be for Magento vs 1.7, but I last time I tried this snippet I put a halt in their operations. Does this look correct to you? Any ideas?
$comment = '<b><br>*** Order has shipped. ***</b><br/><br/>' .
'<b>3PL order number:</b> ' . $fields[1] . '<br/>' .
'<b>Weight:</b> ' . $fields[2] . '<br/>' .
'<b>Shipped via:</b> ' . $fields[3] . '<br/>' .
'<b>Tracking number:</b> ' . $fields[4] . '<br/>' .
'<b>Ship date:</b> ' . $fields[5] . '<br/>' .
'<b>Postage:</b> ' . $fields[6] . '<br/>' .
'<b>Fulfillment:</b> ' . $fields[7] . '<br/>' .
'<b>Per packslip:</b> ' . $fields[8];
// Make shipment and add tracking number
if ($fields[3] == 'UPS-RESIDENTIAL') { $shippedby = 'ups'; $shipname = 'UPS Ground'; }
elseif ($fields[3] == 'UPS-2') { $shippedby = 'ups'; $shipname = 'UPS 2nd Day Air'; }
elseif ($fields[3] == 'UPS-OVERNIGHT') { $shippedby = 'ups'; $shipname = 'UPS Next Day Air Saver'; }
elseif ($fields[3] == 'USPS-PRI') { $shippedby = 'usps'; $shipname = 'USPS Priority'; }
elseif ($fields[3] == 'CANADA') { $shippedby = 'custom'; $shipname = 'MSI Canada (Standard) '; }
elseif ($fields[3] == 'MSITRACK') { $shippedby = 'custom'; $shipname = 'MSI Canada (Express)'; }
else { $shippedby = 'custom'; }
// Attempt to create the order, notify on failure
try {
$newShipmentId = $client->call($sess_id, 'sales_order_shipment.create', array($ShippedOrderId, array(), $comment, true, false, $shippedby, $shipname, $fields[4]));
//Caitlin
//$newShipmentId = $client->call($sess_id, 'sales_order_shipment.create', array($ShippedOrderId, array(), $comment, true, false));
//$newTrackId = $proxy->call($sessionId, 'sales_order_shipment.addTrack', array($newShipmentId, $shippedby, $shipname, $fields[4]));
}
catch (Exception $e) { echo 'Shipment creation failed on order '. $ShippedOrderId . ': ', $e->getMessage(); }
// Add comment to order with all the info
$client->call($sess_id, 'sales_order.addComment', array($ShippedOrderId, 'complete', $comment, false));
$mail_content .= $line . "\n";
$importcount++;
}
//}
}
Edit 2/25/13
Using below implementation. I have error from running this script. I haven't been able to test it though since I would have to when the cron runs at 5am.
// Make shipment and add tracking number
if ($fields[3] == 'UPS-RESIDENTIAL') { $shippedby = 'ups'; $shipname = 'UPS Ground'; }
elseif ($fields[3] == 'UPS-2') { $shippedby = 'ups'; $shipname = 'UPS 2nd Day Air'; }
elseif ($fields[3] == 'UPS-OVERNIGHT') { $shippedby = 'ups'; $shipname = 'UPS Next Day Air Saver'; }
elseif ($fields[3] == 'USPS-PRI') { $shippedby = 'usps'; $shipname = 'USPS Priority'; }
elseif ($fields[3] == 'CANADA') { $shippedby = 'custom'; $shipname = 'MSI Canada (Standard) '; }
elseif ($fields[3] == 'MSITRACK') { $shippedby = 'custom'; $shipname = 'MSI Canada (Express)'; }
else { $shippedby = 'custom'; }
/////////////////////////////////////////////
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$shipment_collection = Mage::getResourceModel('sales/order_shipment_collection');
$shipment_collection->addAttributeToFilter('order_id', $orderId);
$shipment_collection->load();
$firstItem = $shipment_collection->getFirstItem();
if(count($shipment_collection) > 1)
{
$track_no = $fields[4]; // insert tracking # string here
$shipment = Mage::getModel('sales/order_shipment');
$shipment->load($firstItem->getId());
if($shipment->getId() != '')
{
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', $shipname) // User syntax correct name here
->setData('number', $track_no)
->setData('carrier_code', $shippedby) // use code that matches DB code for ship method here
->setData('order_id', $shipment->getData('order_id'));
$track->save();
}
return true;
} else {
$orderShip = $order->prepareShipment(); // can take sku => qty array
$orderShip->register();
$orderShip->sendEmail();
$tracker = Mage::getModel( 'sales/order_shipment_track' );
$tracker->setShipment( $orderShip );
$tracker->setData( 'title', $shipname );
$tracker->setData( 'number', $importData['Tracking Number'] );
$tracker->setData( 'carrier_code', $shippedby );
$tracker->setData( 'order_id', $orderId );
$orderShip->addTrack($tracker);
$orderShip->save();
$order->setData('state', "complete");
$order->setStatus("complete");
$history = $order->addStatusHistoryComment('Order marked as complete by shipment code.', false);
$history->setIsCustomerNotified(false);
$order->save();
/////////////////////////////////////////////////
// Add comment to order with all the info
$client->call($sess_id, 'sales_order.addComment', array($ShippedOrderId, 'complete', $comment, false));
$mail_content .= $line . "\n";
$importcount++;
}
//}
}
The above implementation almost worked for me but I was unable to add the tracking numbers. I eventually went back to testing out the code from the Magento soap API. The following also added the tracking numbers:
try {
// Create new shipment
$newShipmentId = $client->call($sess_id, 'sales_order_shipment.create', array($ShippedOrderId, array(), 'Shipment Created', true, true));
$newTrackId = $client->call($sess_id, 'sales_order_shipment.addTrack', array($newShipmentId, $shippedby, $shipname, $fields[4]));
}
catch (Exception $e) { echo 'Shipment creation failed on order '. $ShippedOrderId . ': ', $e->getMessage(); }
Can't believe I spent so much time on it because I had tried this before and I think I just messed up a variable. Happy to help anyone who may need extra assistance.
I would strip out the use of the API all together.
Try this:
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$shipment_collection = Mage::getResourceModel('sales/order_shipment_collection');
$shipment_collection->addAttributeToFilter('order_id', $orderId);
$shipment_collection->load();
$firstItem = $shipment_collection->getFirstItem();
if(count($shipment_collection) > 1)
{
$track_no = "FEDEX9879879"; // insert tracking # string here
$shipment = Mage::getModel('sales/order_shipment');
$shipment->load($firstItem->getId());
if($shipment->getId() != '')
{
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', 'United Parcel Service') // User syntax correct name here
->setData('number', $track_no)
->setData('carrier_code', 'ups') // use code that matches DB code for ship method here
->setData('order_id', $shipment->getData('order_id'));
$track->save();
}
return true;
} else {
$orderShip = $order->prepareShipment(); // can take sku => qty array
$orderShip->register();
$orderShip->sendEmail();
$tracker = Mage::getModel( 'sales/order_shipment_track' );
$tracker->setShipment( $orderShip );
$tracker->setData( 'title', 'United Parcel Service' );
$tracker->setData( 'number', $importData['Tracking Number'] );
$tracker->setData( 'carrier_code', 'ups' );
$tracker->setData( 'order_id', $orderId );
$orderShip->addTrack($tracker);
$orderShip->save();
$order->setData('state', "complete");
$order->setStatus("complete");
$history = $order->addStatusHistoryComment('Order marked as complete by shipment code.', false);
$history->setIsCustomerNotified(false);
$order->save();
Notice the saving of orderShip automatically saves the tracker, and you CAN NOT save a tracker object on its own because it will fail foreign key constraint.