是否可以使用wp_remote_post向第三方api发送http post请求?我无法成功地将用户对象保存为javascript变量,因此我希望能够使用php发出http请求,并在我的节点速递应用程序中处理javascript操作。
目前的尝试:
function identify_user() {
echo "made it into identify user";
if( is_user_logged_in()):
$current_user = wp_get_current_user();
$user = [];
$user['id'] = $current_user->ID;
$user['user_login'] = $current_user->user_login;
$user['user_email'] = $current_user->user_email;
$user['user_firstname'] = $current_user->user_firstname;
$user['user_lastname'] = $current_user->user_lastname;
$user['display_name'] = $current_user->display_name;
$response = wp_remote_post( 'myapp.com/endpoint', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($user)
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
print_r( $response );
}
endif;
}
add_action( 'wp_login', 'identify_user' );
我在排除这段代码时遇到了困难,因为没有一个回显调用是登录到控制台的。我已经看到您可以运行error_log(某些东西),但它也无法运行。
发布于 2018-10-15 22:41:41
“body”需要是一个数组,不包括“json_encode($user)”部分。
$response = wp_remote_post( 'myapp.com/endpoint', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => $user
)
);
我在我的功能中也有这一点,因为我也有身体是一个对象的问题:
if (is_object($user) && !is_array($user))
$user = json_decode(json_encode($user), true);
$body = $user;
关于运行error_log(某物).如果您有问题,请尝试#大卫·李·的包装函数。
基本上你可以打电话
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
// or log data like objects
write_log($object_you_want_to_log);
我不知道没有它我会做什么。
发布于 2018-03-31 03:51:29
请尝试下面的代码可能对您有帮助。
function identify_user() {
if( is_user_logged_in()):
$current_user = wp_get_current_user();
$_id = $current_user->ID;
$_email = $current_user->user_email;
$user = json_encode(array("user_id"=>$_id,"user_email"=>$_email));
$curl = curl_init("myeNDPOINT");
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS,$user);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type:application/json'));
curl_exec( $curl );
curl_close( $curl );
endif;
}
add_action( 'wp_enqueue_scripts', 'identify_user');
发布于 2018-03-31 02:54:48
您可以在下面的代码中尝试wp_remote_post.might,如果您缺少远程post url参数。
另外,我注意到您正在将用户变量转换为json格式2(时间),这是错误的。
$response = wp_remote_post($url, array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'httpversion' => '1.0',
'sslverify' => false,
'body' => json_encode($user)
);
https://wordpress.stackexchange.com/questions/299437
复制相似问题