|
接口文档:https://developer.walmart.com/home/us-mp/
沃尔玛api 分为US站点和CA站点
US站点是获取token的方式
MX站点获取方式和US差不多 多一个参数 "WM_MARKET: mx",
CA站点是签名的方式
US刷新token
/**
* walmart获取token ( us站点 和 mx站点 )
* @url /services/walmart/walmartpromotions/batchupdatetoken
*/
public function actionBatchupdatetoken() {
ini_set("memory_limit","500M");
set_time_limit(3600);
$model =YbModel::model('WalmartAccount');
$id = Yii::app()->request->getParam('id');
$where = " site in('us','mx') and status=1 ";
if($id){
$where .=" and id=". $id;
}
$sql = "select * from yibai_walmart_account where ".$where;
$accountList = $model->getDbConnection()->createCommand($sql)->queryAll();
if($accountList) {
$i = 1;
foreach ($accountList as $val) {
$accountInfo = YbModel::model('WalmartAccount')->findByPk($val['id']);
if ($accountInfo) {
$this->client_id = $accountInfo['client_id'];
$this->client_sec = $accountInfo['client_sec'];
if (!empty($accountInfo['client_id'] && !empty($accountInfo)))
{
$result = $accountInfo->getTokenFromRefreshToken();
if (isset($result['access_token']) && !empty($result['access_token'])) {
$accountInfo->access_token = $result['access_token'];
$accountInfo->expires_in = $result['expires_in'];
$accountInfo->expiry_time = date('Y-m-d H:i:s', time() + $result['expires_in']);
$accountInfo->update_time = date('Y-m-d H:i:s', time());
$accountInfo->save(false);
echo $val['id'].'<br/>';
$i++;
}
}
}
}
}
echo '共更新账号数:'.$i.'<br/>';
}
/*
获取token
*/
public function getTokenFromRefreshToken()
{
$clientId =$this->client_id;
$clientSecret =$this->client_sec;
$site = $this->site;
$qos = uniqid();
if($site=="us"){
$header = array(
"Authorization: Basic " . base64_encode("" .$clientId . ":" . $clientSecret . ""),
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'WM_SVC.NAME: Walmart Marketplace',
'WM_QOS.CORRELATION_ID: '.$qos,
'WM_SVC.VERSION: 1.0.0'
);
}elseif($site=="mx"){
$header = array(
"WM_MARKET: mx",
"Authorization: Basic " . base64_encode("" .$clientId . ":" . $clientSecret . ""),
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'WM_SVC.NAME: Walmart Marketplace',
'WM_QOS.CORRELATION_ID: '.$qos,
'WM_SVC.VERSION: 1.0.0'
);
}
$param=array(
'grant_type'=>'client_credentials',
);
$url=self::TOKEN_URL;
return self::CurlRequest($url, $param, $header,600);
}
private static function CurlRequest($url, $data='', $header=array(), $timeout=300)
{
$opts = array();
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_HEADER] = 0;
$opts[CURLOPT_HTTPHEADER] = $header;
$opts[CURLOPT_RETURNTRANSFER] = 1;
if(!empty($data)) //POST请求
{
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = is_array($data) ? http_build_query($data) : $data;
}
$opts[CURLOPT_TIMEOUT] = $timeout;
$opts[CURLOPT_SSL_VERIFYPEER] = 0;
$opts[CURLOPT_SSL_VERIFYHOST] = 0;
$ch = curl_init();
curl_setopt_array($ch, $opts);
$response_raw = curl_exec($ch);
$errno = curl_errno($ch);
if (0 !== $errno) { #返回头信息
return curl_getinfo($ch) + array('errno'=>$errno, 'error'=>curl_error($ch));
}
curl_close($ch);
$response = json_decode($response_raw, 1);
if(!is_array($response))
{
$response = ['errno'=>500, 'error'=>$response_raw];
}
//echo '<pre>';
//print_r($response);
return $response;
}
追加:
沃尔玛拉取listing 有下载文件形式的 getReport (系统自动申请报告,只适合 mx和ca站点)
/**
* 下载压缩包->actionGetallitemreport(解压压缩包)
* 拉取Item report
* 返回与沃尔玛平台上设置的Seller项目相关的所有信息。
* /services/walmart/walmartlisting/getzip/account_id/1
*/
public function actionGetZip()
{
ini_set("memory_limit","3000M");
set_time_limit(3600);
$start_time = microtime(true);
$account_id = Yii::app()->request->getParam('account_id');
if ($account_id) {
/******************* 添加执行日志start ***********************/
$execute_param = array(
"type" => 301,
"type_name" => "拉取listing压缩文件",
"keyword" => "getzip",
"exp3" => $account_id,
"exp1" => "walmartlisting",
);
YbModel::model('WalmartExecuteLog')->insertData($execute_param);
/******************* 添加执行日志end ***********************/
$idArr =explode(',',$account_id);
foreach ($idArr as $id){
$walmartPostService = new WalmartListingData($id);
$walmartPostService->getAllItemreport($id);
}
}else{
$accountList = YbModel::model('WalmartAccount')->getInfoByWhere( "status = 1 and site in('mx','ca')", "id");
$accountList = array_column($accountList,'id');
if(!empty($accountList)){
foreach ($accountList as $val){
MHelper::runThreadSOCKET('/services/walmart/walmartlisting/getzip/account_id/'.$val);
sleep(5);
}
}
}
$end_time = microtime(true);
echo '执行完成, 耗时:' . round(($end_time - $start_time), 3).'秒';
exit;
}
/**
* 拉取Item report
* @param $accountId
* @return bool|int
*/
public function getAllItemreport($accountId)
{
$accountInfo = array();
if($this->site=='ca'){
$url = "https://marketplace.walmartapis.com/v3/getReport?type=item_ca"; //v2->v3 更新时间 2019-10-30
$extra = [
"Accept"=>"application/xml",
"Content-Type"=>"application/xml",
];
}elseif($this->site=='us'){
$url = "https://marketplace.walmartapis.com/v3/getReport?type=item"; //v2->v3 更新时间 2019-10-30
$extra = [
"Accept"=>"application/xml",
"content-type"=>"text/plain",
];
}elseif($this->site=='mx'){
$url = "https://marketplace.walmartapis.com/v3/getReport?type=item_mx"; //v2->v3 更新时间 2019-10-30
$extra = [
"Accept"=>"application/xml",
"content-type"=>"text/plain",
];
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$date = date('Ymd');
$path = Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/';
if (!file_exists($path)) {
mkdir(Yii::getPathOfAlias('webroot') . '/upload/erp_log/', 0777);
mkdir($path, 0777);
}
$filename = $path.'walmartreport_'.$date.'_'.$accountId.'.zip'; //设置文件名
//$filename =Yii::app()->params['FILE_BASE_DIR'].'/erp_log/walmartreport/walmartreport_'.$date.'_'.$accountId.'.zip'; //设置文件名
file_put_contents($filename,$result);
}
/**
* @desc 获取要发送的头部信息
* @access protected
* @param string $url 请求沃尔玛的地址
* @param string $method 请求方式
* @param array $account_info 包含私钥的沃尔玛账户信息
* @param array $extra 除默认的头部信息之外每个接口要单独设置的头部信息
*/
protected function getHeaders($url, $method='GET', $account_info, $extra=array())
{
if (empty($url)) {
return false;
}
//默认的而且是必须的头部信息
/* $default = [
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: " . $this->getRandStr(),
"WM_SEC.TIMESTAMP: " . $timestamp,
"WM_SEC.AUTH_SIGNATURE: " . $signature,
"WM_CONSUMER.CHANNEL.TYPE: " . $api_config['channel_type'],
"WM_CONSUMER.ID: " . $api_config['consumer_id'],
"Expect:",
]; */
if($this->site =='ca'){
//获取签名和时间戳
list($signature, $timestamp) = $this->getSignatureAndTimestamp($url, $method, $account_info);
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"WM_SEC.TIMESTAMP" => $timestamp,
"WM_SEC.AUTH_SIGNATURE" => $signature,
"WM_CONSUMER.CHANNEL.TYPE" => $this->channel_type,
"WM_CONSUMER.ID" => $this->consumer_id,
];
} elseif($this->site =='us') {
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"Authorization" => "Basic " . base64_encode($this->client_id . ":" . $this->client_sec),
"WM_SEC.ACCESS_TOKEN" => $this->access_token,
];
}elseif($this->site =='mx') {
$default = [
"WM_MARKET" => "mx",
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"Authorization" => "Basic " . base64_encode($this->client_id . ":" . $this->client_sec),
"WM_SEC.ACCESS_TOKEN" => $this->access_token,
];
}
$ss = array_merge($this->header_params,$default,$extra);
return $this->structureHeaders($ss);
}
基础类 WalmartAp.php
<?php
/**
*沃尔玛请求接口父类文件
*包含了获取沃尔玛接口签名方法,以及组装沃尔玛头部认证的头部信息
*包含了沃尔玛get接口请求实例,以及post接口请求实例
*所有的沃尔玛相关业务接口均继承本类
* @author YB
* @version v3
* @since 1.0
*/
class WalmartApi {
public function __construct() {
}
/**
* @desc 生成沃尔玛相关接口的签名和时间戳
* @access protected
* @param string $url 要请求的接口的完整url包括参数
* @param string $method 请求接口的方式(GET,POST)
* @param array $account_info 包含账户私钥的沃尔玛账户信息
*/
protected function getSignatureAndTimestamp($url, $method, $account_info)
{
//生成以毫秒为单位的时间戳
list($tmp1, $tmp2) = explode(' ', microtime());
$timestamp = (float)sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
//沃尔玛api账户信息包含要签名的私钥
//$api_config = $account_info;
//引入签名的第三方库
Yii::import("application.vendors.*");
include_once "phpseclib/Crypt/RSA.php";
include_once "phpseclib/Math/BigInteger.php";
//待签名的字符
$signature_str = $this->consumer_id . "\n" . $url . "\n" . $method . "\n" . $timestamp . "\n";
$rsa = new Crypt_RSA();
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS8);
$rsa->loadKey($this->private_key); // private key
$rsa->setHash('sha256');
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
$signature = $rsa->sign($signature_str);
//返回签名后的字符和时间戳
return [base64_encode($signature),$timestamp];
}
/**
* @desc 获取要发送的头部信息
* @access protected
* @param string $url 请求沃尔玛的地址
* @param string $method 请求方式
* @param array $account_info 包含私钥的沃尔玛账户信息
* @param array $extra 除默认的头部信息之外每个接口要单独设置的头部信息
*/
protected function getHeadersnew($url, $method='GET', $account_info, $extra=array())
{
if (empty($url)) {
return false;
}
if(!empty($account_info)){
$this->site = $account_info['site'];
$this->client_id = $account_info['client_id'];
$this->client_sec = $account_info['client_sec'];
$this->access_token = $account_info['access_token'];
$this->channel_type = $account_info['channel_type'];
}
if($this->site !='us'){
//获取签名和时间戳
list($signature, $timestamp) = $this->getSignatureAndTimestamp($url, $method, $account_info);
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"WM_SEC.TIMESTAMP" => $timestamp,
"WM_SEC.AUTH_SIGNATURE" => $signature,
"WM_CONSUMER.CHANNEL.TYPE" => $this->channel_type,
"WM_CONSUMER.ID" => $this->consumer_id,
];
} else {
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"Authorization" => "Basic " . base64_encode($this->client_id . ":" . $this->client_sec),
"WM_SEC.ACCESS_TOKEN" => $this->access_token,
];
}
return $this->structureHeaders(array_merge($this->header_params,$default,$extra));
}
/**
* @desc 获取要发送的头部信息
* @access protected
* @param string $url 请求沃尔玛的地址
* @param string $method 请求方式
* @param array $account_info 包含私钥的沃尔玛账户信息
* @param array $extra 除默认的头部信息之外每个接口要单独设置的头部信息
*/
protected function getHeaders($url, $method='GET', $account_info, $extra=array())
{
if (empty($url)) {
return false;
}
//默认的而且是必须的头部信息
/* $default = [
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: " . $this->getRandStr(),
"WM_SEC.TIMESTAMP: " . $timestamp,
"WM_SEC.AUTH_SIGNATURE: " . $signature,
"WM_CONSUMER.CHANNEL.TYPE: " . $api_config['channel_type'],
"WM_CONSUMER.ID: " . $api_config['consumer_id'],
"Expect:",
]; */
if($this->site =='ca'){
//获取签名和时间戳
list($signature, $timestamp) = $this->getSignatureAndTimestamp($url, $method, $account_info);
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"WM_SEC.TIMESTAMP" => $timestamp,
"WM_SEC.AUTH_SIGNATURE" => $signature,
"WM_CONSUMER.CHANNEL.TYPE" => $this->channel_type,
"WM_CONSUMER.ID" => $this->consumer_id,
];
} elseif($this->site =='us') {
$default = [
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"Authorization" => "Basic " . base64_encode($this->client_id . ":" . $this->client_sec),
"WM_SEC.ACCESS_TOKEN" => $this->access_token,
];
}elseif($this->site =='mx') {
$default = [
"WM_MARKET" => "mx",
"WM_SVC.NAME" => "Walmart Marketplace",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"Authorization" => "Basic " . base64_encode($this->client_id . ":" . $this->client_sec),
"WM_SEC.ACCESS_TOKEN" => $this->access_token,
];
}
$ss = array_merge($this->header_params,$default,$extra);
return $this->structureHeaders($ss);
}
/**
* @desc 生成随机的数字和字母的组合的一个字符串
* @access private
* @return string
*/
private function getRandStr()
{
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z",
);
$chars_len = count($chars) - 1;
shuffle($chars);
list($letter, $number) = ["",""];
for ($i=0; $i<4; $i++) {
$letter .= $chars[mt_rand(0, $chars_len)];
$number .= mt_rand(1, 9);
}
return $number . $letter;
}
/**
* @desc get方法请求接口获取请求结果
* @access protected
* @param string $url 请求的接口地址包括参数
* @param array $headers 要设置的头部信息
*/
protected function getResult($url, $headers)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($_GET['istest']==1){
$curlInfo = curl_getinfo($ch);
// var_dump($data);
echo '<pre>';print_r($curlInfo);
}
curl_close($ch);
return $data;
}
/**
* @desc post方法请求接口获取请求结果
* @access protected
* @param string $url 要请求的沃尔玛接口地址
* @param array $body 要发送请求body
* @param array $header 要设置的头部信息
* @param array $formart 返回值类型 xml、json
*/
protected function postResult($url, $body, $header,$formart='json')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_ENCODING,""); // 返回数据支持所有编码,不乱码 ;如果为空字符串"",会发送所有支持的编码类型。
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
$data = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
if($_GET['istest']==1){
var_dump($data);
echo '<pre>';print_r($curlInfo);
$version = curl_version();
echo '<pre>';print_r($version);
}
curl_close($ch);
if($formart == 'json'){
}elseif($formart == 'xml'){
$preg = "/(<|<\/)(?:\w+:)/is";
$newXmlStr = preg_replace($preg,"\\1",$data);
//echo $newXmlStr;
$data = simplexml_load_string($newXmlStr);
$data = $data?$data:array('http_code'=>$curlInfo['http_code']);
}
return $data;
}
/**
* 获取标记已发货接口要发送的请求体的信息
* @access protected
* @param array $params 要标记发货要求发送的请求body信息
*/
protected function getShipOrderRequestBodyData($params)
{
$orderLineArr = array(); //保存多个item
if((isset($params['otherCarrier'])) && ($params['otherCarrier'] == "OTHER-ST")){
foreach( $params['lineNumbers'] as $key=>$val ){
$orderLineArr["orderLine"][] = array(
"lineNumber" => $val,
"orderLineStatuses" => array(
"orderLineStatus" => array(
array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "EACH",
// "amount" => "1",
"amount" => !empty($params['amount'][$val]) && $params['amount'][$val] > 1 ?$params['amount'][$val]:1,
),
"trackingInfo" => array(
"shipDateTime" => $params['shipDateTime'],
"carrierName" => array(
"otherCarrier" => $params['otherCarrier'],
),
"methodCode" => 'Standard',
"trackingNumber" => $params['trackingNumber'],
// "trackingURL" => $params['trackingURL'],
"trackingURL" => 'http://tracking.asendiausa.com/t.aspx?p'
),
),
),
),
);
}
$add_message = array();
$add_message['account_id'] = $params['account_id'];
$add_message['task_name'] = "WALMART_biaoji";
$add_message['start_time'] = date("Y-m-d H:i:s");
$add_message['end_time'] = date("Y-m-d H:i:s");
$add_message['order_id'] = $params['order_id'];
$add_message['platform_order_id'] = $params['platform_order_id'];
$add_message['status'] = 'WALMART';
Yii::app()->db->createCommand()->insert('{{system}}.{{mall_api_log}}', $add_message);
}else{
foreach( $params['lineNumbers'] as $key=>$val ){
$orderLineArr["orderLine"][] = array(
"lineNumber" => $val,
"orderLineStatuses" => array(
"orderLineStatus" => array(
array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "EACH",
// "amount" => "1",
"amount" => !empty($params['amount'][$val]) && $params['amount'][$val] > 1?$params['amount'][$val]:1,
),
"trackingInfo" => array(
"shipDateTime" => $params['shipDateTime'],
"carrierName" => array(
"otherCarrier" => null,
"carrier" => $params['carrier']
),
"methodCode" => $params['methodCode'],
"trackingNumber" => $params['trackingNumber'],
"trackingURL" => $params['trackingURL'],
),
),
),
),
);
}
}
$body = array(
"orderShipment" => array(
"orderLines" => $orderLineArr,
),
);
//返回要发送的json格式数据
return json_encode($body);
}
protected function getShipOrderRequestBodyData_bak($params)
{
$orderLineArr = array(); //保存多个item
foreach( $params['lineNumbers'] as $key=>$val ){
$orderLineArr["orderLine"][] = array(
"lineNumber" => $val,
"orderLineStatuses" => array(
"orderLineStatus" => array(
array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "EA",
"amount" => "1",
),
"trackingInfo" => array(
"shipDateTime" => $params['shipDateTime'],
"carrierName" => array(
"otherCarrier" => null,
"carrier" => $params['carrier']
),
"methodCode" => $params['methodCode'],
"trackingNumber" => $params['trackingNumber'],
//"trackingURL" => $order_info['trackingURL']
),
),
),
),
);
}
$body = array(
"orderShipment" => array(
"orderLines" => $orderLineArr,
),
);
//返回要发送的json格式数据
return json_encode($body);
}
/**
* 获取标记已发货接口要发送的请求体的信息[针对dsv]
* @access protected
* @param array $params 要标记发货要求发送的请求body信息
*/
protected function getShipOrderRequestBodyDataDsv($params){
$orderLineArr = array(); //保存多个item
foreach( $params['lineNumbers'] as $key=>$val ){
$orderLineArr["orderLine"][] = array(
"lineNumber" => $val,
"orderLineStatuses" => array(
"orderLineStatus" => array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "Each",
// "amount" => "1",
"amount" => !empty($params['amount'][$val]) && $params['amount'][$val] > 1?$params['amount'][$val]:1,
),
"trackingInfo" => array(
"shipDateTime" => $params['shipDateTime'],
"carrierName" => array(
//"otherCarrier" => $params['carrier'],
"carrier" => $params['carrier']
),
"methodCode" => $params['methodCode'],
"trackingNumber" => $params['trackingNumber'],
//"trackingURL" => $params['tracking_url']
),
),
),
);
}
$body = array(
"orderLines" => $orderLineArr,
);
//返回要发送的json格式数据
return $this->requestXmlBody($body);
}
/**
* @desc 获取要发送的头部信息[针对dsv]
* @access protected
* @param string $url 请求沃尔玛的地址
* @param string $method 请求方式
* @param array $account_info 包含私钥的沃尔玛账户信息
* @param array $extra 除默认的头部信息之外每个接口要单独设置的头部信息
*/
protected function getHeadersDsv($url, $method='GET', $account_info, $extra=array())
{
if (empty($url)) {
return false;
}
//获取签名和时间戳
list($signature, $timestamp) = $this->getSignatureAndTimestamp($url, $method, $account_info);
//默认的而且是必须的头部信息
/* $default = [
"WM_SVC.NAME: Drop Ship Vendor Services",
"WM_QOS.CORRELATION_ID: " . $this->getRandStr(),
"WM_SEC.TIMESTAMP: " . $timestamp,
"WM_SEC.AUTH_SIGNATURE: " . $signature,
"WM_CONSUMER.CHANNEL.TYPE: " . $api_config['channel_type'],
"WM_CONSUMER.ID: " . $api_config['consumer_id'],
]; */
$default = [
"WM_SVC.NAME" => "Drop Ship Vendor Services",
"WM_QOS.CORRELATION_ID" => $this->getRandStr(),
"WM_SEC.TIMESTAMP" => $timestamp,
"WM_SEC.AUTH_SIGNATURE" => $signature,
"WM_CONSUMER.CHANNEL.TYPE" => $this->channel_type,
"WM_CONSUMER.ID" => $this->consumer_id,
];
//return array_merge($default, $extra);
return $this->structureHeaders(array_merge($this->header_params,$default,$extra));
}
public static function getXmlGeneratorObj() {
return new XmlGenerator();
}
/**
* request xml body
*/
public function requestXmlBody(array $params=array()) {
$xmlObj = self::getXmlGeneratorObj();
$xmlObj->XmlWriter()
->push('ns2:orderShipment', array( 'xmlns:ns2' => 'http://walmart.com/mp/v3/orders','xmlns:ns3' => 'http://walmart.com/'))
->buildXMLFilterArr($params,'',array(),'ns2')
->pop();
return $xmlObj->getXml();
}
/**
* @param string $xmlStr
* @return SimpleXMLElement
*/
public function parseXML($xmlStr = '')
{
$preg = "/(<|<\/)(?:\w+:)/is";
$newXmlStr = preg_replace($preg,"\\1",$xmlStr);
$data = simplexml_load_string($newXmlStr);
return $data;
}
/**
* 对象转关联数组
* @author YB
* @param object $obj
* @return array
*/
public function object_to_array($obj){
$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($_arr as $key => $val){
$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}
/**
* @desc 构建http请求头部
*/
public function structureHeaders(array $headers = []){
$ret = [];
foreach($headers as $key=>$value){
if($key) $ret[] = $key.': '.$value;
}
return $ret;
}
protected function deleteResult($url, $body, $header)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$data = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
if($_GET['istest']==1){
var_dump($data);
echo '<pre>';print_r($curlInfo);
}
curl_close($ch);
$preg = "/(<|<\/)(?:\w+:)/is";
$newXmlStr = preg_replace($preg,"\\1",$data);
//echo $newXmlStr;
$data = simplexml_load_string($newXmlStr);
$data = $data?$data:array('http_code'=>$curlInfo['http_code']);
return $data;
}
}
配置
'header_params' => ['us' => ['WM_SVC.NAME' => 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID' => '',
'WM_SEC.TIMESTAMP' => '',
'WM_SEC.AUTH_SIGNATURE' => '',
'WM_CONSUMER.CHANNEL.TYPE' => '',
'WM_CONSUMER.ID' => '',
'Accept' => 'application/json',
'Expect'=>''],
'mx' => [
'WM_MARKET' => 'mx',
'WM_SVC.NAME' => 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID' => '',
'WM_SEC.TIMESTAMP' => '',
'WM_SEC.AUTH_SIGNATURE' => '',
'WM_CONSUMER.CHANNEL.TYPE' => '',
'WM_CONSUMER.ID' => '',
'Accept' => 'application/json',
'Expect'=>''],
'ca' => ['WM_SVC.NAME' => 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID' => '',
'WM_SEC.TIMESTAMP' => '',
'WM_SEC.AUTH_SIGNATURE' => '',
'WM_CONSUMER.CHANNEL.TYPE' => '',
'WM_CONSUMER.ID' => '',
'WM_TENANT_ID' => 'WALMART.CA',
'WM_LOCALE_ID' => 'en_CA',
'Accept' => 'application/json',
'Content-Type' => 'multipart/form-data'],
'us_dsv' => ['WM_SVC.NAME' => 'Drop Ship Vendor Services',
'WM_QOS.CORRELATION_ID' => '',
'WM_SEC.TIMESTAMP' => '',
'WM_SEC.AUTH_SIGNATURE' => '',
'WM_CONSUMER.CHANNEL.TYPE' => '',
'WM_CONSUMER.ID' => '',
'Accept' => 'application/xml',
'Content-Type' => 'application/xml']
],
解压数据包
/**
* 拉取listing数据 两阶段
* 一阶段:解压压缩包更新数据
* @url /services/walmart/walmartlisting/getallitemreport/account_id/83
*/
public function actionGetallitemreport(){
ini_set("memory_limit","3000M");
set_time_limit(3600);
$start_time = microtime(true);
$account_id = Yii::app()->request->getParam('account_id');
if ($account_id) {
$keyword = date("YmdHis").'_'.$account_id;
/******************* 添加执行日志start ***********************/
$execute_param = array(
"type" => 3,
"type_name" => "listing解压缩",
"keyword" => $keyword,
"exp3" => $account_id,
"exp1" => "walmartlisting",
"exp2" => "getallitemreport",
);
YbModel::model('WalmartExecuteLog')->insertData($execute_param);
/******************* 添加执行日志end ***********************/
$date = date('Ymd');
$filename =Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/walmartreport_'.$date.'_'.$account_id.'.zip'; //设置文件名
if (!file_exists($filename)) {
$message = "未发现压缩文件";
echo $message;
} else {
$walmartPostService = new WalmartListingData($account_id);
$re = $walmartPostService->unZip($account_id, $filename);
$message = "执行完成";
if (!empty($re)) {
$message = "执行异常:".$re;
}
}
//更新日志执行结果
$walmartExecuteLogModel = new WalmartExecuteLog();
$walmartExecuteLogModel->getDbConnection()->createCommand()->update
(
$walmartExecuteLogModel->tableName(),
[
'content'=> $message,
],
"type=3 and keyword='{$keyword}'"
);
}else{
$accountList = YbModel::model('WalmartAccount')->getInfoByWhere( "status = 1 and site in('mx','ca')", "id");
$accountList = array_column($accountList,'id');
$limit = ceil(count($accountList)/100); //每次执行一个账号(4-7点每五分钟一次)
$accountIdList = $this->getExeId($limit,'walmart_listing_account');
if(!empty($accountIdList)){
foreach ($accountIdList as $val){
MHelper::runThreadSOCKET('/services/walmart/walmartlisting/getallitemreport/account_id/'.$val);
}
}
}
$end_time = microtime(true);
echo '执行完成, 耗时:' . round(($end_time - $start_time), 3).'秒';
exit;
}
/**
* 描述:获取需要执行的id
* @author YB
* @param int $limit 每次执行几个
* @return array
*/
private function getExeId($limit,$key=null)
{
if(empty($key)){
$key = 'walmart_listing_account';
}
$ids = EbuyMemcache::getCache($key);
$idsArr = json_decode($ids,true);
if(empty($idsArr))
{
$accountList = YbModel::model('WalmartAccount')->getAccountList();
$ids = array_column($accountList,'id');
}
else
{
$ids = $idsArr;
}
$_ids = $ids;
array_splice($ids,$limit);
$new_ids = array_diff($_ids,$ids);
$str_list = json_encode($new_ids);
EbuyMemcache::setCache($key,$str_list,86400);
return $ids;
}
/**
* 解压压缩包
*/
public function unZip($accountId, $filename) {
if (empty($filename) || empty($accountId)) {
return null;
}
$zip = new ZipArchive;
$res = $zip->open($filename);
if ($res === TRUE) {
//解压缩到log文件夹
$zip->extractTo(Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/');
$file = $zip->getNameIndex(0);
$zip->close();
$file_excel = Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/'.$file;
$file = fopen($file_excel,'r');
$i =0;
$msg = '';
$walmartListingModel = new WalmartListing();
while (($data = fgetcsv($file))!== false) { //每次读取CSV里面的一行内容
if(strpos($this->short_name,'DSV') !==false){ //dsv
continue;
}elseif ($this->site=='ca'){
if($data[0]=='PARTNER ID' && $data[1]=='SKU'){
continue;
}
$sellerSku =trim($data[1],'="');
$sellerSku =trim(trim($sellerSku,'"'));
$item_id = trim($data[15]);
$skuMap = YbModel::model('Walmartskumap')->find("seller_sku ='{$sellerSku}'");
$row =array(
'partner_id' => $data[0],
'seller_sku' => $sellerSku,
'product_name' => $data[2],
'product_category' => $data[3],
'price' => $data[4]?$data[4]:0.00,
'currency' => $data[5],
'buybox_item_price_ca' => $data[6]?$data[6]:0.00,//购物车价格
'buybox_ship_price_ca' => $data[7]?$data[7]:0.00,//购物车运费
'won_buy_box' => $data[8],//WON BUY BOX?
'publish_status' => $data[9],
'status_change_reason' => $data[10],
'lifecycle_status' => $data[11],
'inventory_count' => $data[12]?$data[12]:0,
'ship_method' => $data[13],
'wpid' => $data[14] ? $data[14] : '',
'item_id' => $data[15],
'gtin' => $data[16] ? $data[16] : '',
'upc' => $data[17] ? $data[17] : '',
'main_url' => $data[18],//PRIMARY IMAGE URL
'shelf_name' => $data[19],
'primary_cat_path' => $data[20],
'offer_start_date' => date('Y-m-d H:i:s',strtotime($data[21])),
'offer_end_date' => date('Y-m-d H:i:s',strtotime($data[22])),
'item_creation_date' => date('Y-m-d H:i:s',strtotime($data[23])),
'item_last_updated' => date('Y-m-d H:i:s',strtotime($data[24])),
'item_page_url' => $data[25],
'reviews_count' => $data[26],
'average_rating' => $data[27]?$data[27]:0,
'searchable' => $data[27],
'account_id' => $accountId,
'sku' => $skuMap->sku,
'original_price' => $data[4]?$data[4]:0.00,
);
}elseif ($this->site=='mx'){
if($data[0]=='ID de la Tienda' && $data[1]=='SKU'){
continue;
}
if($data[15]){
$t1 = explode('/',$data[15]);
$t1d = $t1[2].'-'.$t1[1].'-'.$t1[0];
}
if($data[16]){
$t2 = explode('/',$data[16]);
$t2d = $t2[2].'-'.$t2[1].'-'.$t2[0];
}
if($data[17]){
$t3 = explode('/',$data[17]);
$t3d = $t3[2].'-'.$t3[1].'-'.$t3[0];
}
if($data[18]){
$t4 = explode('/',$data[18]);
$t4d = $t4[2].'-'.$t4[1].'-'.$t4[0];
}
$row =array(
'account_id' => $accountId,
'partner_id' => $data[0],
'seller_sku' => $data[1],
'product_name' => $data[2],
'product_category' => $data[3],
'price' => $data[4]?$data[4]:0.00,
'currency' => $data[5],
'publish_status' => $data[6],
'status_change_reason' => $data[7],
'lifecycle_status' => $data[8],
'wpid' => $data[9],
'gtin' => $data[10],
'upc' => $data[11],
'main_url'=> $data[12],
'shelf_name'=> $data[13],
'primary_cat_path'=> $data[14],
'offer_start_date' => date('Y-m-d H:i:s',strtotime($t1d)),
'offer_end_date' => date('Y-m-d H:i:s',strtotime($t2d)),
'item_creation_date' => date('Y-m-d H:i:s',strtotime($t3d)),
'item_last_updated' => date('Y-m-d H:i:s',strtotime($t4d)),
);
}else{
if($data[0]=='PARTNER ID' && $data[1]=='SKU'){
continue;
}
$sellerSku =trim($data[1],'="');
$sellerSku =trim(trim($sellerSku,'"'));
$item_id = trim($data[12]);
$skuMap = YbModel::model('Walmartskumap')->find("seller_sku ='{$sellerSku}'");
$row =array(
'partner_id' => $data[0],
'seller_sku' => $sellerSku,
'product_name' => $data[2],
'product_category' => $data[3],
'price' => $data[4],
'currency' => $data[5],
'publish_status' => $data[6],
'status_change_reason' => $data[7],
'lifecycle_status' => $data[8],
'inventory_count' => $data[9],
'ship_method' => $data[10],
'wpid' => $data[11] ? $data[11] : '',
'item_id' => $data[12],
'gtin' => $data[13] ? $data[13] : '',
'upc' => $data[14] ? $data[14] : '',
'main_url' => $data[15],//PRIMARY IMAGE URL
'shelf_name' => $data[16],
'primary_cat_path' => $data[17],
'offer_start_date' => date('Y-m-d H:i:s',strtotime($data[18])),
'offer_end_date' => date('Y-m-d H:i:s',strtotime($data[19])),
'item_creation_date' => date('Y-m-d H:i:s',strtotime($data[20])),
'item_last_updated' => date('Y-m-d H:i:s',strtotime($data[21])),
'item_page_url' => $data[22],
'reviews_count' => $data[23],
'average_rating' => $data[24],
'searchable' => $data[25],
'account_id' => $accountId,
'sku' => $skuMap->sku,
'original_price' => $data[4],
);
}
if($row['offer_start_date']=='1970-01-01 08:00:00'){
$row['offer_start_date'] = date('Y-m-d H:i:s');
}
if($row['offer_end_date']=='1970-01-01 08:00:00'){
$row['offer_end_date'] = date('Y-m-d H:i:s');
}
if($row['item_creation_date']=='1970-01-01 08:00:00'){
$row['item_creation_date'] = date('Y-m-d H:i:s');
}
if($row['item_last_updated']=='1970-01-01 08:00:00'){
$row['item_last_updated'] = date('Y-m-d H:i:s');
}
$taskRow = $this->getWalmartTaskRowByListing($row["item_id"], $row["sku"], $row["account_id"]);
if(!empty($taskRow)){
$row["task_id"] = $taskRow["id"];
$row["source_type"] = $taskRow["source_type"];
}
$WalmartListingModel = YbModel::model('WalmartListing')->find("account_id = $accountId and seller_sku ='{$sellerSku}' and item_id='{$item_id}'");
if($WalmartListingModel){
if($WalmartListingModel->original_price >0){
unset($row['original_price']);
}
$row['update_time'] = date('Y-m-d H:i:s');
$re_update = $walmartListingModel->getDbConnection()->createCommand()->update(
$walmartListingModel->tableName(),
$row,
"account_id = $accountId and seller_sku ='{$sellerSku}' and item_id='{$item_id}'"
);
if ($re_update) {
$i++;
}
}else{
$row['create_time'] = date('Y-m-d H:i:s');
$model = new WalmartListing();
if(!$model->getDbConnection()->createCommand()->insert($model->tableName(), $row)){
$i++;
}
}
// echo '<pre>'; print_r($data); //此为一个数组,要获得每一个数据,访问数组下标即可
// exit;
}
fclose($file);
fclose($file_excel);
unlink($file);
unlink($file_excel);
unlink($filename);
} else {
return false;
}
return $msg;
}
用item_id去更新listing —— 可以废弃
/**
* 补拉拉取listing
* @url /services/walmart/walmartlisting/repairgetlisting/account_id/2
*/
public function actionRepairGetListing(){
$account_id = Yii::app()->request->getParam('account_id');
$type = Yii::app()->request->getParam('type');
$modellisting = YbModel::model('WalmartListing');
if($type=='see'){
$accountss = Yii::app()->memcache->get('walmart_listing_line');
$lines = json_decode($accountss,true);
VHelper::dump($lines);exit();
}
if($account_id){
$date = date('Y-m-d');
$sqlac = "SELECT item_id FROM yibai_walmart_listing WHERE update_time<'".$date."' and account_id=".$account_id." limit 1000";
$list = $modellisting->getDbConnection()->createCommand($sqlac)->queryColumn();
if($list){
$walmartPostService = new WalmartListingData($account_id);
foreach ($list as $val){
$res = $walmartPostService->getanitems($val);
if($res[0]==200){
$info = json_decode($res[1],true);
if($info['totalItems']>=1){
$arr['price'] = $info['ItemResponse'][0]['price']['amount'];
$arr['currency'] = $info['ItemResponse'][0]['price']['currency'];
$arr['seller_sku'] = $info['ItemResponse'][0]['sku'];
$arr['wpid'] = $info['ItemResponse'][0]['wpid'];
$arr['gtin'] = $info['ItemResponse'][0]['gtin'];
$arr['publish_status'] = $info['ItemResponse'][0]['publishedStatus'];
$arr['lifecycle_status'] = $info['ItemResponse'][0]['lifecycleStatus'];
$arr['update_time'] = date('Y-m-d H:i:s');
$modellisting->updateAll($arr,"account_id={$account_id} and item_id='".$val."'");
}else{
$arr['publish_status'] = 'NOT_SEARCH';
$arr['update_time'] = date('Y-m-d H:i:s');
$modellisting->updateAll($arr,"account_id={$account_id} and item_id='".$val."'");
}
}
}
MHelper::runThreadSOCKET('/services/walmart/walmartlisting/repairgetlisting/account_id/'.$account_id);
sleep(2);
}
}else{
if(Yii::app()->request->getParam('type')=='delete'){
Yii::app()->memcache->delete('walmart_listing_line');
die('删除换成成功');
}
$accountss = Yii::app()->memcache->get('walmart_listing_line');
$lines = json_decode($accountss,true);
if(empty($lines)){
$account = YbModel::model('WalmartAccount');
$accounts = $account->getDbConnection()->createCommand()
->select('id,account_name,MOD(id,10)as line')
->from($account->tableName())
->where('status=1')
->order('id asc')
->queryAll();
$accounts_line=array_column($accounts,null,'id');
foreach($accounts_line as $val){
$lines[$val['line']][] = $val['id'];
}
//Yii::app()->memcache->set('amazon_listing_line',json_encode($lines),5*3600);
}
for($i=0;$i<10;$i++){
if(!empty($lines[$i])){
$account_id = array_shift($lines[$i]);
Yii::app()->memcache->set('walmart_listing_line',json_encode($lines),5*3600);
$url = sprintf('%s/services/walmart/walmartlisting/repairgetlisting/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
echo $url;echo '<br/>';
MHelper::curl_post_async($url);
}else{
continue;
}
}
}
}
public function getanitems($itemid){
$accountInfo = array();
$url = "https://marketplace.walmartapis.com/v3/items/{$itemid}?productIdType=ITEM_ID";
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$res = $this->cur_request($url,'GET','',$headers);
return $res;
}
mx 和 ca 的库存只能通过接口(无法通过申请报告形式)
/**
* 获取库存
* @url /services/walmart/walmartlisting/getinventory
*/
public function actionGetinventory(){
$account_id = Yii::app()->request->getParam('account_id');
$date = Yii::app()->request->getParam('date');
$type = Yii::app()->request->getParam('type');
$modellisting = YbModel::model('WalmartListing');
if($type=='see'){
$accountss = Yii::app()->memcache->get('walmart_listing_inventory');
$lines = json_decode($accountss,true);
VHelper::dump($lines);exit();
}
if($account_id){
$date = $date?$date:date('Y-m-d');
$sqlac = "SELECT seller_sku,item_id FROM yibai_walmart_listing WHERE inventory_updatetime<'".$date."' and account_id=".$account_id." limit 1000";
$list = $modellisting->getDbConnection()->createCommand($sqlac)->queryAll();
if($list){
$walmartPostService = new WalmartListingData($account_id);
foreach ($list as $val){
$res = $walmartPostService->getinventory($val['seller_sku']);
if(isset($res['quantity'])){
$arr['inventory_count'] = $res['quantity']['amount'];
$arr['inventory_updatetime'] = date('Y-m-d H:i:s');
}else{
$arr['inventory_count'] = 0;
$arr['inventory_updatetime'] = date('Y-m-d H:i:s');
}
$modellisting->updateAll($arr,"account_id={$account_id} and item_id='".$val['item_id']."'");
}
MHelper::runThreadSOCKET('/services/walmart/walmartlisting/getinventory/account_id/'.$account_id);
sleep(2);
}
}else{
if(Yii::app()->request->getParam('type')=='delete'){
Yii::app()->memcache->delete('walmart_listing_inventory');
die('删除换成成功');
}
$accountss = Yii::app()->memcache->get('walmart_listing_inventory');
$lines = json_decode($accountss,true);
if(empty($lines)){
$account = YbModel::model('WalmartAccount');
$accounts = $account->getDbConnection()->createCommand()
->select('id,account_name,MOD(id,10)as line')
->from($account->tableName())
->where('status=1 and site in("ca","mx")')
->order('id asc')
->queryAll();
$accounts_line=array_column($accounts,null,'id');
foreach($accounts_line as $val){
$lines[$val['line']][] = $val['id'];
}
//Yii::app()->memcache->set('amazon_listing_line',json_encode($lines),5*3600);
}
for($i=0;$i<10;$i++){
if(!empty($lines[$i])){
$account_id = array_shift($lines[$i]);
Yii::app()->memcache->set('walmart_listing_inventory',json_encode($lines),5*3600);
$url = sprintf('%s/services/walmart/walmartlisting/getinventory/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
echo $url;echo '<br/>';
MHelper::curl_post_async($url);
}else{
continue;
}
}
}
}
获取库存接口
//获取库存
public function getinventory($sku){
$accountInfo = [];
if($this->site=='ca'){
$url = "https://marketplace.walmartapis.com/v3/ca/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}elseif($this->site=='us'){
$url = "https://marketplace.walmartapis.com/v3/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}elseif($this->site=='mx'){
$url = "https://marketplace.walmartapis.com/v3/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$result = json_decode($result,true);
return $result;
}
us 拉取listing和拉取库存 通过申请报告形式的方式 接口文档 Onrequestreports - US - API Reference - Walmart Developer Portal
任务表:
CREATE TABLE `yibai_walmart_listing_task` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`account_id` int(11) NOT NULL DEFAULT '0' COMMENT '账户ID',
`account_name` varchar(50) NOT NULL DEFAULT '' COMMENT '账户名称',
`site` varchar(10) NOT NULL DEFAULT '' COMMENT '站点',
`report_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1:ITEM 2:INVENTORY',
`request_body` text COMMENT '请求报告参数',
`response_body` text COMMENT '请求报告返回',
`status` varchar(50) NOT NULL DEFAULT '' COMMENT '报告状态',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0:未处理 1:已处理',
`requestid` varchar(500) NOT NULL DEFAULT '' COMMENT '申请的requestid',
`is_down` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0:未下载 1:已经下载',
`down_url` varchar(1000) NOT NULL DEFAULT '' COMMENT '下载地址',
`create_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
`update_date` datetime DEFAULT '0000-00-00 00:00:00' COMMENT '修改时间',
PRIMARY KEY (`id`),
KEY `idx_account_id` (`account_id`),
KEY `idx_report_type` (`report_type`),
KEY `idx_status` (`status`),
KEY `idx_type` (`type`),
KEY `idx_is_down` (`is_down`)
) ENGINE=InnoDB AUTO_INCREMENT=217 DEFAULT CHARSET=utf8 COMMENT='拉取listing任务表';
1. 创建任务 report_type=1 listing任务 report_type=2 库存任务
/**
* 创建报告
* @url /services/walmart/walmartlisting/createreporttask
*/
public function actionCreatereporttask(){
$del = Yii::app()->request->getParam('del');
$type = Yii::app()->request->getParam('type');
$id = Yii::app()->request->getParam('id');
$model = YbModel::model('WalmartListingTask');
if($del==1){
if(!$type){
die('参数不对');
}
$model->deleteAll("report_type=".$type);
die('删除us拉取listing的申请报告');
}
if(!$type){
die('参数不对');
}
/*$job = $model->findAll('report_type=1 and create_date>"'.date('Y-m-d').'"');
if($job){die('当天数据已经存在');}*/
$where = '';
if($id){
$where .=' and id='.$id;
}
$sql = "select id,short_name,site from yibai_system.yibai_walmart_account where site='us' and status=1 ".$where;
$list = $model->getDbConnection()->createCommand($sql)->queryAll();
if($list){
$inlist = $indata = [];
$datetime = date('Y-m-d H:i:s');
foreach ($list as $val){
$indata['account_id'] = $val['id'];
$indata['account_name'] = $val['short_name'];
$indata['site'] = $val['site'];
$indata['report_type'] = $type;
$indata['status'] = '';
$indata['type'] = 0;
$indata['is_down'] = 0;
$indata['create_date'] = $datetime;
$inlist[] = $indata;
$indata = [];
}
}
if($inlist){
$model->batchInsertAll($model->tableName(), array_keys($inlist[0]), $inlist, true);
}
echo 'DOLL';
}
2.申请报告
2.1 listing 接口 https://marketplace.walmartapis.com/v3/reports/reportRequests?reportType=ITEM&reportVersion=v4
2.2 库存接口 https://marketplace.walmartapis.com/v3/reports/reportRequests?reportType=INVENTORY&reportVersion=v1
/**
* 申请报告
* @url /services/walmart/walmartlisting/createreport
*/
public function actionCreatereport(){
$model = YbModel::model('WalmartListingTask');
$datetime = date('Y-m-d');
$sql = "select id,account_id,report_type from yibai_walmart_listing_task where report_type in(1,2) and type=0 and is_down=0 and create_date>".$datetime;
$list = $model->getDbConnection()->createCommand($sql)->queryAll();
if($list){
foreach ($list as $val){
$data = [];
$walmartPostService = new WalmartListingData($val['account_id']);
if($account_info->site=='ca'){
$type=$val['report_type']==1?'ITEM_CA':'INVENTORY_CA';
}elseif ($account_info->site=='mx'){
$type=$val['report_type']==1?'ITEM_MX':'INVENTORY_MX';
}elseif ($account_info->site=='us'){
$type=$val['report_type']==1?'ITEM':'INVENTORY';
}
$res = json_decode($walmartPostService->createreportlisting($type),true);
$data['request_body'] = '';
$data['response_body'] = json_encode($res);
$data['update_date'] = date('Y-m-d H:i:s');
if(isset($res['requestId'])){
$data['requestid'] = $res['requestId'];
$data['status'] = $res['requestStatus'];
$data['type'] = 1;
}
$model->updateAll($data,"id=".$val['id']);
}
}
echo 'DOLL';
}
//创建报告请求listing(/v3/reports/reportRequests) ITEM:listing INVENTORY:库存
public function createreportlisting($type){
$accountInfo = [];
if($this->site=='ca'){
$reportVersion = $type=='ITEM_CA'?'v4':'v1';
$url = "https://marketplace.walmartapis.com/v3/ca/reports/reportRequests?reportType=".$type."&reportVersion=".$reportVersion;
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
$body = '';
}elseif($this->site=='us'){
$reportVersion = $type=='ITEM'?'v4':'v1';
$url = "https://marketplace.walmartapis.com/v3/reports/reportRequests?reportType=".$type."&reportVersion=".$reportVersion;
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
$body='';
}elseif($this->site=='mx'){
$reportVersion = $type=='ITEM_MX'?'v4':'v1';
$url = "https://marketplace.walmartapis.com/v3/reports/reportRequests?reportType=".$type."&reportVersion=".$reportVersion;
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->postResult($url, '', $headers,'json');
return $result;
}
3.根据requestid获取报告状态
/**
* 根据requestid获取报告状态
* @url /services/walmart/walmartlisting/getreportstatus
*/
public function actionGetreportstatus(){
$model = YbModel::model('WalmartListingTask');
$datetime = date('Y-m-d');
$sql = "select id,account_id,requestid from yibai_walmart_listing_task where report_type in(1,2) and type=1 and is_down=0 and status in('INPROGRESS','RECEIVED') and create_date>".$datetime;
$list = $model->getDbConnection()->createCommand($sql)->queryAll();
if(!$list){
die('没有数据需要处理');
}
foreach ($list as $val){
$walmartPostService = new WalmartListingData($val['account_id']);
$res = $walmartPostService->getreportstatus($val['requestid']);
if(isset($res['requestId'])){
$model->updateAll(['status'=>$res['requestStatus'],"update_date"=>date('Y-m-d H:i:s')],"id=".$val['id']);
}
}
echo 'DOLL';
}
//报告请求状态(/v3/reports/reportRequests/{requestId})
public function getreportstatus($requestid){
$accountInfo = [];
if($this->site=='ca'){
}elseif($this->site=='us'){
$url = "https://marketplace.walmartapis.com/v3/reports/reportRequests/".$requestid;
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
}elseif($this->site=='mx'){
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$result = json_decode($result,true);
return $result;
}
4.获取所有报告结果 (这个用来查看就行了)
/**
* 获取所有报告结果
* @url /services/walmart/walmartlisting/getallreport
*/
public function actionGetallreport(){
$type = Yii::app()->request->getParam('type');
$id = Yii::app()->request->getParam('id');
$account_id = $id;
$type=$type==1?'ITEM':'INVENTORY';
$walmartPostService = new WalmartListingData($account_id);
$ra = $walmartPostService->getallreport($type);
print_r('<pre>');
print_r($ra);
print_r('</pre>');
exit();
}
//获取所有报告请求(/v3/reports/reportRequests)
public function getallreport($type){
$accountInfo = [];
$url = "https://marketplace.walmartapis.com/v3/reports/reportRequests?reportType=".$type."&reportVersion=v3";
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$result = json_decode($result,true);
return $result;
}
5.解析数据 (因为下载链接 几分钟就失效,所以获取链接了 马上解析数据)
/**
* 解析报告new
* @url /services/walmart/walmartlisting/analysislisting
*/
public function actionAnalysislisting(){
$del = Yii::app()->request->getParam('del');
$account_id = Yii::app()->request->getParam('account_id');
$modeltask = YbModel::model('WalmartListingTask');
$model = new WalmartListing();
$datetime = date('Y-m-d');
if($del==1 && $account_id){
$model->deleteAll("account_id=".$account_id);
die('删除数据成功');
}
$sql = "select id,account_id,report_type,requestid from yibai_walmart_listing_task where report_type=1 and type=1 and is_down=0 and status='READY' and create_date>".$datetime;
$list = $modeltask->getDbConnection()->createCommand($sql)->queryAll();
if(!$list){
$sql = "select id,account_id,report_type,requestid from yibai_walmart_listing_task where report_type=2 and type=1 and is_down=0 and status='READY' and create_date>".$datetime;
$list = $modeltask->getDbConnection()->createCommand($sql)->queryAll();
if(!$list){
die('没有数据需要处理');
}
}
$date = date('Ymd');
$path = Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/';
if (!file_exists($path)) {
mkdir(Yii::getPathOfAlias('webroot') . '/upload/erp_log/', 0777);
mkdir($path, 0777);
}
foreach ($list as $val){
$walmartPostService = new WalmartListingData($val['account_id']);
$res = $walmartPostService->downloadreport($val['requestid']);
if(isset($res['requestId'])){
$modeltask->updateAll(['down_url'=>$res['downloadURL'],"update_date"=>date('Y-m-d H:i:s')],"id=".$val['id']);
}else{
$modeltask->updateAll(['is_down'=>1,"update_date"=>date('Y-m-d H:i:s')],"id=".$val['id']);
continue;
}
$walmartPostService = new WalmartListingData($val['account_id']);
$accountinfo = YbModel::model('WalmartAccount')->findByPk($val['account_id']);
$filename = 'walmartreport_'.$date.'_'.$val['account_id'].'_'.$val['report_type'].'.zip'; //设置文件名
if (!file_exists($path.$filename)){
@unlink($path.$filename);
}
$walmartPostService->getFile($res['downloadURL'],$path,$filename);
$zip = new ZipArchive;
$res = $zip->open($path.$filename);
$datatimes = date('Y-m-d H:i:s');
if ($res === TRUE) {
//解压缩到log文件夹
$zip->extractTo(Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/');
$file = $zip->getNameIndex(0);
$zip->close();
$file_excel = Yii::getPathOfAlias('webroot') . '/upload/erp_log/walmartreport/'.$file;
$file = fopen($file_excel,'r');
$i =0;
$msg = '';
$walmartListingModel = new WalmartListing();
if($val['report_type']==1) {
while (($data = fgetcsv($file)) !== false) { //每次读取CSV里面的一行内容
if ($data[0] == 'SKU' && $data[1] == 'Item ID') {
continue;
}
$item_id = trim($data[1]);
$sellerSku = trim($data[0], '="');
$sellerSku = trim(trim($sellerSku, '"'));
$accountId = $val['account_id'];
$skuMap = YbModel::model('Walmartskumap')->find("seller_sku ='{$sellerSku}'");
$row = array(
'partner_id' => $accountinfo->partner_id,
'seller_sku' => $sellerSku,
'item_id' => $item_id,
'product_name' => $data[2],
'lifecycle_status' => $data[3],
'publish_status' => $data[4],
'status_change_reason' => $data[5],
'product_category' => $data[6],
'price' => $data[7] ? $data[7] : 0.00,
'currency' => $data[8],
'buybox_item_price_ca' => $data[9] ? $data[9] : 0.00,//购物车价格
'buybox_ship_price_ca' => $data[10] ? $data[10] : 0.00,//购物车运费
'wpid' => $data[20] ? $data[20] : '',
'gtin' => $data[21] ? $data[21] : '',
'upc' => $data[22] ? $data[22] : '',
'offer_start_date' => date('Y-m-d H:i:s', strtotime($data[28])),
'offer_end_date' => date('Y-m-d H:i:s', strtotime($data[29])),
'item_creation_date' => date('Y-m-d H:i:s', strtotime($data[30])),
'item_last_updated' => date('Y-m-d H:i:s', strtotime($data[31])),
'reviews_count' => $data[32]?(int)$data[32]:0,
'average_rating' => $data[33] ? $data[33] : 0,
'searchable' => $data[34],
'original_price' => $data[7] ? $data[7] : 0.00,
'account_id' => $accountId,
'item_page_url'=>$data[23] ? $data[23] : '',
'main_url'=>$data[24] ? $data[24] : '',
'sku' => $skuMap->sku,
);
if($row['offer_start_date']=='1970-01-01 08:00:00'){
$row['offer_start_date'] = date('Y-m-d H:i:s');
}
if($row['offer_end_date']=='1970-01-01 08:00:00'){
$row['offer_end_date'] = date('Y-m-d H:i:s');
}
if($row['item_creation_date']=='1970-01-01 08:00:00'){
$row['item_creation_date'] = date('Y-m-d H:i:s');
}
if($row['item_last_updated']=='1970-01-01 08:00:00'){
$row['item_last_updated'] = date('Y-m-d H:i:s');
}
$taskRow = $walmartPostService->getWalmartTaskRowByListing($row["item_id"], $row["sku"], $row["account_id"]);
if (!empty($taskRow)) {
$row["task_id"] = $taskRow["id"];
$row["source_type"] = $taskRow["source_type"];
}
$WalmartListingModel = YbModel::model('WalmartListing')->find("account_id = $accountId and seller_sku ='{$sellerSku}' and item_id='{$item_id}'");
if ($WalmartListingModel) {
if ($WalmartListingModel->original_price > 0) {
unset($row['original_price']);
}
$row['update_time'] = date('Y-m-d H:i:s');
$re_update = $walmartListingModel->getDbConnection()->createCommand()->update(
$walmartListingModel->tableName(),
$row,
"account_id = $accountId and seller_sku ='{$sellerSku}' and item_id='{$item_id}'"
);
if ($re_update) {
$i++;
}
} else {
$row['create_time'] = date('Y-m-d H:i:s');
if (!$model->getDbConnection()->createCommand()->insert($model->tableName(), $row)) {
$i++;
}
}
}
}else{
while (($data = fgetcsv($file)) !== false) { //每次读取CSV里面的一行内容
if ($data[0] == 'SKU' && $data[1] == 'Item ID') {
continue;
}
$WalmartListingModel = $model->find("account_id = {$val['account_id']} and item_id='{$data[1]}'");
if($WalmartListingModel){
$inventory_count = $data[6]?$data[6]:0;
$model->updateAll(['inventory_count'=>$inventory_count,'inventory_updatetime'=>$datatimes],"account_id = {$val['account_id']} and item_id='{$data[1]}'");
}
}
}
}
$modeltask->updateAll(['is_down'=>1,'update_date'=>date('Y-m-d H:i:s')],"id=".$val['id']);
fclose($file);
fclose($file_excel);
unlink($file);
unlink($file_excel);
unlink($filename);
}
echo 'DOLL';
}
//下载报告网址(/v3/reports/downloadReport)
public function downloadreport($requestid){
$accountInfo = [];
if($this->site=='ca'){
}elseif($this->site=='us'){
$url = "https://marketplace.walmartapis.com/v3/reports/downloadReport?requestId=".$requestid;
$extra = [
"Accept"=>"application/json",
"content-type"=>"application/json",
];
}elseif($this->site=='mx'){
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$result = json_decode($result,true);
return $result;
}
/**
* description: 文件下载
* @throws CException
*/
public function getFile($url, $save_dir = '', $filename = '', $type = 0)
{
if (trim($url) == '') {
return false;
}
if (trim($save_dir) == '') {
$save_dir = './';
}
if (0 !== strrpos($save_dir, '/')) {
$save_dir .= '/';
}
//创建保存目录
if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
return false;
}
//获取远程文件所采用的方法
if ($type) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$content = curl_exec($ch);
curl_close($ch);
} else {
ob_start();
readfile($url);
$content = ob_get_contents();
ob_end_clean();
}
//echo $content;
$size = strlen($content);
//文件大小
$fp2 = @fopen($save_dir . $filename, 'a');
@fwrite($fp2, $content);
@fclose($fp2);
unset($content, $url);
return array(
'status' => 1,
'file_name' => $filename,
'save_path' => $save_dir . $filename,
'file_size' => $size
);
}
解析库存
/**
* 获取库存
* @url /services/walmart/walmartlisting/getinventory
*/
public function actionGetinventory(){
$account_id = Yii::app()->request->getParam('account_id');
$date = Yii::app()->request->getParam('date');
$type = Yii::app()->request->getParam('type');
$modellisting = YbModel::model('WalmartListing');
if($type=='see'){
$accountss = Yii::app()->memcache->get('walmart_listing_inventory');
$lines = json_decode($accountss,true);
VHelper::dump($lines);exit();
}
if($account_id){
$date = $date?$date:date('Y-m-d');
$sqlac = "SELECT seller_sku,item_id FROM yibai_walmart_listing WHERE inventory_updatetime<'".$date."' and account_id=".$account_id." limit 1000";
$list = $modellisting->getDbConnection()->createCommand($sqlac)->queryAll();
if($list){
$walmartPostService = new WalmartListingData($account_id);
foreach ($list as $val){
$res = $walmartPostService->getinventory($val['seller_sku']);
if(isset($res['quantity'])){
$arr['inventory_count'] = $res['quantity']['amount'];
$arr['inventory_updatetime'] = date('Y-m-d H:i:s');
}else{
$arr['inventory_count'] = 0;
$arr['inventory_updatetime'] = date('Y-m-d H:i:s');
}
$modellisting->updateAll($arr,"account_id={$account_id} and item_id='".$val['item_id']."'");
}
MHelper::runThreadSOCKET('/services/walmart/walmartlisting/getinventory/account_id/'.$account_id);
sleep(2);
}
}else{
if(Yii::app()->request->getParam('type')=='delete'){
Yii::app()->memcache->delete('walmart_listing_inventory');
die('删除换成成功');
}
$accountss = Yii::app()->memcache->get('walmart_listing_inventory');
$lines = json_decode($accountss,true);
if(empty($lines)){
$account = YbModel::model('WalmartAccount');
$accounts = $account->getDbConnection()->createCommand()
->select('id,account_name,MOD(id,10)as line')
->from($account->tableName())
->where('status=1 and site in("ca","mx")')
->order('id asc')
->queryAll();
$accounts_line=array_column($accounts,null,'id');
foreach($accounts_line as $val){
$lines[$val['line']][] = $val['id'];
}
//Yii::app()->memcache->set('amazon_listing_line',json_encode($lines),5*3600);
}
for($i=0;$i<10;$i++){
if(!empty($lines[$i])){
$account_id = array_shift($lines[$i]);
Yii::app()->memcache->set('walmart_listing_inventory',json_encode($lines),5*3600);
$url = sprintf('%s/services/walmart/walmartlisting/getinventory/account_id/%s', $_SERVER['HTTP_HOST'], $account_id);
echo $url;echo '<br/>';
MHelper::curl_post_async($url);
}else{
continue;
}
}
}
}
//获取库存 这里的 ca和mx 不需要
public function getinventory($sku){
$accountInfo = [];
if($this->site=='ca'){
$url = "https://marketplace.walmartapis.com/v3/ca/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}elseif($this->site=='us'){
$url = "https://marketplace.walmartapis.com/v3/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}elseif($this->site=='mx'){
$url = "https://marketplace.walmartapis.com/v3/inventory?sku=".$sku;
$extra = [
"Accept"=>"application/json",
"Content-Type"=>"application/x-www-form-urlencoded",
];
}
$headers = $this->getHeaders($url, 'GET', $accountInfo, $extra);
$result = $this->getResult($url, $headers);
$result = json_decode($result,true);
return $result;
}
来源:https://www.cnblogs.com/xiangshihua/p/16285202.html |