Retrieve stripe session id at success page - django

I am using stripe with django and I want to pass some information I received from the checkout session to success page.
After reading the documentation https://stripe.com/docs/payments/checkout/custom-success-page#modify-success-url I modified success url to
MY_DOMAIN = 'http://127.0.0.1:8000/orders'
success_url=MY_DOMAIN + '/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=YOUR_DOMAIN + '/cancel/',
metadata={
"price_id": price_id,
}
)
def Success(request):
session = stripe.checkout.Session.retrieve('session_id')
return render(request, 'orders/success.html')
But this gives me an error:
Invalid checkout.session id: session_id
If I manually put instead of "session_id" the actual id that is printed in the url everything works fine.
So my question is what should I write instead of 'session_id' in order to retrieve the session?

When using the prebuilt checkout page, you provide Stripe with the success url to send the user to when they successfully complete a payment. This is done like so:
checkout_session = stripe.checkout.Session.create(
line_items=[{'price': price, 'quantity': 1}],
payment_method_types=['card'],
mode='payment',
success_url="http://yoursite.com/order/success?session_id={CHECKOUT_SESSION_ID}"
cancel_url=domain + cancelURL,
)
return redirect(checkout_session.url)
This will create a Stripe checkout session and send the user to it.
Once the user successfully pays, Stripe will send them to the success_url you provided and put in the correct checkout session id.
You will have to use webhooks to get the data you want, save it to your database, and then query the database in the success page view. Getting the checkout session id from the success page URL will depend on if you are using a GET like in the example above or as part of the URL like https://yoursite.com/order/12345. If you use the GET method, see here for more info.

Related

How can i send a webook to my django app and only execute it on logged in user

Hi i am new to coding and only been learning python and django for about a week. so sorry if this does not make sense.
i am trying to send a webhook(this is just a test then ill add json)
so that when i send to http://127.0.0.1:8000/webhook
i am using postmen desktop so i receive the webhooks.
it will execute my session code but the problem i have that in my app i have
already set up users db and when i sent the webhook it return none since no one seems to be logged in. i know i will have to add a code something like a token to specify each user but only want to test with one user first.
i get the error None or when i remove user authenticated then it says i can't send to anonymous user. is there a way i can send it to lets say a specific user or ID or let's say a token i save with the user.
#csrf_exempt
def webhook(request):
#get current users keys
if request.user.is_authenticated:
user = request.user
database = Bybitapidatas.objects.all().filter(user=user)
for apikey in database:
apikey = apikey.apikey
for apisecret in database:
apisecret = apisecret.apisecret
session = HTTP(endpoint='https://api-testnet.bybit.com/', api_key=apikey, api_secret=apisecret,spot=True)
print(session.place_active_order(
symbol="BTCUSDT",
side="Buy",
type="MARKET",
qty="20",
timeInForce="GTC"
))

how to create a custom session for log in user in Django

I am trying to login a user by sending a post request to an endpoint, the endpoint is returning status of 200 means the user information is true, but what i have been doing previously in django is simplify using authenticate method and passing user_phone and password later setting that resul to login(request, user_phone), now I dont know what to do here as here I am getting a response from that api which is just a user id, can we do something custom for this result.
user_is_authenticated = res['data']['user_id']
print('response',res['data']['user_id'] )
request.session['user_is_authenticated'] = True
print('response',request.session['user_is_authenticated'])
return render(request, "app/com-dashboard.html",{'user_is_authenticated':user_is_authenticated } )
here i am getting user_id, i just want to use user_is_authenticated just like we do in normal django app

Redirect From REST_API Response

I am using Angular and Django in my stack for a website, and after a user registers it emails them a link to activate their account. As of right now everything is working but the link takes the user to the Django rest framework page.
I've been returning responses in my app like this
data = {'success': True, 'message': 'An account has been activated.', 'response': {}}
return Response(data, status=status.HTTP_201_CREATED)
I am curious on how to redirect a user back to the login page which at the current moment would be a localhost page such as http://localhost:4200/#/authentication/login.
From research I have found methods like
return redirect('http://localhost:4200/#/authentication/login')
but I am wanting to keep my responses consistent. Is there a way to redirect a user while still using the rest api Response object?
After thinking about the comment posted by Muhammad Hassan, I realized I was thinking about this all wrong. Instead of sending a Django url I have change the email to send a URL to an Angular page I made and then I just sent an HTTP request from that page to the Django URL.

Django submit form and redirect to payment page then do form stuff

I'm trying to integrate Stripe Checkout to have the customer pay when submitting the form. This integration redirects the customer to Stripe's page to do the payment. How can I make Django remember the input values from the Form after the payment is submitted on the redirected page? Can I create a custom URL that remembers the values?
Also their script requires a payment ID which I serve through a variable but this variable is first created once the form is submitted. I can't change a javascript variable dynamically once the page is rendered, right?
Javascript
<script>
stripe.redirectToCheckout({
sessionId: "{{context}}",
}).then(function (result) {
// Diplay result.error.message to your customer
});
</script>
Python code to create the payment which is called after form submission
stripeUID = str(uuid.uuid4())
payment = stripe.checkout.Session.create(
success_url="https://mypage.com/succes",
cancel_url="https://mypage.com/error",
payment_method_types=["card"],
client_reference_id= stripeUID,
line_items=[
{
"amount": 2000242,
"quantity": 1,
"name": "Blender rendering",
"currency": "usd",
}
]
)
context = payment.id
For the payment ID, use AJAX. Submit the form with Javascript, and in the AJAX response serve the payment ID. then you can use it in the redirect. As for the redirect, you will need to create a model to store the form value against stripe session ID, so when your customer gets redirect back to your website, u can query the table with the session ID to get their original form values.
AJAX calls can be done by using fetch, XMLHttpRequest, jQuery.ajax

Get user uid from Facebook with Django Social Auth

I'm trying to get the user profile picture from Facebook with django-social-auth.
I saw in an other post, that I should get the user uid from Facebook to have access to the profile picture.
How can I get the uid?
From django-social-auth I just installed it and configured the basic stuff to login/logout with django-registrations.
This is my html to login:
Login with FB
How can I do a request to a 'home' view to the user in facebook and get the uid?
I found this in the django-socail-auth docs:
def social_associate_and_load_data(backend, details, response, uid, user,
social_user=None, *args, **kwargs):
"""
The combination of associate_user and load_extra_data functions
of django-social-auth. The reason for combining these two pipeline
functions is decreasing the number of database visits.
"""
extra_data = backend.extra_data(user, uid, response, details)
created = False
if not social_user and user:
social_user, created = UserSocialAuth.objects.get_or_create(
user_id=user.id,
provider=backend.name,
uid=uid,
defaults={'extra_data': extra_data})
if not created and extra_data and social_user.extra_data != extra_data:
social_user.extra_data.update(extra_data)
social_user.save()
return {'social_user': social_user}
Where should I put it in my django app? In views.py? If it yes, how can I activated the view, if I'm just logging in with commom social-auth urls.
Facebook uid is stored in UserSocialAuth instance, you can get it by doing
user.social_auth.get(provider='facebook').uid