You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xero SDK v2创建工时表返回400 Bad Request错误如何解决

Xero SDK v2 工时表提交错误修复方案

你的代码存在以下4处关键错误,对应修改即可:

  • 变量名大小写不匹配:你提前定义了$startDate和$endDate,但调用setStartDate、setEndDate时传入了未定义的$Start_Date、$End_Date变量
  • 创建工时表接口参数错误:你预先把构造好的工时表存入了$emp_timeSheet数组,但调用createTimesheet时传入了未定义的$krr变量
  • 工时单位参数格式错误:你手动拼接了字符串格式的数组"[x.x,y.y]"传给setNumberOfUnits,实际上该方法接收浮点型数组,SDK会自动完成序列化
  • 工时行赋值逻辑错误:循环内每次调用setTimesheetLines会覆盖之前的工时行,且你传入了带TimesheetLines键的关联数组,正确逻辑是先把所有工时行存入索引数组,最后统一赋值

修正后代码

require __DIR__ . '/xero-auth/vendor/autoload.php';
$config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken(xxxxxxxxx);
$apiInstance = new XeroAPI\XeroPHP\Api\PayrollAuApi(
    new GuzzleHttp\Client(),
    $config
);
$xeroTenantId = "xxxxxxxxxxxxxxxxxxx";
$emp_timeSheet = array();
$startDate = new DateTime('2021-09-20');
$endDate = new DateTime('2021-10-03');
$timesheet = new XeroAPI\XeroPHP\Models\PayrollAu\Timesheet; 
if($timesheet_id != '') $timesheet->setTimesheetId($timesheet_id);
$timesheet->setEmployeeId($employee_id);
// 修正变量名大小写问题
$timesheet->setStartDate($startDate);                 
$timesheet->setEndDate($endDate); 
$timesheet->setStatus(XeroAPI\XeroPHP\Models\PayrollAu\TimesheetStatus::DRAFT);

// 先初始化工时行索引数组
$timesheetLines = [];
if(count($timelines)>0){                    
    foreach ($timelines as $timeline) {
        $payItem = $this->xero_model->getPayItem($timeline['EarningsRateKey']); 
        if(!empty($payItem)) {
            $timesheetLine = new XeroAPI\XeroPHP\Models\PayrollAu\TimesheetLine;
            $timesheetLine->setEarningsRateId($payItem['EarningsRateID']);
            // 直接组装浮点型数组,不要手动拼字符串
            $units = [];
            foreach ($timeline['hours'] as $hour) { 
                $units[] = (float)number_format($hour, 1);                         
            }
            $timesheetLine->setNumberOfUnits($units);
            // 把当前工时行加入数组,不要直接覆盖
            $timesheetLines[] = $timesheetLine;                                   
        }
    }
    // 循环结束后统一赋值所有工时行,直接传索引数组
    $timesheet->setTimesheetLines($timesheetLines);
}  

array_push($emp_timeSheet, $timesheet);
try { 
    if($timesheet_id == ''){
        // 修正参数为正确的$emp_timeSheet数组
        $result = $apiInstance->createTimesheet($xeroTenantId, $emp_timeSheet);  
    }else{
        $result = $apiInstance->updateTimesheet($xeroTenantId, $timesheet_id, $emp_timeSheet);
    } 
} catch (Exception $e) {
    // 可自行加异常处理逻辑
    echo $e->getMessage();
}

内容的提问来源于stack exchange,提问作者Guri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:15:03