WordPress电商API插件:仅创建公司无法创建用户求助
问题描述
我正在为WordPress电商网站开发自定义API插件,需求是用户提交结账表单后,先创建公司,再在该公司下创建关联用户。目前仅公司创建返回201状态码,用户创建无响应,且用户相关的error_log未出现在调试日志中。
核心业务函数:注册公司与用户
function hr_register_company_and_user($order_id) { $order = wc_get_order($order_id); $billing_company = $order->get_billing_company(); $firstName = $order->get_billing_first_name(); $lastName = $order->get_billing_last_name(); $email = $order->get_billing_email(); $industry = 'Guide'; $businessType = 'Private'; $employeeCount = 33; $industryClassification = '92 - Public Administration'; $locationName = 'Primary Location'; $zip = 90292; // Prepare data from the order $companyData = [ 'companyName' => $billing_company, 'displayName' => $billing_company, 'industry' => $industry, 'configurationName' => $companyData, 'businessType' => $businessType, 'employeeCount' => $employeeCount, 'industryClassification' => $industryClassification, 'location' => Array ( 'locationName' => $locationName, 'zip' => $zip, ), ]; // Handle product selection for configurationName $items = $order->get_items(); foreach ($items as $item) { $product_id = $item->get_product_id(); $product = wc_get_product($product_id); if (strpos(strtolower($product->get_name()), 'basic') !== false) { $companyData['configurationName'] .= 'HR - Basic;'; } if (strpos(strtolower($product->get_name()), 'essentials') !== false) { $companyData['configurationName'] .= 'HR - Essentials;'; } } $companyData['configurationName'] = rtrim($companyData['configurationName'], ';'); $accessToken = get_access_token(); if (!$accessToken) { error_log('Failed to obtain access token for Platform API'); return; } // Create company via TM API $companyId = create_company($accessToken, $companyData); if (!$companyId) { error_log('Failed to create company via Platform API'); return; } update_post_meta($order_id, 'hrcenteruid', $companyId); // Prepare data for user creation $userData = [ // 'user' => array( 'firstName' => $firstName, 'lastName' => $lastName, 'email' => $email, 'userName' => $email, // Assuming username is the same as email 'role' => 'Employee', // Specify role if necessary 'companyName' => $billing_company, // ) ]; // Create user associated with the company $userId = hr_create_user($accessToken, $userData, $companyId); if (!hr_create_user($accessToken, $userData, $companyId)) { error_log('Failed to create user via Platform API'); } }
获取访问令牌函数
function get_access_token() { $url = 'https://site/v2/oauth/token'; $credentials = base64_encode(CREDS); $body = http_build_query([ 'grant_type' => 'password', 'client_id' => CLIENTID, 'client_secret' => CLIENTSECRET, 'username' => USRNME, 'password' => PSSWRD, ]); $args = [ 'headers' => [ 'Authorization' => 'Basic ' . $credentials, 'Content-Type' => 'application/x-www-form-urlencoded', ], 'body' => $body, 'method' => 'POST', ]; $response = wp_remote_post($url, $args); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) { return false; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); return $data['access_token'] ?? false; }
平台API交互函数(创建公司/用户)
function create_company($accessToken, $companyData) { $url = 'https://site/v2/companies?partnerID=369'; $args = [ 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json', ], 'body' => json_encode($companyData), 'method' => 'POST', ]; $response = wp_remote_request($url, $args); if (is_wp_error($response)) { error_log('WP_Error in create_company: ' . $response->get_error_message()); return false; } $statusCode = wp_remote_retrieve_response_code($response); if ($statusCode != 200) { error_log('API message in create_company: HTTP status code ' . $statusCode . '; Response: ' . wp_remote_retrieve_body($response)); return false; } $body = json_decode(wp_remote_retrieve_body($response), true); return $body['companyId'] ?? false; } function hr_create_user($accessToken, $userData, $companyId) { $url = 'https://site/v2/users?partnerID=369'; $userData['companyId'] = $companyId; // Associate user with the company $args = [ 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json', ], 'body' => json_encode($userData), 'method' => 'POST', ]; $response = wp_remote_request($url, $args); if (is_wp_error($response)) { error_log('WP_Error in create_user: ' . $response->get_error_message()); return false; } $statusCode = wp_remote_retrieve_response_code($response); if ($statusCode != 200) { error_log('API message in create_user: HTTP status code ' . $statusCode . '; Response: ' . wp_remote_retrieve_body($response)); return false; } $body = json_decode(wp_remote_retrieve_body($response), true); return $data['userId'] ?? false; }
排查思路与解决方案
1. 核心错误点定位
hr_create_user函数返回值未定义变量
在hr_create_user函数末尾,代码使用return $data['userId'] ?? false;,但$data从未被定义,正确的变量应为$body,这会导致函数始终返回false,且第一次调用的错误无法被捕获。
重复调用hr_create_user接口
业务函数中先执行$userId = hr_create_user(...),随后在if条件中再次调用该函数,导致两次请求平台API,且第一次请求的结果未被校验,即使失败也不会触发日志。
companyData初始化错误
$companyData数组中'configurationName' => $companyData这行代码错误,此时$companyData尚未完成初始化,会导致configurationName被赋值为无效引用,后续拼接产品名称时生成错误数据,可能影响用户关联流程。
2. 具体修复步骤
修复hr_create_user返回值
将函数末尾代码修改为:
$body = json_decode(wp_remote_retrieve_body($response), true); return $body['userId'] ?? false;
修复重复调用问题
修改业务函数中的用户创建逻辑,仅调用一次并校验结果:
// Create user associated with the company $userId = hr_create_user($accessToken, $userData, $companyId); if (!$userId) { error_log('Failed to create user via Platform API'); }
修复companyData初始化错误
将configurationName初始化为空字符串:
$companyData = [ 'companyName' => $billing_company, 'displayName' => $billing_company, 'industry' => $industry, 'configurationName' => '', // 初始化为空字符串 'businessType' => $businessType, 'employeeCount' => $employeeCount, 'industryClassification' => $industryClassification, 'location' => Array ( 'locationName' => $locationName, 'zip' => $zip, ), ];
3. 额外排查建议
- 开启WordPress调试模式:在
wp-config.php中设置WP_DEBUG = true和WP_DEBUG_LOG = true,确保所有错误日志被捕获。 - 在
hr_create_user函数中添加参数日志:请求前记录$userData内容,确认发送给平台的参数符合要求:
error_log('Sending user data to API: ' . json_encode($userData));
- 核对平台API文档:确认用户创建接口的必填参数结构,比如是否需要用
'user' => array()包裹参数(代码中该部分被注释,若API要求需恢复)。
内容的提问来源于stack exchange,提问作者w_lpz
相关产品推荐
相关产品推荐

