我正在wordpress中使用表格来调用第三方api,并希望在提交后过滤确认文本中的响应。我已经设法在不需要令牌授权的api上使用例如这在我的functions.php中:
add_filter( 'gform_confirmation_4', 'custom_confirmation', 10, 4 );
function custom_confirmation( $confirmation, $form, $entry, $ajax ) {
$response = wp_remote_get( 'https://api.github.com/users/someuser' );
if ( is_wp_error( $response ) ) {
echo 'An error happened';
} else {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
}
$confirmation .= print_r( $data->id, true );
return $confirmation;
}
从json中返回哪个github用户的“ id”值,并将其打印在确认中。
对于我的首先需要授权令牌的受限api,请将其放置在functions.php中
add_filter( 'gform_webhooks_request_headers_4', function ( $request_headers ) {
$token = GFCache::get( 'accessToken' );
if ( ! $token ) {
$post_url = 'https://MyRestrictedApi.com/v1/auth/accesstokenrequest?
name=something&password=something';
$headers = array( 'Content-Type' => 'application/x-url-form-encoded' );
$response = wp_remote_post( $post_url, array( 'body' => $body, 'headers' => $headers ) );
gf_webhooks()->log_debug( 'gform_webhooks_request_headers: response => ' . print_r( $response,
true ) );
if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) == 200 ) {
$response_body_json = wp_remote_retrieve_body( $response );
$response_body_array = json_decode( $response_body_json, true );
if ( isset( $response_body_array['accessToken'] ) ) {
$token = $response_body_array['accessToken'];
GFCache::set( 'accessToken', $token, true, $response_body_array['expires_in'] - 30 );
}
}
}
if ( $token ) {
gf_webhooks()->log_debug( 'gform_webhooks_request_headers: token added.' );
$request_headers['Authorization'] = 'Bearer ' . $token;
}
return $request_headers;
} );
这可以正确发出令牌,因为我可以看到它在表单调试日志中起作用,并在日志中显示来自表单提交的api响应数据。
我一直在尝试组合这两个代码块的等效项,以在调用受限api时将响应打印在表单确认中,该api将上面使用的github演示替换为以下内容。
add_filter( 'gform_confirmation_4', 'custom_confirmation', 10, 4 );
function custom_confirmation( $confirmation, $form, $entry, $ajax ) {
$response = wp_remote_get( 'https://MyRestrictedAPI.com/v1/user/list' );
if ( is_wp_error( $response ) ) {
echo 'An error happened';
} else {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
}
$confirmation .= print_r( $data->id );
return $confirmation;
}
但是结果是它在确认上打印“ 1”(也许是ssl的真值),而“ id” 8864是可以预期的。查看表单的调试日志显示:
(
[body] =>
[method] => GET
[headers] => Array
(
[Authorization] => Bearer 9kcTI3DEChPHgRr3kheHqnGaiBqaeT7MzIQUCZwM-5KLuLpZxL...
)
[sslverify] => 1
)
2020-01-06 9:29:10.110383 - DEBUG --> GF_Webhooks::process_feed(): Webhook successfully executed.
code: 200; body: [{"id":8864,"name": etc...
我是否需要将accessToken放入我的functions.php中的第二个函数中,这就是为什么它不打印响应的原因?有关如何操作的任何提示?谢谢