Wp_remote_postを使用してhttp投稿リクエストをサードパーティのapiに送信することは可能ですか?ユーザーオブジェクトを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' );
私のecho呼び出しはどれもコンソールにログインしていないため、このコードのトラブルシューティングに問題があります。私はあなたがerror_log(何か)を実行することができることを見ましたが、それをうまく動かすこともできませんでした。
'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;
あなたが問題を抱えている 'run error_log(something)...'に関しては、 #David Leeのラッパー関数を試してください
基本的にあなたは呼び出すことができます
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
// or log data like objects
write_log($object_you_want_to_log);
私はそれがなければ何ができるかわからない。
以下のコードを試してみてください。
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');
リモート投稿のURLパラメータがない場合は、以下のwp_remote_post.mightのコードを試すことができます。
また、私はあなたがユーザー変数を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)
);