Skip to content

Instantly share code, notes, and snippets.

@camaleaun
Last active October 20, 2020 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camaleaun/6956e5af2a0c1ed09d3c43650fc69c28 to your computer and use it in GitHub Desktop.
Save camaleaun/6956e5af2a0c1ed09d3c43650fc69c28 to your computer and use it in GitHub Desktop.
Integration Contact Form 7 with Sales Call
<?php
/**
* Integration Contact Form 7 with Sales Call.
*/
function wpcf7_sales_call_register_service() {
$integration = WPCF7_Integration::get_instance();
$integration->add_category(
'call_request',
__( 'Solicitação de ligação', 'wpcf7-sales-call' )
);
$service = WPCF7_SalesCall::get_instance();
$integration->add_service( 'sales_call', $service );
}
add_action( 'wpcf7_init', 'wpcf7_sales_call_register_service', 10, 0 );
function wpcf7_sales_call_skip_mail( $skip_mail, $contact_form ) {
$service = WPCF7_SalesCall::get_instance();
if ( $service->is_active() && $service->is_valid( $contact_form ) ) {
$skip_mail = true;
}
return $skip_mail;
}
add_filter( 'wpcf7_skip_mail', 'wpcf7_sales_call_skip_mail', 10, 2 );
function wpcf7_sales_call_submit( $contact_form, $result ) {
$service = WPCF7_SalesCall::get_instance();
if ( ! $service->is_active() ) {
return;
}
if ( $contact_form->in_demo_mode() ) {
return;
}
if ( ! $service->is_valid( $contact_form ) ) {
return;
}
$do_submit = true;
$status = empty( $result['status'] ) ? array() : $result['status'];
if ( ! in_array( $status, array( 'mail_sent' ), true ) ) {
$do_submit = false;
}
$do_submit = apply_filters(
'wpcf7_sales_call_submit',
$do_submit,
$contact_form,
$result
);
if ( ! $do_submit ) {
return;
}
$service->request_call( $contact_form );
}
add_filter( 'wpcf7_submit', 'wpcf7_sales_call_submit', 10, 2 );
class WPCF7_SalesCall extends WPCF7_Service {
const SERVICE_NAME = 'sales_call';
const ENDPOINT = 'https://rest.salescall.com.br/rest/integracao';
private static $instance;
private $credentials;
private $contact_form;
private $prefix;
public static function get_instance() {
if ( empty( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
private function __construct() {
$this->prefix = sprintf( '%s_', self::SERVICE_NAME );
$this->credentials = (array) WPCF7::get_option( self::SERVICE_NAME );
}
protected function save_data() {
WPCF7::update_option( self::SERVICE_NAME, $this->credentials );
}
protected function reset_data() {
$this->credentials = null;
$this->save_data();
}
public function get_title() {
return __( 'Sales Call', 'wpcf7-sales-call' );
}
public function is_active() {
return $this->has_credentials();
}
private function has_credentials() {
$user = $this->get_user();
return $user && $this->get_password( $user );
}
public function get_categories() {
return array( 'call_request' );
}
public function icon() {
}
public function link() {
echo sprintf(
'<a href="%1$s">%2$s</a>',
'https://www2.salescall.com.br/',
'salescall.com.br'
);
}
private function get_user() {
if ( empty( $this->credentials ) || ! is_array( $this->credentials ) ) {
return false;
}
$credentials = array_keys( $this->credentials );
return $credentials[0];
}
private function get_password( $user ) {
$credentials = (array) $this->credentials;
if ( ! isset( $credentials[ $user ] ) ) {
return false;
}
return $credentials[ $user ];
}
protected function remote_request( $url, $request = array() ) {
$request = wp_parse_args( $request, array() );
$response = wp_remote_request( esc_url_raw( $url ), $request );
return $response;
}
protected function log( $url, $request, $response ) {
wpcf7_log_remote_request( $url, $request, $response );
}
protected function menu_page_url( $args = '' ) {
$args = wp_parse_args( $args, array() );
$url = menu_page_url( 'wpcf7-integration', false );
$url = add_query_arg( array( 'service' => self::SERVICE_NAME ), $url );
if ( ! empty( $args ) ) {
$url = add_query_arg( $args, $url );
}
return $url;
}
public function load( $action = '' ) {
if ( 'setup' === $action && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
check_admin_referer( 'wpcf7-sales-call-setup' );
if ( ! empty( $_POST['reset'] ) ) {
$this->reset_data();
} else {
$user = isset( $_POST['user'] ) ? trim( $_POST['user'] ) : '';
$password = isset( $_POST['password'] ) ? trim( $_POST['password'] ) : '';
if ( $user and $password ) {
$this->credentials = array( $user => $password );
$this->save_data();
$redirect_to = $this->menu_page_url(
array(
'message' => 'success',
)
);
} else {
$redirect_to = $this->menu_page_url(
array(
'action' => 'setup',
'message' => 'invalid',
)
);
}
}
}
}
public function request_call( WPCF7_ContactForm $contact_form ) {
$this->contact_form = $contact_form;
$request = array(
'method' => 'POST',
'headers' => array(
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8',
),
'body' => json_encode( $this->get_data() ),
);
$response = $this->remote_request( self::ENDPOINT, $request );
$return_code = 0;
$body = wp_remote_retrieve_body( $response );
if ( isset( $body['codigo_retorno'] ) ) {
$return_code = intval( $body['codigo_retorno'] );
}
if ( 1 !== $return_code && WP_DEBUG ) {
$this->log( self::ENDPOINT, $request, $response );
}
}
public function admin_notice( $message = '' ) {
switch ( $message ) {
case 'success':
echo sprintf(
'<div class="updated notice notice-success is-dismissible"><p>%s</p></div>',
esc_html( __( 'Connection established.', 'contact-form-7' ) )
);
break;
case 'failed':
echo sprintf(
'<div class="error notice notice-error is-dismissible"><p><strong>%1$s</strong>: %2$s</p></div>',
esc_html( __( 'Error', 'contact-form-7' ) ),
esc_html( __( 'Failed to establish connection. Please double-check your configuration.', 'contact-form-7' ) )
);
break;
case 'updated':
echo sprintf(
'<div class="updated notice notice-success is-dismissible"><p>%s</p></div>',
esc_html( __( 'Configuration updated.', 'contact-form-7' ) )
);
break;
}
}
public function display( $action = '' ) {
if ( 'documentation' !== $action ) {
echo '<p>' . sprintf(
esc_html(
/* translators: %s: Documentation link */
__( 'O módulo de integração do Sales Call permite que você envie dados de contato coletados por meio dos seus formulários de contato para a API do Sales Call. Você pode criar serviços de solicitação de ligação confiável com facilidade e em poucas etapas. Para obter detalhes, consulte %s', 'wpcf7-sales-call' )
),
wpcf7_link(
$this->menu_page_url( array( 'action' => 'documentation' ) ),
__( 'Integraçao com Sales Call', 'wpcf7-sales-call' )
)
) . '</p>';
if ( $this->is_active() ) {
echo sprintf(
'<p class="dashicons-before dashicons-yes">%s</p>',
esc_html( __( 'Credenciais da API do Sales Call estão definidas.', 'wpcf7-sales-call' ) )
);
}
if ( 'setup' === $action ) {
$this->display_setup();
} else {
echo sprintf(
'<p><a href="%1$s" class="button">%2$s</a></p>',
esc_url( $this->menu_page_url( 'action=setup' ) ),
esc_html( __( 'Setup Integration', 'contact-form-7' ) )
);
}
} else {
$this->display_documentation();
}
}
private function display_setup() {
$user = $this->is_active() ? $this->get_user() : '';
$password = $this->is_active() ? $this->get_password( $user ) : '';
?>
<form method="post" action="<?php echo esc_url( $this->menu_page_url( 'action=setup' ) ); ?>">
<?php wp_nonce_field( 'wpcf7-sales-call-setup' ); ?>
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="user"><?php echo esc_html( __( 'Usuário', 'wpcf7-sales-call' ) ); ?></label></th>
<td>
<?php
if ( $this->is_active() ) {
echo esc_html( $user );
echo sprintf(
'<input type="hidden" value="%1$s" id="user" name="user" />',
esc_attr( $user )
);
} else {
echo sprintf(
'<input type="text" aria-required="true" value="%1$s" id="user" name="user" class="regular-text code" />',
esc_attr( $user )
);
}
?>
</td>
</tr>
<tr>
<th scope="row"><label for="password"><?php echo esc_html( __( 'Senha', 'wpcf7-sales-call' ) ); ?></label></th>
<td>
<?php
if ( $this->is_active() ) {
echo esc_html( wpcf7_mask_password( $password ) );
echo sprintf(
'<input type="hidden" value="%1$s" id="password" name="password" />',
esc_attr( $password )
);
} else {
echo sprintf(
'<input type="text" aria-required="true" value="%1$s" id="password" name="password" class="regular-text code" />',
esc_attr( $password )
);
}
?>
</td>
</tr>
</tbody>
</table>
<?php
if ( $this->is_active() ) {
submit_button(
_x( 'Redefinir credenciais', 'API keys', 'contact-form-7' ),
'small',
'reset'
);
} else {
submit_button(
__( 'Definir credenciais da API do Sales Call', 'wpcf7-sales-call' )
);
}
?>
</form>
<?php
}
private function display_documentation() {
$prefix = $this->prefix;
echo '<p><b>' . wp_kses_post( __( 'Documentação', 'wpcf7-sales-call' ) ) . ':</b></p>';
echo '<p>' . sprintf(
wp_kses_post(
/* translators: %1$s: Campaign property id, %2$s: Mailing property id */
__( 'Nas <b>Configurações Adicionais</b> de cada formulário inclua <code>%1$s</code> e <code>%2$s</code>, além dos demais propriedades com seus respectivos nomes de campo do formulário.', 'wpcf7-sales-call' )
),
'campanha',
'mailing'
) . '</p>';
echo '<p>' . wp_kses_post(
__( 'Todas as propriedades devem estar no formato <code>sales_call_{propriedade}: [valor ou nome de campo do formulário]</code>.', 'wpcf7-sales-call' )
) . '</p>';
echo '<p>' . sprintf(
wp_kses_post(
/* translators: %s: Documentation link */
__( 'As propriedades da <b>Estrutura de dados</b> podem ser consultadas na %1$s.', 'wpcf7-sales-call' )
),
wpcf7_link(
'https://atendimento.salescall.com.br/kb/article/128412/api',
__( 'Documentação oficial', 'wpcf7-sales-call' )
)
) . '</p>';
echo '<p>' . sprintf(
wp_kses_post(
/* translators: %1$s: Campaign property id, %2$s: Mailing property id, %3$s: Phone range property id */
__( 'É importante para correto funcionamento que estejam ao menos <code>%1$s</code>, <code>%2$s</code> e um <code>%3$s</code> estejam definidos, além das credenciais no painel de <b>Integração</b> do <b>Contact Form 7</b>.', 'wpcf7-sales-call' )
),
'campanha',
'mailing',
'telefone{1-10}'
) . '</p>';
echo '<p><b>' . wp_kses_post( __( 'Exemplo', 'wpcf7-sales-call' ) ) . ':</b></p>';
echo "<p id=\"postdivrich\"><textarea id=\"content\" rows=\"5\" class=\"large-text readonly\" readonly>sales_call_campanha: \"C2C\"\nsales_call_mailing: \"LEADS\"\nsales_call_nome: your-name\nsales_call_telefone1: phone\nsales_call_coringa1: your-email</textarea></p>";
}
public function is_valid( WPCF7_ContactForm $contact_form ) {
$this->contact_form = $contact_form;
$credentials = $this->has_credentials();
$campaign = ! empty( $this->get_property( 'campanha', false ) );
$mailing = ! empty( $this->get_property( 'mailing', false ) );
$phones = $this->get_property_range( 'telefone', false );
if ( $credentials && $campaign && $mailing && count( $phones ) ) {
return true;
}
return false;
}
private function get_contat_form_pref_prefixed( $pref ) {
return $this->contact_form->pref( $this->prefix . $pref );
}
private function get_property( $property, $with_key = true ) {
$value_or_field = $this->get_contat_form_pref_prefixed( $property );
$value_or_field = trim( $value_or_field, '"' );
$value = $this->get_field( $value_or_field );
if ( ! $value ) {
$value = $value_or_field;
}
if ( $value && $with_key ) {
$value = array( $property => $value );
}
return $value;
}
private function get_fields() {
$submission = WPCF7_Submission::get_instance();
$fields = array();
$tags = $this->contact_form->scan_form_tags();
foreach ( $tags as $tag ) {
if ( empty( $tag->name ) ) {
continue;
}
$fields[ $tag->name ] = (string) $submission->get_posted_data( $tag->name );
}
return $fields;
}
private function get_field( $field ) {
$fields = $this->get_fields();
$value = null;
if ( isset( $fields[ $field ] ) ) {
$value = $fields[ $field ];
}
return $value;
}
private function get_property_range( $property, $with_key = true ) {
$values = array();
for ( $i = 1; $i <= 10; $i++ ) {
$value = $this->get_property( $property . $i, $with_key );
if ( $value ) {
$values = array_merge( $values, (array) $value );
}
}
return $values;
}
private function get_properties() {
$properties = array(
'campanha',
'mailing',
'nome',
);
foreach ( array( 'telefone', 'coringa' ) as $property ) {
for ( $i = 1; $i <= 10; $i++ ) {
$properties[] = $property . $i;
}
}
return $properties;
}
private function get_lead() {
$lead = array();
foreach ( $this->get_properties() as $property ) {
$value = $this->get_property( $property, false );
if ( $value ) {
$lead[ $property ] = $value;
}
}
return $lead;
}
private function get_data() {
$user = $this->get_user();
$lead = array(
'usuario' => $user,
'senha' => $this->get_password( $user ),
'leads' => array( $this->get_lead() ),
);
return $lead;
}
}
@camaleaun
Copy link
Author

Require the file in functions.php. Change relative path if necessary.

Example:

/**
 * Integration Contact Form 7 with Sales Call
 */
require "cf7-sales-call.php";

If in parent theme use another any wich can overwrited by a child theme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment