How to make WordPress return an arbitrary file on a specific request

Sometimes implementing a feature requires placing a specific file at a specific path. An example is integrating Apple Pay via Stripe – it requires the site to respond to a /.well-known/apple-developer-merchantid-domain-association request with a particular file, for verification. Sure the file can just be put on server root, but what if we’re writing a plugin?

init hook to the rescue

A WP plugin can hijack any request to the site by exiting from the init hook. The request path can be read from a PHP $_SERVER global. Then, a static file can be returned by calling file_get_contents.

Here’s the code

add_action(
	'init',
	function () {
		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			$raw_uri = sanitize_text_field(
				wp_unslash( $_SERVER['REQUEST_URI'] )
			);
			if ( '/.well-known/apple-developer-merchantid-domain-association' === $raw_uri ) {
				$path = dirname( __FILE__ ) . '/apple-developer-merchantid-domain-association';
				header( 'content-type: application/octet-stream' );
				echo file_get_contents( $path );
				exit;
			}
		}
	}
);

Leave a comment

Comments (

0

)