#chiayi

1 messages · Page 1 of 1 (latest)

jade pelicanBOT
lunar fulcrum
#

Did you configure any CSP in your integration?

tame marten
#

yes, this is the CSP config on my server, http://localhost:4242 is where my frontend is being hosted

from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import stripe

app = FastAPI()

origins = [
    "http://localhost:4242/*"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

endpoint_secret = "my_app_secret"
@app.post("/isUserExist")
async def root(request: Request, response: Response):
    payload = await request.json()
    if "stripe-signature" in request.headers:
        sig_header = request.headers["stripe-signature"]
    else:
        sig_header = {}
    payload = {
        "user_id": payload["user_id"],
        "account_id": payload["account_id"]
    }
    try:
        event = stripe.WebhookSignature.verify_header(
            payload, sig_header, endpoint_secret
        )
    except ValueError as e:
        # Invalid payload
        raise e
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        raise e
    # Handle the request by returning a response
    # to acknowledge receipt of the event.
    response.json({ success: true })
    
    return True
lunar fulcrum
#

Why do you need CSP for request of Webhook event from Stripe? The webhook sent from Stripe should never come from frontend/client

tame marten
#

ok sorry, you can ignore the variable event

I was following this doc https://stripe.com/docs/stripe-apps/build-backend#send-a-signed-request-with-additional-data

and I was thinking maybe stripe.webhooks.signature.verifyHeader(request.body, sig, appSecret); (in javascript) is equivalent to event = stripe.WebhookSignature.verify_header( payload, sig_header, endpoint_secret ) (in python)

ultimately, try block will call from an external api that is hosted by my company's own webapp on ec2

#

I am just testing the csp integration using the code in the doc

lunar fulcrum
#

The issue is likely not with Stripe integration, but your CORS settings:

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
#

If you remove this, does the error go away?

tame marten
#

frontend code

const fetchData = async (userContext) => {
  fetch("http://127.0.0.1:8000/isUserExist", { <- this is line 108 where the error was triggered
      method: "POST",
      headers: {
        "Stripe-Signature": await fetchStripeSignature(),
        "Content-Type": "application/json"
      },
      // Include the account ID and user ID in the body to verify on backend.
      body: JSON.stringify({
        user_id: userContext?.id,
      account_id: userContext?.account.id
      }),
    })
  .then(response => {
    console.log(response.json())
  })
}

const Main = ({ userContext, environment }: ExtensionContextValue) => {
  useEffect(() => {
    fetchData(userContext)
  }, []);
  return null;
};
#

i am getting these errors when I remove app.add_middleware (I also got the same errors when I had app.add_middleware)

lunar fulcrum
#

I see! Thanks for sharing

#

From the error message:

stripe-app.json
found violation for connect-src "http://127.0.0.1:8000/isUserExist": protocol has to be https

If you host your code in HTTPS instead of HTTP localhost, will it work?

jade pelicanBOT
tame marten
#

I followed this doc https://web.dev/how-to-use-local-https/#:~:text=Sometimes%2C you need to run,do this safely and quickly.&text=Most of the time%2C http,work on http%3A%2F%2Flocalhost . to generate localhost.pem and localhost-key.pem in order to run http://127.0.0.1:8000/isUserExist as https://127.0.0.1:8000/isUserExist

right now my server is running as https://127.0.0.1:8000/isUserExist and this error message has disappeared stripe-app.json found violation for connect-src "http://127.0.0.1:8000/isUserExist": protocol has to be https
however, ever since I added this new block of code in my server

if __name__ == '__main__':
    # Run a subprocess to return a redirect response from one port to another.
    Popen(['python', '-m', 'api'])  # Add this
    uvicorn.run(
        'api:app', port=8000, host='127.0.0.1',
        reload=True, reload_dirs=['html_files'],
        ssl_keyfile='./localhost.pem',
        ssl_certfile='./localhost-key.pem')

the subprocess keeps running infinitely and https://127.0.0.1:8000/isUserExist is timing out, I will look into this when I'm back at 3pm (GMT+8), you are more than welcome to chip in if you have done this before and you have a hunch how to fix the subprocess from running infinitely