Laravel中如何在认证中传递用户名和密码?含Postman配置
在Laravel里用Http客户端实现Postman的用户名密码认证

从你贴的Postman截图能看到,这里用的是Basic认证(用户名+密码的HTTP基础认证),Laravel Http客户端有现成的方法可以直接实现,不用自己手动拼Authorization头。
修改后的代码:
$response = Http::withHeaders([ 'Content-Type' => 'application/json', ]) // 替换成你在Postman里填的用户名和密码 ->withBasicAuth('你的用户名', '你的密码') ->post( $url.'/wp-json/wc/v3/products', [ 'product' => $product ] );
关键说明:
- 如果你是调用WooCommerce的API,Postman里的「Username」对应WooCommerce的消费者密钥(Consumer Key),「Password」对应消费者密码(Consumer Secret),直接填入
withBasicAuth的两个参数即可。 - Laravel的
withBasicAuth方法会自动生成符合规范的Authorization请求头,无需手动拼接。
如果需要手动构造Authorization头(不推荐,不如用内置方法便捷),可以参考以下代码:
$credentials = base64_encode('你的用户名:你的密码'); $response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Authorization' => "Basic {$credentials}" ]) ->post( $url.'/wp-json/wc/v3/products', [ 'product' => $product ] );
内容的提问来源于stack exchange,提问作者milica98
相关产品推荐
相关产品推荐

