Skip to content

Instantly share code, notes, and snippets.

@Lonsdale201
Created December 7, 2024 00:33
Show Gist options
  • Save Lonsdale201/e45932907dd551cc7fb17404113130c0 to your computer and use it in GitHub Desktop.
Save Lonsdale201/e45932907dd551cc7fb17404113130c0 to your computer and use it in GitHub Desktop.
JetFormBuilder - Call webhook - Call Chatgpt
// place the code in the child theme functions.php or a custom code snippets plugin like Fluent Snippts etc..
// You need to add two key in your wp-config.php
// first open your wp-config.php and define( 'OPENAI_API_KEY', 'My_Chatgpt_API');
// add a new line with your auth token: define( 'CUSTOM_API_TOKEN', 'My_auth_token');
// example token define( 'CUSTOM_API_TOKEN', 'a3f9c74d2b69a7e1bcd15e2e4fc98a6c4ed12e9985bcae439f6ad5db95f17c23');
// in the Custom api token you can enter anything
// open your functions.php or fluentsnippets and paste the code which you can find below
// open your jetformbuilder add a new webhook submission and paste your wesbite domain name like
// https://mywebsite.com/wp-json/custom-webhooks/v1/chatgpt-handler?api_token=CUSTOM_API_TOKEN
// in the codes you can change the model, and the instrucitons.
// this example work with two field (field names need to change!)
// user_input this field name -> that chatgpt will receive from the user , feel free to change it
// gpt_answer this field name -> to which chatgpt will send a reply, fel free to change it
// This code do:
// In this example, the chatgpt is instructed to decide from the information mapped from the user whether he has written
// some swear words or phrases. If yes, it returns false. if ok, it returns true.
// What my example does is that the response is submitted to a hidden field, (gpt_answer),
// which I have hooked up to two submissin post submission events, if
// the response is false the submitted post is drafted, if true it is published
// Please note that this code only uses a simple parameter authentication.
// It is strongly recommended to further protect the restapi with other authentication,
// or by introducing a rate limiter. The api key (chatgpt) defined in the wp config is appropriate,
// but this can be modified to other solutions.
// paste this codes
add_action('rest_api_init', function () {
register_rest_route('custom-webhooks/v1', '/chatgpt-handler', [
'methods' => 'POST',
'callback' => 'handle_chatgpt_webhook',
'permission_callback' => function (WP_REST_Request $request) {
$token = $request->get_param('api_token');
// error_log('Received token: ' . $token);
if (!$token || $token !== CUSTOM_API_TOKEN) {
// error_log('Token verification failed.');
return new WP_Error('rest_forbidden', 'Invalid API token.', ['status' => 403]);
}
return true;
},
]);
});
// Use this with the jfb webhook
use Jet_Form_Builder\Exceptions\Action_Exception;
function handle_chatgpt_webhook(WP_REST_Request $request) {
$user_input = $request->get_param('user_input');
// error_log('Webhook received input: ' . print_r($user_input, true));
if (empty($user_input)) {
error_log('Error: No input provided by the user.');
return new WP_Error('no_input', 'User input is required.', ['status' => 400]);
}
// OpenAI API settings
$api_key = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : null;
if (!$api_key) {
// error_log('Error: API key is not defined.');
return new WP_Error('no_api_key', 'API key is not defined.', ['status' => 500]);
}
$endpoint = 'https://api.openai.com/v1/chat/completions';
$response = wp_remote_post($endpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json',
],
'body' => json_encode([
'model' => 'gpt-4o-2024-11-20',
'messages' => [
['role' => 'system', 'content' => 'Check if the input contains offensive words. Respond with "false" if any offensive word is detected, otherwise respond with "true".'],
['role' => 'user', 'content' => $user_input]
],
'max_tokens' => 10, // short answer need it
]),
]);
if (is_wp_error($response)) {
// error_log('Error: API request failed. ' . $response->get_error_message());
return new WP_Error('api_error', 'Failed to communicate with ChatGPT API.', ['status' => 500]);
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (!isset($body['choices'][0]['message']['content'])) {
// error_log('Error: Invalid response from API.');
return new WP_Error('invalid_response', 'Invalid response from ChatGPT.', ['status' => 500]);
}
$response_text = trim($body['choices'][0]['message']['content']);
error_log('Response text to return: ' . $response_text);
return [
'gpt_answer' => $response_text,
];
}
// do someting when webhook success (this example modify a hidden field and populate with the chatgpt response)
add_action('jet-form-builder/action/webhook/response', function ($response, $settings) {
// Get webhook URL
$url = $settings['webhook_url'];
// Check if the webhook URL matches our ChatGPT endpoint
if (false === strpos($url, 'custom-webhooks/v1/chatgpt-handler')) {
return;
}
// Get response code
$response_code = wp_remote_retrieve_response_code($response);
// Check if response is OK
if ($response_code !== 200) {
return;
}
// Get response body
$body = wp_remote_retrieve_body($response);
// Decode JSON response
$data = json_decode($body, true);
if (!is_array($data) || !isset($data['gpt_answer'])) {
return; // if required field missing exit
}
// Update form field 'gpt_answer' with the received value
jet_fb_context()->update_request($data['gpt_answer'], 'gpt_answer');
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment