'GET', 'callback' => array( __CLASS__, 'route_start' ), 'permission_callback' => function () { return current_user_can( AIEO_CAPABILITY ); }, 'args' => array( 'platform' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_key', ), ), ) ); register_rest_route( 'aieo/v1', '/social/oauth/callback', array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'route_callback' ), 'permission_callback' => '__return_true', ) ); } public static function route_start( $request ) { $platform = sanitize_key( (string) $request->get_param( 'platform' ) ); $url = self::start_url( $platform ); if ( is_wp_error( $url ) ) { return $url; } return rest_ensure_response( array( 'ok' => true, 'authorize_url' => $url, ) ); } public static function start_url( $platform ) { $platform = sanitize_key( (string) $platform ); if ( ! in_array( $platform, AIEO_Social_Store::PLATFORMS, true ) ) { return new WP_Error( 'unknown_platform', __( 'Unknown social platform.', 'ai-eshop-optimizer' ), array( 'status' => 400 ) ); } if ( 'instagram' === $platform ) { return new WP_Error( 'via_facebook', __( 'Instagram Business accounts connect through Facebook: connect Facebook, and the Instagram account linked to each Page comes with it.', 'ai-eshop-optimizer' ), array( 'status' => 400 ) ); } if ( ! AIEO_Social_Store::app_configured( $platform ) ) { return new WP_Error( 'not_configured', __( 'This platform has no app credentials configured yet. Add your app ID and secret first.', 'ai-eshop-optimizer' ), array( 'status' => 400 ) ); } $state = bin2hex( random_bytes( 16 ) ); $store = array( 'platform' => $platform, 'user' => get_current_user_id(), ); if ( 'facebook' === $platform ) { $url = self::facebook_authorize_url( $state ); } else { $conn = self::connector( $platform ); if ( ! $conn ) { return new WP_Error( 'pending', sprintf( __( 'The %s connect leg is not available in this build.', 'ai-eshop-optimizer' ), $platform ), array( 'status' => 501 ) ); } $res = call_user_func( array( $conn, 'authorize_url' ), AIEO_Social_Store::get_app( $platform ), AIEO_Social_Store::redirect_uri( $platform ), $state ); if ( is_wp_error( $res ) ) { return $res; } $url = (string) ( $res['url'] ?? '' ); if ( '' === $url ) { return new WP_Error( 'connector_error', __( 'The platform did not return an authorize URL.', 'ai-eshop-optimizer' ) ); } if ( ! empty( $res['store'] ) && is_array( $res['store'] ) ) { $store = array_merge( $store, $res['store'] ); } } set_transient( self::STATE_PREFIX . hash( 'sha256', $state ), $store, self::STATE_TTL ); return $url; } private static function connector( $platform ) { $map = array( 'x' => 'AIEO_Social_Connector_X', 'linkedin' => 'AIEO_Social_Connector_Linkedin', 'tiktok' => 'AIEO_Social_Connector_Tiktok', ); $map = apply_filters( 'aieo_social_connectors', $map ); if ( empty( $map[ $platform ] ) || ! class_exists( $map[ $platform ] ) ) { return null; } return $map[ $platform ]; } private static function save_accounts( $platform, array $accounts ) { $n = 0; foreach ( $accounts as $a ) { if ( ! is_array( $a ) || empty( $a['external_id'] ) ) { continue; } AIEO_Social_Store::save_account( $platform, array( 'external_id' => sanitize_text_field( (string) $a['external_id'] ), 'name' => isset( $a['name'] ) ? sanitize_text_field( (string) $a['name'] ) : '', 'type' => isset( $a['type'] ) ? sanitize_text_field( (string) $a['type'] ) : '', 'parent_external_id' => isset( $a['parent_external_id'] ) ? sanitize_text_field( (string) $a['parent_external_id'] ) : '', 'access_token' => isset( $a['access_token'] ) ? (string) $a['access_token'] : '', 'refresh_token' => isset( $a['refresh_token'] ) ? (string) $a['refresh_token'] : '', 'token_expires_at' => isset( $a['token_expires_at'] ) ? sanitize_text_field( (string) $a['token_expires_at'] ) : '', 'scopes' => isset( $a['scopes'] ) ? sanitize_text_field( (string) $a['scopes'] ) : '', ) ); $n++; } return $n; } private static function facebook_authorize_url( $state ) { $app = AIEO_Social_Store::get_app( 'facebook' ); $args = array( 'client_id' => isset( $app['app_id'] ) ? $app['app_id'] : '', 'redirect_uri' => AIEO_Social_Store::redirect_uri( 'facebook' ), 'state' => $state, 'response_type' => 'code', 'scope' => 'pages_show_list,pages_manage_posts,pages_read_engagement,business_management', ); return 'https://www.facebook.com/' . self::FB_API . '/dialog/oauth?' . http_build_query( $args ); } public static function route_callback( $request ) { $platform = sanitize_key( (string) $request->get_param( 'platform' ) ); $state = (string) $request->get_param( 'state' ); $code = (string) $request->get_param( 'code' ); $oauth_error = (string) $request->get_param( 'error' ); if ( '' !== $oauth_error ) { self::render_result_page( false, $platform, 0, __( 'Authorization was cancelled or denied.', 'ai-eshop-optimizer' ) ); return; } $ctx = self::consume_state( $state ); if ( is_wp_error( $ctx ) ) { self::render_result_page( false, $platform, 0, $ctx->get_error_message() ); return; } $platform = $ctx['platform']; if ( '' === $code ) { self::render_result_page( false, $platform, 0, __( 'No authorization code was returned.', 'ai-eshop-optimizer' ) ); return; } if ( 'facebook' === $platform ) { $result = self::facebook_complete( $code ); } else { $conn = self::connector( $platform ); if ( ! $conn ) { $result = new WP_Error( 'pending', sprintf( __( 'The %s connect leg is not available in this build.', 'ai-eshop-optimizer' ), $platform ) ); } else { $accounts = call_user_func( array( $conn, 'complete' ), AIEO_Social_Store::get_app( $platform ), $code, AIEO_Social_Store::redirect_uri( $platform ), $ctx ); $result = is_wp_error( $accounts ) ? $accounts : self::save_accounts( $platform, (array) $accounts ); } } if ( is_wp_error( $result ) ) { self::render_result_page( false, $platform, 0, $result->get_error_message() ); return; } self::render_result_page( true, $platform, (int) $result, '' ); } private static function consume_state( $state ) { $state = (string) $state; if ( '' === $state || ! ctype_xdigit( $state ) ) { return new WP_Error( 'bad_state', __( 'Invalid or missing security state.', 'ai-eshop-optimizer' ) ); } $key = self::STATE_PREFIX . hash( 'sha256', $state ); $ctx = get_transient( $key ); if ( ! is_array( $ctx ) || empty( $ctx['platform'] ) ) { return new WP_Error( 'expired_state', __( 'This connection request expired or was already used. Please try again.', 'ai-eshop-optimizer' ) ); } delete_transient( $key ); $ctx['platform'] = sanitize_key( $ctx['platform'] ); return $ctx; } private static function facebook_complete( $code ) { $app = AIEO_Social_Store::get_app( 'facebook' ); if ( empty( $app['app_id'] ) || empty( $app['app_secret'] ) ) { return new WP_Error( 'not_configured', __( 'Facebook app credentials are missing.', 'ai-eshop-optimizer' ) ); } $redirect_uri = AIEO_Social_Store::redirect_uri( 'facebook' ); $base = 'https://graph.facebook.com/' . self::FB_API; $short = self::fb_post( $base . '/oauth/access_token', array( 'client_id' => $app['app_id'], 'client_secret' => $app['app_secret'], 'redirect_uri' => $redirect_uri, 'code' => $code, ) ); if ( is_wp_error( $short ) ) { return $short; } $user_token = isset( $short['access_token'] ) ? (string) $short['access_token'] : ''; if ( '' === $user_token ) { return new WP_Error( 'no_token', __( 'Facebook did not return a user access token.', 'ai-eshop-optimizer' ) ); } $long = self::fb_post( $base . '/oauth/access_token', array( 'grant_type' => 'fb_exchange_token', 'client_id' => $app['app_id'], 'client_secret' => $app['app_secret'], 'fb_exchange_token' => $user_token, ) ); if ( is_wp_error( $long ) ) { return $long; } if ( empty( $long['access_token'] ) ) { return new WP_Error( 'no_long_token', __( 'Facebook did not return a long-lived token — please try connecting again.', 'ai-eshop-optimizer' ) ); } $user_token = (string) $long['access_token']; $accounts = self::fb_get_bearer( $base . '/me/accounts', array( 'fields' => 'id,name,access_token,instagram_business_account{id,username}', 'limit' => 200 ), $user_token ); if ( is_wp_error( $accounts ) ) { return $accounts; } $pages = ( isset( $accounts['data'] ) && is_array( $accounts['data'] ) ) ? $accounts['data'] : array(); if ( empty( $pages ) ) { return new WP_Error( 'no_pages', __( 'No Facebook Pages were found for this account. Make sure you granted Page access.', 'ai-eshop-optimizer' ) ); } $connected = 0; foreach ( $pages as $page ) { if ( empty( $page['id'] ) || empty( $page['access_token'] ) ) { continue; } AIEO_Social_Store::save_account( 'facebook', array( 'external_id' => sanitize_text_field( (string) $page['id'] ), 'name' => isset( $page['name'] ) ? sanitize_text_field( (string) $page['name'] ) : '', 'type' => 'page', 'access_token' => (string) $page['access_token'], 'refresh_token' => '', 'scopes' => 'pages_manage_posts,pages_read_engagement', ) ); $connected++; if ( ! empty( $page['instagram_business_account']['id'] ) ) { $ig = $page['instagram_business_account']; AIEO_Social_Store::save_account( 'instagram', array( 'external_id' => sanitize_text_field( (string) $ig['id'] ), 'name' => isset( $ig['username'] ) ? sanitize_text_field( '@' . $ig['username'] ) : sanitize_text_field( (string) ( $page['name'] ?? 'Instagram' ) ), 'type' => 'ig_business', 'parent_external_id' => sanitize_text_field( (string) $page['id'] ), 'access_token' => (string) $page['access_token'], 'refresh_token' => '', 'scopes' => 'instagram_content_publish,instagram_basic', ) ); } } if ( 0 === $connected ) { return new WP_Error( 'no_pages', __( 'No usable Facebook Pages could be connected.', 'ai-eshop-optimizer' ) ); } return $connected; } private static function fb_post( $url, array $args ) { return self::fb_decode( wp_remote_post( $url, array( 'timeout' => 20, 'sslverify' => true, 'body' => $args, ) ) ); } private static function fb_get_bearer( $url, array $args, $token ) { return self::fb_decode( wp_remote_get( add_query_arg( array_map( 'rawurlencode', $args ), $url ), array( 'timeout' => 20, 'sslverify' => true, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), ) ) ); } private static function fb_decode( $response ) { if ( is_wp_error( $response ) ) { return $response; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) ) { return new WP_Error( 'bad_response', __( 'Unexpected response from Facebook.', 'ai-eshop-optimizer' ) ); } if ( isset( $body['error'] ) ) { $msg = isset( $body['error']['message'] ) ? (string) $body['error']['message'] : __( 'Facebook returned an error.', 'ai-eshop-optimizer' ); return new WP_Error( 'fb_error', $msg ); } $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status < 200 || $status >= 300 ) { return new WP_Error( 'http_error', sprintf( __( 'Facebook request failed (HTTP %d).', 'ai-eshop-optimizer' ), $status ) ); } return $body; } private static function render_result_page( $ok, $platform, $count, $error ) { $platform = sanitize_key( (string) $platform ); $count = (int) $count; $ok = (bool) $ok; $admin_url = admin_url( 'admin.php?page=aieo-social' ); if ( $ok ) { $heading = __( 'Connected', 'ai-eshop-optimizer' ); $detail = sprintf( _n( 'Connected %1$d account on %2$s.', 'Connected %1$d accounts on %2$s.', $count, 'ai-eshop-optimizer' ), $count, $platform ); } else { $heading = __( 'Failed', 'ai-eshop-optimizer' ); $detail = '' !== $error ? $error : __( 'The connection could not be completed.', 'ai-eshop-optimizer' ); } $payload = wp_json_encode( array( 'type' => 'aieo-social-oauth', 'ok' => $ok, 'platform' => $platform, 'count' => $count, ) ); nocache_headers(); status_header( 200 ); header( 'Content-Type: text/html; charset=utf-8' ); ?> > <?php echo esc_html( $heading ); ?>