' . esc_html__( 'MailerLite → Integrations → MailerLite API → Generate new token. This is the new MailerLite (connect.mailerlite.com), not MailerLite Classic.', 'fieldwren' ) . '
'; } public function credential_fields() { return array( 'api_key' => array( 'label' => __( 'API token', 'fieldwren' ), 'type' => 'password', 'required' => true ), ); } private function api( $method, $path, $body = null, $key = null ) { $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . ( null === $key ? $this->cred( 'api_key' ) : $key ) ) ); if ( null !== $body ) { $args['body'] = $body; } return $this->http( $method, 'https://connect.mailerlite.com/api' . $path, $args ); } public function verify( array $creds ) { $b = self::body( $this->api( 'GET', '/groups?limit=1', null, (string) $creds['api_key'] ) ); return is_wp_error( $b ) ? $b : true; } public function options( $source, array $settings ) { if ( 'groups' === $source ) { $b = self::body( $this->api( 'GET', '/groups?limit=250&sort=name' ) ); return is_wp_error( $b ) ? $b : self::pluck( $b['data'] ?? array(), 'id', 'name' ); } if ( 'fields' === $source ) { $b = self::body( $this->api( 'GET', '/fields?limit=100' ) ); if ( is_wp_error( $b ) ) { return $b; } $auto = array( 'name' => 'first_name', 'last_name' => 'last_name', 'phone' => 'phone', 'company' => 'company' ); $out = array(); foreach ( (array) ( $b['data'] ?? array() ) as $f ) { $out[] = array( 'key' => $f['key'], 'label' => $f['name'], 'auto' => $auto[ $f['key'] ] ?? '' ); } return $out; } return parent::options( $source, $settings ); } public function feed_fields( $form_id ) { return array_merge( array( array( 'key' => 'groups', 'type' => 'select', 'multiple' => true, 'source' => 'groups', 'label' => __( 'Groups', 'fieldwren' ) ) ), $this->contact_fields( array( 'email' ) ), array( array( 'key' => 'map', 'type' => 'map', 'source' => 'fields', 'label' => __( 'Fields', 'fieldwren' ) ), array( 'key' => 'double_optin', 'type' => 'toggle', 'label' => __( 'Double opt-in', 'fieldwren' ), 'text' => __( 'Add new subscribers as "unconfirmed" (MailerLite sends the confirmation when double opt-in for API is on)', 'fieldwren' ) ), ) ); } public function process( array $feed, array $entry, array $values ) { $s = $feed['settings']; $c = $this->contact(); $err = $this->require_email( $c ); if ( $err ) { return $err; } $body = array( 'email' => $c['email'] ); $fields = $this->mapped( 'map' ); if ( $fields ) { $body['fields'] = (object) $fields; } $groups = array_values( array_filter( array_map( 'strval', (array) ( $s['groups'] ?? array() ) ) ) ); if ( $groups ) { $body['groups'] = $groups; } if ( ! empty( $s['double_optin'] ) ) { $body['status'] = 'unconfirmed'; } if ( filter_var( $this->ip(), FILTER_VALIDATE_IP ) ) { $body['ip_address'] = $this->ip(); } $res = $this->api( 'POST', '/subscribers', $body ); /* translators: %s email */ return is_wp_error( $res ) ? $res : sprintf( __( '%s saved.', 'fieldwren' ), $c['email'] ); } }