Search code examples
pythondjangostripe-connect

Stripe Connect Python


Trying to clean this question up a little, everything works in the stripe connect callback function and I can save stripe user id againt my user, Id like to save the stripe user id againt a related profile model but not sure how to get that model from user=request.user. Any suggestions would be a big help.

class CompanyUser(models.Model):
    email = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=50, null=True, blank=True)
    business_owner = models.CharField(max_length=50, null=True, blank=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True) # validators should be a list
    stripe_user_id = models.CharField(max_length=120, null=True, blank=True)



def stripe_callback(request):
    client_secret = STRIPE_API_KEY
    user = request.user
    code = request.GET.get('code', '')
    data = {
        'grant_type': 'authorization_code',
        'client_secret': 'sk_test_5SLLtqWFDTqzdbYmBz4XZpSX',
        'client_id': 'ca_ANdfv3rlKvpOU3rDglk6qoXuBYqGYiq5',
        'code': code,
    } 
    url = 'https://connect.stripe.com/oauth/token'
    resp= requests.post(url, params=data)  
    stripe_payload = json.loads(resp.text)
    stripe_user_id = stripe_payload['stripe_user_id']
    user.stripe_user_id = stripe_user_id 
    user.save()

Solution

  • This worked so posting incase it may help anyone else, thank you to dirkgroten below in the comments.

     def stripe_callback(request):
    
        client_secret = STRIPE_API_KEY
        # the temporary code returned from stripe
        user = request.user.companyuser
        code = request.GET.get('code', '')
        # identify what we are going to ask for from stripe
        data = {
            'grant_type': 'authorization_code',
            'client_secret': 'sk_test_secretstuff',
            'client_id': 'ca_secretstuff',
            'code': code,
        }
        # Get the access_token using the code provided
        url = 'https://connect.stripe.com/oauth/token'
        resp= requests.post(url, params=data)
    
        stripe_payload = json.loads(resp.text)
    
        print(stripe_payload)
    
        stripe_user_id = stripe_payload['stripe_user_id']
    
        user.stripe_user_id = stripe_user_id
        print(stripe_user_id)
        user.save()