代码改变世界

mercadolibre 美卡多 拉取listing

2025-07-04 17:16  天心PHP  阅读(24)  评论(0)    收藏  举报

mercadolibre账户分为本土和跨境

创建任务表: yibai_mercadolibre_listing_task

CREATE TABLE `yibai_mercadolibre_listing_task` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `account_id` int(11) NOT NULL DEFAULT '0' COMMENT 'account_id',
  `account_name` varchar(50) NOT NULL DEFAULT '' COMMENT 'account_name',
  `type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1:本土 2:跨境',
  `currert` int(11) NOT NULL DEFAULT '0' COMMENT '当前数量',
  `total` int(11) NOT NULL DEFAULT '0' COMMENT '总数量',
  `itemnum` int(11) NOT NULL DEFAULT '0' COMMENT '拉取item_id数量',
  `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0:未开始 1:进行中 2:完成',
  `scroll_id` varchar(1000) DEFAULT '' COMMENT 'scroll_id',
  `create_dates` datetime DEFAULT NULL COMMENT '创建时间',
  `update_dates` datetime DEFAULT NULL COMMENT '修改时间',
  `start_dates` datetime DEFAULT NULL COMMENT '开始时间',
  `end_dates` datetime DEFAULT NULL COMMENT '结束时间',
  `msg` text COMMENT '接口错误原因',
  PRIMARY KEY (`id`),
  KEY `idx_account_id` (`account_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='美客多listing任务表';
View Code

创建site表: yibai_mercadolibre_listing_site

CREATE TABLE `yibai_mercadolibre_listing_site` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `item_id` varchar(50) NOT NULL DEFAULT '' COMMENT '产品id',
  `mpid` varchar(50) NOT NULL DEFAULT '' COMMENT 'cbtid',
  `listing_pk_id` int(11) NOT NULL DEFAULT '0' COMMENT 'yibai_mercadolibre_listing表id',
  `account_id` int(11) NOT NULL DEFAULT '-1' COMMENT '账号id',
  `status_site` varchar(20) NOT NULL DEFAULT '' COMMENT '商品状态',
  `type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '类型',
  `created_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
  `updated_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_item_id` (`item_id`),
  KEY `idx_listing_id` (`listing_pk_id`),
  KEY `idx_status_site` (`status_site`),
  KEY `idx_mpid` (`mpid`),
  KEY `idx_type` (`type`),
  KEY `idx_accountid_type_itemid` (`account_id`,`type`,`item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='mercadolibre刊登站点item中间表';
View Code

创建账户表: yibai_mercadolibre_accounts

CREATE TABLE `yibai_mercadolibre_accounts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `account` varchar(155) DEFAULT NULL COMMENT '账号名',
  `shop_id` varchar(30) NOT NULL DEFAULT '' COMMENT '店铺ID',
  `email` varchar(100) DEFAULT NULL COMMENT '在线账号的id',
  `access_token` varchar(155) DEFAULT NULL COMMENT 'api访问token',
  `refresh_token` varchar(155) DEFAULT NULL COMMENT 'api刷新token',
  `expires_in` datetime DEFAULT NULL COMMENT 'token过期时间',
  `app_id` int(11) DEFAULT NULL COMMENT '账号所属的app',
  `status` int(11) DEFAULT '-1' COMMENT '账号状态,初始化(待激活),停用,启用;(-1,0,1)',
  `created_at` datetime DEFAULT NULL COMMENT '账号(erp)创建时间',
  `created_by` int(11) DEFAULT NULL COMMENT '创建人',
  `updated_at` datetime DEFAULT NULL COMMENT '更新时间',
  `account_name` varchar(125) DEFAULT NULL COMMENT '账号名称',
  `user_id` int(11) NOT NULL DEFAULT '0' COMMENT '账号id',
  `site_id` varchar(150) NOT NULL DEFAULT '' COMMENT '站点id',
  `type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '店铺性质 0:默认 1:跨境 2:本土',
  `shop_type` tinyint(1) DEFAULT '0' COMMENT '店铺类型 0:无 1:个人店铺 2:企业店铺',
  `ziniao_id` varchar(50) DEFAULT '' COMMENT '紫鸟id 对应 yy_ziniao_store_list',
  `collecting_company` tinyint(1) NOT NULL DEFAULT '1' COMMENT '收款公司 1:香港云羿公司 2:云羿公司',
  `is_rpa_finance` tinyint(1) NOT NULL DEFAULT '2' COMMENT '云羿RPA运行状态-财务 (0:否 1:是 2:所有)',
  `site` varchar(10) DEFAULT '' COMMENT '站点',
  PRIMARY KEY (`id`),
  KEY `yibai_mercadolibre_categories_index` (`account`),
  KEY `idx_type` (`type`) USING BTREE,
  KEY `idx_shop_type` (`shop_type`) USING BTREE COMMENT 'shop_type'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='mercadolibre账号列表';
View Code

创建listing表: yibai_meil_online_listing_new

CREATE TABLE `yibai_meil_online_listing_new` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `item_id` varchar(50) NOT NULL DEFAULT '' COMMENT 'listing_id',
  `mpid` varchar(50) NOT NULL DEFAULT '' COMMENT 'item_id',
  `sku` varchar(50) NOT NULL DEFAULT '' COMMENT '平台sku,由平台规定',
  `platform_sku` varchar(150) NOT NULL DEFAULT '' COMMENT '平台sku(加密)',
  `site` varchar(10) NOT NULL DEFAULT '' COMMENT '老站点名',
  `status_site` varchar(50) NOT NULL DEFAULT '' COMMENT '商品状态',
  `site_id` varchar(50) NOT NULL DEFAULT '' COMMENT '站点',
  `product_title_english` varchar(200) NOT NULL DEFAULT '' COMMENT '标题',
  `subtitle` varchar(50) NOT NULL DEFAULT '' COMMENT '副标题',
  `descriptions_deatil` text COMMENT '描述',
  `seller_id` varchar(50) NOT NULL DEFAULT '' COMMENT '卖方的用户id',
  `category_id` varchar(50) NOT NULL DEFAULT '' COMMENT '分类id',
  `official_store_id` varchar(50) NOT NULL DEFAULT '' COMMENT '卖方的官方商店id',
  `sale_price_site` decimal(10,0) NOT NULL DEFAULT '0' COMMENT '售价',
  `base_price` decimal(10,0) NOT NULL DEFAULT '0' COMMENT '底价',
  `original_price` decimal(10,0) NOT NULL DEFAULT '0' COMMENT '商品的原价',
  `currency_id` varchar(50) NOT NULL DEFAULT '0.0' COMMENT '币别',
  `initial_quantity` bigint(10) NOT NULL DEFAULT '0' COMMENT '原有的数量',
  `available_quantity` bigint(10) NOT NULL DEFAULT '0' COMMENT '可售数量',
  `sold_quantity` bigint(10) NOT NULL DEFAULT '0' COMMENT '销量',
  `sale_terms` varchar(500) NOT NULL DEFAULT '' COMMENT '销售条件',
  `buying_mode` varchar(50) NOT NULL DEFAULT '' COMMENT '购买模式',
  `listing_type_id` varchar(50) NOT NULL DEFAULT '' COMMENT 'listing_type_id',
  `start_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '上架时间',
  `stop_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '停售时间',
  `condition` varchar(50) NOT NULL DEFAULT '' COMMENT '条件',
  `permalink` varchar(350) NOT NULL DEFAULT '' COMMENT '商品链接',
  `thumbnail` varchar(200) NOT NULL DEFAULT '' COMMENT '主图',
  `pictures` varchar(1500) NOT NULL DEFAULT '' COMMENT '子图',
  `video_id` varchar(50) NOT NULL DEFAULT '' COMMENT '视频id',
  `accepts_mercadopago` varchar(50) NOT NULL DEFAULT '' COMMENT 'mercado pago付款方式',
  `non_mercado_pago_payment_methods` varchar(200) NOT NULL DEFAULT '' COMMENT '非mercado pago付款方式',
  `shipping` varchar(500) NOT NULL DEFAULT '' COMMENT '发货详细资料',
  `international_delivery_mode` varchar(50) NOT NULL DEFAULT '' COMMENT '国际交付模式',
  `seller_contact` varchar(50) NOT NULL DEFAULT '' COMMENT '卖家联系',
  `location` varchar(200) NOT NULL DEFAULT '' COMMENT '位置',
  `geolocation` varchar(200) NOT NULL DEFAULT '' COMMENT '定位',
  `coverage_areas` varchar(50) NOT NULL DEFAULT '' COMMENT '覆盖范围',
  `attributes` text COMMENT '属性',
  `warnings` varchar(200) NOT NULL DEFAULT '' COMMENT '警告信息',
  `listing_source` varchar(50) NOT NULL DEFAULT '' COMMENT '指示项目列表源',
  `sub_status` varchar(200) NOT NULL DEFAULT '' COMMENT '内部修饰词和/或状态',
  `tags` varchar(500) NOT NULL DEFAULT '' COMMENT '标签',
  `warranty` varchar(50) NOT NULL DEFAULT '' COMMENT '指示是否对该物品提供担保',
  `catalog_product_id` varchar(50) NOT NULL DEFAULT '' COMMENT '链接到该项的目录产品id',
  `domain_id` varchar(200) NOT NULL DEFAULT '' COMMENT '项目所属的域id',
  `parent_item_id` varchar(50) NOT NULL DEFAULT '' COMMENT '父项id',
  `differential_pricing` varchar(50) NOT NULL DEFAULT '' COMMENT '指定项目差异定价',
  `deal_ids` varchar(255) NOT NULL DEFAULT '' COMMENT '项目的交易id',
  `automatic_relist` varchar(50) NOT NULL DEFAULT '' COMMENT '指示该项目是否可以自动重新列表',
  `date_created` varchar(50) NOT NULL DEFAULT '' COMMENT '创建项目的日期',
  `last_updated` varchar(50) NOT NULL DEFAULT '' COMMENT '更新项目的日期',
  `health` varchar(50) NOT NULL DEFAULT '' COMMENT '健康状况百分比',
  `catalog_listing` varchar(50) NOT NULL DEFAULT '' COMMENT '指定项目是否为目录列表',
  `product_linelist_id` int(11) NOT NULL DEFAULT '0' COMMENT '产品线id',
  `main_product_linelist_id` int(11) NOT NULL DEFAULT '0' COMMENT 'main产品线id',
  `sale_cost_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '保本价',
  `old_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '原刊登价',
  `account_id` int(11) NOT NULL DEFAULT '0' COMMENT '账号',
  `user_logistic_type` varchar(50) NOT NULL DEFAULT '' COMMENT '物流类型',
  `rate_profit` decimal(11,2) NOT NULL DEFAULT '0.00' COMMENT '利润率',
  `gross_profit_rate` decimal(11,2) NOT NULL DEFAULT '0.00' COMMENT '毛利率',
  `variation_multi` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否变体',
  `updated_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '更新时间',
  `created_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '拉取时间',
  `visits_num` int(11) NOT NULL DEFAULT '0' COMMENT '浏览量',
  `upc` varchar(50) NOT NULL DEFAULT '' COMMENT 'upc',
  `sales_id` int(11) NOT NULL DEFAULT '0' COMMENT '销售员id',
  `del_status` int(11) NOT NULL DEFAULT '1' COMMENT 'listing删除状态 1.未删除 2.已删除',
  `sku_status` int(11) NOT NULL DEFAULT '1' COMMENT '产品停售标识 1.未停售 2.已停售',
  `price_usd` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '美元价格',
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_item_id` (`item_id`),
  KEY `idx_mpid` (`mpid`),
  KEY `idx_sku` (`sku`),
  KEY `idx_site` (`site`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_status_site` (`status_site`),
  KEY `idx_del_status` (`del_status`),
  KEY `idx_sku_status` (`sku_status`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='mercadolibre在线listing新api';
View Code

创建listing变体表: yibai_meil_online_listing_new

CREATE TABLE `yibai_meil_listing_variations` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `variations_id` varchar(50) NOT NULL DEFAULT '' COMMENT '变体id',
  `item_id` varchar(50) NOT NULL DEFAULT '' COMMENT 'item_id',
  `mpid` varchar(50) NOT NULL DEFAULT '' COMMENT 'mpid',
  `sku_variations` varchar(50) NOT NULL DEFAULT '' COMMENT 'sku',
  `platform_sku_variations` varchar(150) NOT NULL DEFAULT '' COMMENT '平台sku',
  `available_quantity_variations` bigint(10) NOT NULL DEFAULT '0' COMMENT '可售数量',
  `sold_quantity_variations` bigint(10) NOT NULL DEFAULT '0' COMMENT '出售数量',
  `picture_ids` varchar(1000) NOT NULL DEFAULT '' COMMENT '图片id',
  `package_height_value` varchar(50) NOT NULL DEFAULT '' COMMENT '包装高度',
  `package_width_value` varchar(50) NOT NULL DEFAULT '' COMMENT '包装宽度',
  `upc_variations` varchar(50) NOT NULL DEFAULT '' COMMENT 'UPC',
  `price_variations` varchar(50) NOT NULL DEFAULT '' COMMENT '价格',
  `package_length_value` varchar(50) NOT NULL DEFAULT '' COMMENT '包装长度',
  `package_weight_value` varchar(50) NOT NULL DEFAULT '' COMMENT '包装重',
  `attribute_json` varchar(1000) NOT NULL DEFAULT '' COMMENT '属性',
  `updated_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '更新时间',
  `created_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_item_id` (`item_id`) USING BTREE,
  KEY `idx_mpid` (`mpid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
View Code

1.第一步

/services/mercadolibre/mercadolibreitemsnew/addaccounts?type=1 #美卡多加入要拉取的账户 境外账户
加入任务表 yibai_mercadolibre_listing_task
/services/mercadolibre/mercadolibreitemsnew/addaccounts?type=2 #美卡多加入要拉取的账户 本土账户
加入任务表 yibai_mercadolibre_listing_task

public function actionAddAccounts()
{
    $account_id = Yii::app()->request->getParam('account_id');
    $type = Yii::app()->request->getParam('type');
    $taskmodel = new MercadolibreListingTask();
    $accountmodel = new MercadolibreAccount();
    $sitemodel = new Mercadolibrelistingsite();
    $tasklist = $taskmodel->getDbConnection()->createCommand()
        ->select('account_id')
        ->from($taskmodel->tableName())
        ->queryColumn();
    $where = ' ';
    if($account_id){$where .= " and id=".$account_id;}
    if($type){$where .= " and type=".$type;}

    $accounts = $accountmodel->queryPairs('id,account,type','status=1'.$where);
    $list = $data = [];
    $datetimes = date('Y-m-d H:i:s');
    foreach ($accounts as $key=>$val){
        if(in_array($key, $tasklist)){
            $taskmodel->updateAll(['currert'=>0,'total'=>0,'status'=>0,'itemnum'=>0,'scroll_id'=>'','update_dates'=>$datetimes,'start_dates'=>NULL,'end_dates'=>NULL,'msg'=>''],'account_id='.$key);
        }else{
            $data['account_id'] = $key;
            $data['account_name'] = $val['account'];
            $data['type'] = $val['type'];
            $data['currert'] = 0;
            $data['total'] = 0;
            $data['status'] = 0;
            $data['itemnum'] = 0;
            $data['scroll_id'] = '';
            $data['create_dates'] = $datetimes;
            $data['update_dates'] = $datetimes;
            $data['msg'] = '';
            $list[] = $data;
        }
    }
    $taskmodel->batchInsertAll($taskmodel->tableName(), array_keys($list[0]), $list, true);
    echo 'DOLL';
}
View Code

 2.第二部

/services/mercadolibre/mercadolibreitemsnew/getoldonlinelisting?type=2 #EPR系统--美卡多拉取MPID或ITEM_ID
拉取 本土账户的 item_id 到 yibai_mercadolibre_listing_site 表
拉取 境外账户的 mpid 到 yibai_mercadolibre_listing_site 表

 

yibai_mercadolibre_listing_site 的type
type=1 需要拉取listing的状态
type=4 已经拉取了lisitng的状态
type=2 境外新拉取的mpid
type=5 境外根据mpid拉取到了item_id的状态
type=3 境外没有根据mpid拉取到了item_id的状态(接口成功)
type=6 根据mpid拉取到了item_id的(接口失败)

public function actionGetOldOnlineListing()
{
    set_time_limit(0);
    $type = Yii::app()->request->getParam('type');
    $account_id = Yii::app()->request->getParam('account_id');
    $keys='mercadolibre_list_task';
    $taskmodel = new MercadolibreListingTask();
    $accountmodel = new MercadolibreAccount();
    if($type==3){
        $accountss = Yii::app()->memcache->get($keys);
        $lines = json_decode($accountss,true);
        VHelper::dump($lines);exit();
    }
    if($type==4){
        Yii::app()->memcache->delete($keys);
        die('删除换成成功');
    }
    if ($account_id) {
        $taskinfo = $taskmodel->getDbConnection()->createCommand()
            ->select('*')
            ->from($taskmodel->tableName())
            ->where("account_id=".$account_id." and status!=2")
            ->queryRow();
        if($taskinfo){
            $accountinfo = $accountmodel->findByPk($taskinfo['account_id']);
            $accountArr= explode("-",$accountinfo->access_token);
            $users= end($accountArr);
            $scroll_id = $taskinfo['scroll_id'];
            $currert[$account_id] = $taskinfo['currert'];
            while(true) {
                $data=array('search_type'=>'scan','scroll_id'=>$scroll_id,'orders'=>'start_time_desc','offset'=>0,'limit'=>100,'access_token'=>$accountinfo->access_token);
                if($accountinfo->app==NULL){
                    $taskmodel->updateAll(['status'=>2,'update_dates'=>date('Y-m-d H:i:s')],"account_id=".$taskinfo['account_id']);
                    $accountss = Yii::app()->memcache->get($keys);
                    $accountss = json_decode($accountss,true);
                    $line = $account_id%10;
                    if(!empty($accountss[$line])){
                        $account_id = array_shift($accountss[$line]);
                        Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
                        $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getoldonlinelisting/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                        echo $url;echo '<br/>';
                        MHelper::curl_post_async($url);
                    }
                    break;
                }
                $res = $accountinfo->app->get_all_item($users,$data);
                if(isset($res['httpCode']) && $res['httpCode']=='200'){
                    $itemArr=$res['body']->results;
                    $itemArr_str = MHelper::simplode($itemArr);
                    if($taskinfo['type']==2){
                        $exits = YbModel::model('Mercadolibrelistingsite')->queryPairs('item_id,type',"item_id in ({$itemArr_str}) and account_id={$taskinfo['account_id']} and type in(1,4)");
                    }else if($taskinfo['type']==1){
                        //$exits = YbModel::model('Mercadolibrelistingsite')->queryPairs('mpid,id,type',"mpid in ({$itemArr_str}) and account_id={$taskinfo['account_id']} and type in (2,3,5,6)");
                        $exits = YbModel::model('Mercadolibrelistingsite')->queryPairs('mpid,id,type',"mpid in ({$itemArr_str}) and account_id={$taskinfo['account_id']}");
                    }
                    $insert_date = $update_date = [];
                    foreach ($itemArr as $v){
                        if(isset($exits[$v]) && $exits[$v]){
                            if($taskinfo['type']==2){//本土
                                if($exits[$v]==4){
                                    $update_date[] = $v;
                                }
                            }else{//境外
                                continue;
                                //$update_date_item[] = $v;
                            }
                        }else{
                            if($taskinfo['type']==2){//本土
                                $insert_date[] =[
                                    'item_id'=>$v,
                                    'account_id'=>$taskinfo['account_id'],
                                    'type' => 1,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ];
                            }else{
                                $insert_date[] =[//境外
                                    'mpid'=>$v,
                                    'account_id'=>$taskinfo['account_id'],
                                    'type' => 2,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ];
                            }
                        }
                    }
                    if(!empty($insert_date)){
                        YbModel::model('Mercadolibrelistingsite')->batchInsertAll('{{product}}.{{mercadolibre_listing_site}}',array_keys($insert_date[0]),$insert_date);
                        $insert_date = [];
                    }
                    if($update_date){
                        $update_str = MHelper::simplode($update_date);
                        YbModel::model('Mercadolibrelistingsite')->updateAll(['type'=>1,'updated_at'=>date('Y-m-d H:i:s')],"item_id in ({$update_str}) and account_id={$taskinfo['account_id']}");
                    }
                    $currert[$account_id] = $currert[$account_id]+count($itemArr);
                    if($scroll_id==''){
                        $taskmodel->updateAll(['total'=>$res['body']->paging->total,'status'=>1,'start_dates'=>date('Y-m-d H:i:s')],"account_id=".$taskinfo['account_id']);
                    }
                    $taskmodel->updateAll(['scroll_id'=>$res['body']->scroll_id,'currert'=>$currert[$account_id]],"account_id=".$taskinfo['account_id']);
                    $scroll_id = $res['body']->scroll_id;
                }else{
                    $taskmodel->updateAll(['msg'=>json_encode($res)],"account_id=".$taskinfo['account_id']);
                    $accountss = Yii::app()->memcache->get($keys);
                    $accountss = json_decode($accountss,true);
                    $line = $account_id%10;
                    if(!empty($accountss[$line])){
                        $account_id = array_shift($accountss[$line]);
                        Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
                        $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getoldonlinelisting/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                        echo $url;echo '<br/>';
                        MHelper::curl_post_async($url);
                    }
                    break;
                }
                if($currert[$account_id]>=$res['body']->paging->total){
                    $taskmodel->updateAll(['status'=>2,'end_dates'=>date('Y-m-d H:i:s')],"account_id=".$taskinfo['account_id']);
                    $accountss = Yii::app()->memcache->get($keys);
                    $accountss = json_decode($accountss,true);
                    $line = $account_id%10;
                    if(!empty($accountss[$line])){
                        $account_id = array_shift($accountss[$line]);
                        Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
                        $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getoldonlinelisting/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                        echo $url;echo '<br/>';
                        MHelper::curl_post_async($url);
                    }
                    break;
                }
            }

        }
    }else{
        $ssql = "select id from yibai_product.yibai_mercadolibre_listing_task where status=1 and msg=''";
        $resinfo = $taskmodel->getDbConnection()->createCommand($ssql)->queryScalar();
        if($resinfo){
            die('任务正在执行');
        }
        $where = "status!=2";
        if($type){
            $where .= " and type=".$type;
        }
        $accountss = Yii::app()->memcache->get($keys);
        $lines = json_decode($accountss,true);
        if(count(array_filter($lines))==0){
            Yii::app()->memcache->delete($keys);
            $lines = NULL;
        }
        if(empty($lines)){
            $sqlacc = "SELECT account_id,MOD(account_id,10)as line FROM yibai_product.yibai_mercadolibre_listing_task where {$where} group by account_id";
            $account = $taskmodel->getDbConnection()->createCommand($sqlacc)->queryAll();
            if(!$account){die('处理完成1');}
            $accountlist = array_column($account,null,'account_id');
            foreach($accountlist as $val){
                $lines[$val['line']][] = $val['account_id'];
            }
            $taskmodel->updateAll(['msg'=>'']);
        }
        if(count(array_filter($lines))==0){
            die('处理完成2');
        }
        for($i=0;$i<10;$i++){
            if(!empty($lines[$i])){
                $account_id = array_shift($lines[$i]);
                Yii::app()->memcache->set($keys,json_encode($lines),12*3600);
                $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getoldonlinelisting/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                echo $url;echo '<br/>';
                MHelper::curl_post_async($url);
                //break;
            }else{
                continue;
            }
        }
    }
    echo 'DOLL';
}
View Code

 本土直接拉取item_id

境外拉取的是mpid

拉完了的 yibai_mercadolibre_listing_task 表

 3.第三步 只针对境外 本土的不需要

根据mpid 去拉取item_id

/services/mercadolibre/mercadolibreitemsnew/getonlineListinginfonew (境外账户专用) EPR系统--美卡多根据MPID拉取ITEM_ID

public function actionGetonlinelistinginfonew()
{
  set_time_limit(0);
  $keys = 'mercadolibre_listing_account_ids';
  $model = YbModel::model('Mercadolibrelistingsite');
  $accmodel = YbModel::model('MercadolibreAccount');
  $taskmodel = YbModel::model('MercadolibreListingTask');
  $account_id = (int)Yii::app()->request->getParam('account_id');
  $type = (int)Yii::app()->request->getParam('type');
  $see = (int)Yii::app()->request->getParam('see');
  $limit = (int)Yii::app()->request->getParam('limit', 20);
  if($type==3){
      $accountss = Yii::app()->memcache->get($keys);
      $lines = json_decode($accountss,true);
      VHelper::dump($lines);exit();
  }
 if($type==4){
     Yii::app()->memcache->delete($keys);
     die('删除memcache队列');
 }
 $itemnum = [];
 if (!empty($account_id)) {
       set_time_limit(3600);
       $data = $model->getDbConnection()->createCommand()
            ->select('mpid,account_id')
            ->from('yibai_mercadolibre_listing_site')
            ->where("account_id={$account_id} and (item_id IS NULL or item_id='') and type=2")
            ->order("updated_at DESC")
            ->limit($limit)
            ->queryAll();
       $itemnum[$account_id] = $taskmodel->getDbConnection()->createCommand()
           ->select('itemnum')
           ->from($taskmodel->tableName())
           ->where("account_id=".$account_id)
           ->queryScalar();
       if(!empty($data)) {
            $acc = $accmodel->active()->findByPk($account_id);
            $app = $acc->app;
            if (empty($app)) {
                 echo $acc->account . '调/items/search 账号不存在';
            }
            $delete_mpid = $update_mpids = $insert_date = $item_id = [];
            $mpids = array_column($data, 'mpid');
            $mpids_str = MHelper::simplode($mpids);
            $exits = $model->queryPairs('item_id,id', "mpid in ({$mpids_str}) and account_id={$account_id} and type=1");
            $insert_date = [];
            foreach ($data as $val) {
                 $res = $app->get_item_id($val['mpid'], ['access_token' => $acc->access_token]);
                 if ($res['httpCode'] == 0) {
                      echo $val['mpid'] . '调/items/search 网络问题';
                      $update_mpids_err[] = $val['mpid'];
                      continue;
                 }
                 if ($res['httpCode'] > 300) {
                      $error_msg = $res['body'];
                      $update_mpids_err[] = $val['mpid'];
                      echo $val['mpid'] . '调/items/search' . json_encode($error_msg);
                      continue;
                 }
                 if (empty($res['body']->marketplace_items)) {
                      $delete_mpid[] = $val['mpid'];
                      continue;
                 }
                 foreach ($res['body']->marketplace_items as $value) {
                      if ($exits[$value->item_id]) {
                           $update_mpids[] = $val['mpid'];
                           continue;
                      } else {
                           if(!in_array($value->item_id,$item_id)){
                               $insert_date[] = [
                                   'item_id' => $value->item_id,
                                   'mpid' => $val['mpid'],
                                   'account_id' => $val['account_id'],
                                   'created_at' => date('Y-m-d H:i:s'),
                                   'updated_at' => date('Y-m-d H:i:s'),
                                   'type' => 1
                               ];
                               $item_id[] = $value->item_id;
                           }
                           $update_mpids[] = $val['mpid'];
                      }
                 }
            }
            if (!empty($insert_date)) {
                $model->batchInsertAll('{{product}}.{{mercadolibre_listing_site}}', array_keys($insert_date[0]), $insert_date);
            }
            if (!empty($delete_mpid)) {
                 $delete_mpid_str = MHelper::simplode($delete_mpid);
                 $model->updateAll(array('type' => 3, 'updated_at' => date('Y-m-d H:i:s')), "account_id={$account_id} and mpid in ({$delete_mpid_str})");//type=3 listing删除不再执行
            }
            if (!empty($update_mpids)) {
                 $update_mpids_str = MHelper::simplode($update_mpids);
                 $model->updateAll(array('type'=>5,'updated_at' => date('Y-m-d H:i:s')), "account_id={$account_id} and mpid in ({$update_mpids_str}) and type=2");//更新时间
            }
           if (!empty($update_mpids_err)) {//拉取item_id网络错误
               $update_mpids_err_str = MHelper::simplode($update_mpids_err);
               $model->updateAll(array('type'=>6,'updated_at' => date('Y-m-d H:i:s')), "account_id={$account_id} and mpid in ({$update_mpids_err_str}) and type=2");//更新时间
           }
            if (count($data) == $limit) {
                 $taskmodel->updateAll(['itemnum'=>$itemnum[$account_id]+$limit],"account_id=".$account_id);
                 $url = sprintf('http://%s/services/mercadolibre/mercadolibreitemsnew/getonlineListinginfonew/account_id/%s/limit/%s', $_SERVER['HTTP_HOST'], $account_id, $limit);
                 echo $url;
                 MHelper::curl_post_async($url);
            } else {
                $taskmodel->updateAll(['itemnum'=>$itemnum[$account_id]+count($data)],"account_id=".$account_id);
                $accountss = Yii::app()->memcache->get($keys);
                $accountss = json_decode($accountss,true);
                $line = $account_id%10;
                if(!empty($accountss[$line])){
                    $account_id = array_shift($accountss[$line]);
                    Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
                    $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getonlineListinginfonew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                    echo $url;echo '<br/>';
                    $model->updateAll(['type'=>1,'updated_at'=>date('Y-m-d H:i:s')],"account_id=".$account_id." and item_id!='' and mpid!='' and type=4");
                    MHelper::curl_post_async($url);
                }
            }
       }
  } else {
         $where = "type=2";
         $accountss = Yii::app()->memcache->get($keys);
         $lines = json_decode($accountss,true);
         if(count(array_filter($lines))==0){
             Yii::app()->memcache->delete($keys);
             $lines = NULL;
         }
         if(empty($lines)){
             $sqlacc = "SELECT account_id,MOD(account_id,10)as line FROM yibai_product.yibai_mercadolibre_listing_site where {$where} group by account_id";
             $account = $model->getDbConnection()->createCommand($sqlacc)->queryAll();
             if(!$account){die('处理完成1');}
             $accountlist = array_column($account,null,'account_id');
             foreach($accountlist as $val){
                 $lines[$val['line']][] = $val['account_id'];
             }
         }
         if(count(array_filter($lines))==0){
             die('处理完成2');
         }
         for($i=0;$i<10;$i++){
             if(!empty($lines[$i])){
                 $account_id = array_shift($lines[$i]);
                 Yii::app()->memcache->set($keys,json_encode($lines),12*3600);
                 $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getonlineListinginfonew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
                 echo $url;echo '<br/>';
                 $model->updateAll(['type'=>1,'updated_at'=>date('Y-m-d H:i:s')],"account_id=".$account_id." and item_id!='' and mpid!='' and type=4");
                 MHelper::curl_post_async($url);
                 //break;
             }else{
                 continue;
             }
         }
  }
  echo 'DOLL';
}
View Code

 4.第四步 根据拉取到的item_id 去接口拉取详细信息

/services/mercadolibre/mercadolibreitemsnew/getproductnew  拉取mercado在售listing相关sku

public function actionGetproductnew()
{
  set_time_limit(0);
  $account_id = Yii::app()->request->getParam('account_id');
  $type = Yii::app()->request->getParam('type',0);
  $site = Yii::app()->request->getParam('site');
  $item_id = Yii::app()->request->getParam('item_id');
  $print = Yii::app()->request->getParam('print');
  $keys = 'mercadolibre_listing_sku_detail';
  $model = new Mercadolibrelistingsite();
  if($site=='see'){
     $accountss = Yii::app()->memcache->get($keys);
     $lines = json_decode($accountss,true);
     VHelper::dump($lines);exit();
  }
  if($site=='del'){
     $accountss = Yii::app()->memcache->delete($keys);
     VHelper::dump('删除成功');exit();
  }
  if ($account_id) {
       $date= date('Y-m-d');
      $accountModel = new MercadolibreAccount();
      $acc = $accountModel->active()->findByPk($account_id);
      $lists = [];
      $where = '';
      if($item_id){
          $where .=" and l.item_id='".$item_id."'";
      }
      $lists = $model->getDbConnection()->createCommand()
          ->select('l.item_id,l.account_id')
          ->from('{{mercadolibre_listing_site}} l')
          ->where("account_id={$account_id} and type=1".$where)
          ->limit(20)
          ->queryAll();
       if ($lists) {
            $skulist = array_unique(array_column($lists, 'item_id'));
            $skulist_str = MHelper::simplode($skulist);
            if(!$print){
                $model->updateAll(['type'=>4],"account_id={$account_id} and item_id in ({$skulist_str}) and type=1");
            }
            $items['item_id'] = array_column($lists,'item_id');
            $onlineList = MercadolibreOnlineListingNew::staticModel();
            $onlineList->getRedisSiteListing($items, $account_id,$print);
            $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getproductnew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
            MHelper::curl_post_async($url);
       } else {
           $accountss = Yii::app()->memcache->get($keys);
           $accountss = json_decode($accountss,true);
           $line = $account_id%10;
           if(!empty($accountss[$line])){
               $account_id = array_shift($accountss[$line]);
               Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
               $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getproductnew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);

               echo $url;echo '<br/>';
               MHelper::curl_post_async($url);
           }else{
               $line = $line+1;
               if($line>9){
                   die('处理完成');
               }
               $account_id = array_shift($accountss[$line]);
               Yii::app()->memcache->set($keys,json_encode($accountss),12*3600);
               $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getproductnew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
               echo $url;echo '<br/>';
               MHelper::curl_post_async($url);
           }
       }
  } else {
      $accountss = Yii::app()->memcache->get($keys);
      $lines = json_decode($accountss,true);
      if(count(array_filter($lines))==0){
          $accountss = Yii::app()->memcache->delete($keys);
          $lines = NULL;
      }
      if(empty($lines)){
          $sqlacc = "SELECT account_id,MOD(account_id,10)as line FROM yibai_product.yibai_mercadolibre_listing_site where type=1 group by account_id";
          $account = $model->getDbConnection()->createCommand($sqlacc)->queryAll();
          if(!$account){die('处理完成');}
          $accountlist =  array_column($account,null,'account_id');
          foreach($accountlist as $val){
              $lines[$val['line']][] = $val['account_id'];
          };
      }
      if(count(array_filter($lines))==0){
          die('处理完成');
      }
      for($i=0;$i<10;$i++){
          if(!empty($lines[$i])){
              $account_id = array_shift($lines[$i]);
              Yii::app()->memcache->set($keys,json_encode($lines),12*3600);
              $url = sprintf('%s/services/mercadolibre/mercadolibreitemsnew/getproductnew/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
              echo $url;echo '<br/>';
              MHelper::curl_post_async($url);
              //break;
          }else{
              continue;
          }
      }
  }
}


public function getRedisSiteListing($val, $account_id, $print = false)
{
  if (empty($val)) {
       return false;
  }
  $itemIds = implode(',', $val['item_id']);
  $accountModel = new MercadolibreAccount();
  $acc = $accountModel->active()->findByPk($account_id);
  $app = $acc->app;
  if (empty($app)) {
       return $val['mpid'] . '调/items/search 账号不存在';
  }
  $res_listing = [];
  if($acc->type==1){//跨境
      foreach ($val['item_id'] as $ival){
          $listing = $app->get_one_listing($ival, $acc->getToken());
          $res_listing['body'][] = $listing;
      }
      $res_listing['httpCode'] = 200;
  }elseif ($acc->type==2){//本土
      $res_listing = $app->getProductNew($itemIds, $acc->getToken());
  }
  if ($print == 3) {
       VHelper::dump($res_listing);
  }
  if ($res_listing['httpCode'] == 0) {
       return $itemIds . '网络问题';

  }
  if ($res_listing['httpCode'] > 300) {
       $error_msgs = $res_listing['body'];
       return $itemIds . json_encode($error_msgs);
  }
  $this->saveModelItem($res_listing['body'], $acc, $itemIds);
}

public function get_one_listing($mpid,$token)
{
    return $this->api()->get('/marketplace/items/'.$mpid,['access_token' => $token ]);
}

public function getProductNew($id='',$token)
{
    return $this->api()->get('/items',[ 'ids'=>$id,'access_token' => $token ]);
}

public function get_description($item_id,$token)
{
    return $this->api()->get('/items/'.$item_id.'/description',[ 'access_token' => $token ]);
}
    
//获取浏览量
public function curlGet($ids)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://api.mercadolibre.com/visits/items?ids=$ids");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
  $data = curl_exec($ch);
  curl_close($ch);
  return json_decode($data, true);
}

/*
  * 获取CBT,美元价格
  *marketplace/items/MLM765257728
  */
public function getListingOtherInfo($item_id, $acc)
{
  $app = $acc->app;
  $res_des = $app->get_one_listing($item_id, $acc->getToken());
  if ($res_des['httpCode'] == 0) {
       return $item_id . '网络问题';

  }
  if ($res_des['httpCode'] > 300) {
       $error_msgs = $res_des['body'];
       return $item_id . json_encode($error_msgs);
  }
  $dataArr = [];
  $dataArr['cbt_item_id'] = $res_des['body']->cbt_item_id;
  $dataArr['price'] = $res_des['body']->price;
  $dataArr['user_logistic_type'] = $res_des['body']->user_logistic_type;
  return $dataArr;
}
     
public function saveModelItem($res, $acc, $item_ids)
{
  $visitsArr = $this->curlGet($item_ids);//浏览量
 
  $model = new MercadolibreOnlineListingNew();
  $modelsite = new Mercadolibrelistingsite();
  $list = [];
  foreach ($res as $val){
      $data = [];
      $val = (object)$val;
      $var = $val->body;
      $resData = $this->getListingOtherInfo($var->id, $acc);//获取CBTid,美元价格等信息...
      $info = $model->find('account_id=:account_id and item_id=:item_id', [':item_id' =>$var->id,':account_id'=>$acc->id]);
      $old_sku = '';
      $app = $acc->app;
      if(!$var->id){
          continue;
      }
      $data['item_id'] = $var->id;
      $data['mpid'] = isset($resData['cbt_item_id'])?$resData['cbt_item_id']:'';
      $data['platform_sku'] = '';//处理
      $old_site = array_search($var->site_id, MercadolibreListing::SALE_SITES_NEW);
      $data['site'] = $old_site;
      $data['status_site'] = $var->status;
      $data['site_id'] = $var->site_id;
      $data['product_title_english'] = empty($var->title) ? '' : $var->title;
      $data['subtitle'] = empty($info->subtitle) ? '' : $info->subtitle;
      $res_des = $app->get_description($var->id, $acc->getToken());//获取描述详细(需优化,描述分表)
      $data['descriptions_deatil'] = '';
      if ($res_des['httpCode'] == 200) {
          $data['descriptions_deatil'] = $res_des['body']->plain_text;
      }
      $data['seller_id'] = $var->seller_id;
      $data['category_id'] = $var->category_id;
      $data['official_store_id'] = isset($info->official_store_id) ? '' : $info->official_store_id;
      $data['sale_price_site'] = empty($var->price) ? 0 : $var->price;
      $data['base_price'] = empty($var->base_price) ? 0 : $var->base_price;
      $data['original_price'] = empty($var->original_price) ? 0 : $var->original_price;
      $data['currency_id'] = empty($var->currency_id) ? '' : $var->currency_id;
      $data['initial_quantity'] = empty($var->initial_quantity) ? 0 : $var->initial_quantity;
      $data['available_quantity'] = empty($var->available_quantity) ? 0 : $var->available_quantity;
      $data['sold_quantity'] = empty($var->sold_quantity) ? 0 : $var->sold_quantity;
      $data['sale_terms'] = '';//json_encode($sale_terms);
      $data['buying_mode'] = empty($var->buying_mode) ? '' : $var->buying_mode;
      $data['listing_type_id'] = empty($var->listing_type_id) ? '' : $var->listing_type_id;
      $data['start_time'] = empty($var->start_time) ? '0000-00-00 00:00:00' : substr(str_replace("T", " ", $var->start_time), 0, 19);
      $data['stop_time'] = empty($var->stop_time) ? '0000-00-00 00:00:00' : substr(str_replace("T", " ", $var->stop_time), 0, 19);
      $data['condition'] = empty($var->condition) ? '' : $var->condition;
      $data['permalink'] = empty($var->permalink) ? '' : $var->permalink;
      $data['thumbnail'] = empty($var->thumbnail) ? '' : $var->thumbnail;
      $data['pictures'] = '';//implode('~^~', $pictures);
      $data['video_id'] = empty($var->video_id) ? '' : $var->video_id;
      $data['accepts_mercadopago'] = empty($var->accepts_mercadopago) ? '' : $var->accepts_mercadopago;
      $data['non_mercado_pago_payment_methods'] = json_encode($var->non_mercado_pago_payment_methods);
      $data['shipping'] = json_encode((array)$var->shipping);
      $data['international_delivery_mode'] = empty($var->international_delivery_mode) ? '' : $var->international_delivery_mode;
      $data['seller_contact'] = empty($var->seller_contact) ? '' : $var->seller_contact;
      $data['location'] = json_encode($var->location);
      $data['geolocation'] = json_encode($var->geolocation);
      $data['coverage_areas'] = json_encode($var->coverage_areas);
      $data['warnings'] = json_encode($var->warnings);
      $data['listing_source'] = json_encode($var->listing_source);
      $data['sub_status'] = json_encode($var->sub_status);
      $data['tags'] = json_encode($var->tags);
      $data['warranty'] = empty($var->warranty) ? '' : $var->warranty;
      $data['catalog_product_id'] = empty($var->catalog_product_id) ? '' : $var->catalog_product_id;
      $data['domain_id'] = empty($var->domain_id) ? '' : $var->domain_id;
      $data['parent_item_id'] = empty($var->parent_item_id) ? '' : $var->parent_item_id;
      $data['differential_pricing'] = empty($var->differential_pricing) ? '' : $var->differential_pricing;
      $data['deal_ids'] = json_encode($var->deal_ids);
      $data['automatic_relist'] = empty($var->automatic_relist) ? '' : $var->automatic_relist;
      $data['date_created'] = empty($var->date_created) ? '0000-00-00 00:00:00' : substr(str_replace("T", " ", $var->date_created), 0, 19);
      $data['last_updated'] = empty($var->last_updated) ? '0000-00-00 00:00:00' : substr(str_replace("T", " ", $var->last_updated), 0, 19);
      $data['health'] = empty($var->health) ? 0 : $var->health;
      $data['catalog_listing'] = empty($var->catalog_listing) ? '' : $var->catalog_listing;
      $data['sale_cost_price'] = 0;
      $data['account_id'] = $acc->id;
      $data['user_logistic_type'] = isset($resData['user_logistic_type'])?$resData['user_logistic_type']:'';
      $data['rate_profit'] = 0;
      $data['gross_profit_rate'] = 0;
      $data['variation_multi'] = 0;
      if (!empty($var->variations)) {
          $data['variation_multi'] = 1; #是否多属性变体
          $this->saveVariationInfo($data['mpid'],$data['item_id'], $var->variations, $acc);//保存多属性信息
      }
      if($info){
          $data['updated_at'] = date('Y-m-d H:i:s');
          $old_sku = $model->sku?$model->sku:'';
      }else{
          $data['updated_at'] = date('Y-m-d H:i:s');
          $data['created_at'] = date('Y-m-d H:i:s');
      }
      $data['sku'] = $old_sku;
      $data['visits_num'] = isset($visitsArr[$var->id]) ? $visitsArr[$var->id] : 0;
      $data['upc'] = '';//处理
      $data['sales_id'] = 0;
      $data['old_price'] = 0;
      if (!empty($data['mpid'])) {
          $listingInfo = YbModel::model("MercadolibreListing")->find('item_id=:item_id', [':item_id' => $data['mpid']]);
          if (!empty($listingInfo)) {
              $data['sales_id'] = $listingInfo->created_by;
              $old_price_arr = json_decode($listingInfo->sites, true);
              $data['old_price'] = isset($old_price_arr[$old_site]['sale_price']) ? $old_price_arr[$old_site]['sale_price'] : '';//获取原始刊登价
          }
      }
      $data['del_status'] = 1;
      $data['sku_status'] = 1;
      $data['price_usd'] = isset($resData['price_usd'])?$resData['price_usd']:0;
      $data['product_linelist_id'] = 0;
      $data['main_product_linelist_id'] = 0;
      foreach ($var->attributes as $vals) {
          if ($vals->id == 'SELLER_SKU') {
              $ress = YbModel::model(MercadolibreListing::class)->decryptSku($vals->value_name);
              if($ress['ERP']){
                  if(!$data['sku']){
                      $data['sku'] = $res['sku'];
                  }
              }else{
                  $sqls = "select sku from yibai_meil_online_order_sku where account_id={$acc->id} and platformSku='".$vals->value_name."'";
                  $account = new MeilOnlineOrderSku();
                  $yibaisku = $account->getDbConnection()->createCommand($sqls)->queryScalar();
                  if($yibaisku){
                      if(!$data['sku']){
                          $data['sku'] = $yibaisku;
                      }
                  }else{
                      if(!$data['sku']){
                          $data['sku'] = $vals->value_name;
                      }
                  }
              }
              $data['platform_sku'] = $vals->value_name;
          }
          if ($vals->id == 'GTIN') {
              $data['upc'] = $vals->value_name?$vals->value_name:'';
          }
          $attributes[] = array('id' => $vals->id, 'value_id' => $vals->value_name);
      }
      if (!empty($data['sku'])) {
          $product_line = VHelper::selectRowAsArray('Product', 'product_linelist_id', "sku='" . $data['sku'] . "'");
          if (!empty($product_line)) {
              $cateArr = YbModel::model("Productlinelist")->getAllParentByCategoryId($product_line['product_linelist_id']);
              $data['product_linelist_id'] = $product_line['product_linelist_id'];
              $data['main_product_linelist_id'] = isset($cateArr[1]) ? $cateArr[1] : 0;
          }
      }
      $data['attributes'] = json_encode($attributes);
      if($info){
          $model->updateAll($data,"id=".$info->id);
      }else{
          $list[] = $data;
      }
  }
  if($list){
      $model->batchInsertAll($model->tableName(), array_keys($list[0]), $list, false);
  }
  $list = [];
  echo 'DOLL';
}


/*
*保存多属性信息
*/
public function saveVariationInfo($mpid, $item_id, $variations, $acc)
{
  $dataArr = [];
  foreach ($variations as $val) {
       $app = $acc->app;
       $res_des = $app->get_variations($item_id, $val->id,$acc->getToken());
       if ($res_des['httpCode'] == 0) {
            return $item_id . '网络问题';
       }
       if ($res_des['httpCode'] > 300) {
            $error_msgs = $res_des['body'];
            return $item_id . json_encode($error_msgs);
       }
       $dataArr['price'] = $res_des['body']->price;
       $attributeArr = $dataArr = [];
       foreach ($res_des['body']->attribute_combinations as $v) {
            $attributeArr[] = array(
                 'id' => $v->name,
                 'name' => $v->name,
                 'value_id' => $v->value_id,
                 'value_name' => $v->value_name,
            );
       }
       $dataArr['item_id'] = $item_id;
       $dataArr['mpid'] = $mpid;
       $dataArr['sale_price_site'] = $res_des['body']->price;
       $dataArr['variations_id'] = $res_des['body']->id;
       $dataArr['attribute_json'] = json_encode($attributeArr);
       $dataArr['available_quantity'] = $res_des['body']->available_quantity;
       $dataArr['sold_quantity'] = $res_des['body']->sold_quantity;
       $dataArr['picture_ids'] = implode('|', $res_des['body']->picture_ids);
       foreach ($res_des['body']->attributes as $att) {
            if ($att->id == 'PACKAGE_HEIGHT') {
                 $dataArr['package_height_value'] = $att->value_name;
            }
            if ($att->id == 'PACKAGE_WIDTH') {
                 $dataArr['package_width_value'] = $att->value_name;
            }
            if ($att->id == 'GTIN') {
                 $dataArr['UPC'] = $att->value_name?$att->value_name:'';
            }
            if ($att->id == 'PACKAGE_LENGTH') {
                 $dataArr['package_length_value'] = $att->value_name;
            }
            if ($att->id == 'PACKAGE_WEIGHT') {
                 $dataArr['package_weight_value'] = $att->value_name;
            }
            if ($att->id == 'SELLER_SKU') {
                $res = YbModel::model(MercadolibreListing::class)->decryptSku($att->value_name);
                if($res['ERP']){
                    $dataArr['sku_variations'] = $res['sku'];
                }else{
                    $sqls = "select sku from yibai_meil_online_order_sku where account_id={$acc->id} and platformSku='".$att->value_name."'";
                    $account = new MeilOnlineOrderSku();
                    $yibaisku = $account->getDbConnection()->createCommand($sqls)->queryScalar();
                    if($yibaisku){
                        $dataArr['sku_variations'] = $yibaisku;
                    }else{
                        $dataArr['sku_variations'] = $att->value_name;
                    }
                }
                $dataArr['platform_sku_variations'] = $att->value_name;
            }
       }
       $edit = YbModel::model(MercadolibrelistingVariations::class)->find('item_id=:item_id AND variations_id=:variations_id', [':item_id' => $item_id, ':variations_id' => $dataArr['variations_id']]);
       if (empty($edit)) {
            $edit = new MercadolibrelistingVariations();
       }
       $edit->saveDate($dataArr);
  }
}


/*
 * sku:M-SJ05664-01-bao-778705  erp sku :SJ05664-01
 * 解密SKU,encryptSku方法的逆过程
 * @param string 加密的SKU
 * return array  array('sku'=>'真实SKU','ERP'=>'boolean值,是否是ERP加密过的,trueERP加密过,falseERP没加密过')
 */
public function decryptSku($sku)
{
    if ($sku === null || $sku === '') {
        return false;
    }

    if (strpos($sku, 'M-') === 0) {
        $skuInfo = explode('-', $sku);
        $count = count($skuInfo);
        unset($skuInfo[0]);//去掉首元素
        unset($skuInfo[$count - 2]);//去掉倒数两个元素
        unset($skuInfo[$count - 1]);
        return array('sku' => implode('-', $skuInfo), 'ERP' => true);
    } else {
        return array('sku' => $sku, 'ERP' => false);
    }
}
View Code

yibai_meil_online_listing_new  拉取的listing