You can actually do this without any additional code.
WooCommerce supports adding items to the cart via a
?add-to-cart URL parameter.
If you send someone to any page, followed by the URL parameter
?add-to-cart=21 it will automatically add the product with ID 21 to their cart. In this case, you can send them straight to the Checkout page.
This is what your custom URL would look like:
Doing it this way will be much quicker than running a script, and then redirecting to checkout.
Have a project in mind? Get in touch