Posts tagged with django

I am trying to implement Facebook login for my application. It was working well in development mode, but when I try to switch to live mode I see this message:

Feature Unavailable

Facebook Login is currently unavailable for this app, since we are updating additional details for this app. Please try again later.

here is the exact error I get

I do not have any required actions in developer console.

I have searched for an answer, I have already set advanced access to email and public profile, and I got advanced access to other permissions as well. Business verification is complete and I have verified my Business as a tech provider as well.

Here is the code that handles the Facebook login (I am using Django framework):

def facebook_login(request):     facebook_auth_url = "https://www.facebook.com/v21.0/dialog/oauth"     if "test" in request.get_full_path():        redirect_uri = request.build_absolute_uri('/test/home/facebook_login/facebook_callback/')        redirect_uri = "http://localhost:8000/home/facebook_login/facebook_callback/"     else:         redirect_uri = request.build_absolute_uri('/home/facebook_login/facebook_callback/')     scopes = "pages_show_list,business_management,read_insights,ads_read,pages_read_engagement,ads_management"          state = generate_state()     request.session['oauth_state'] = state          params = {         'client_id': settings.META_APP_ID,         'redirect_uri': redirect_uri,         'scope': scopes,         'response_type': 'code',         'state': state,     }     auth_url = f"{facebook_auth_url}?{urlencode(params)}"     return JsonResponse({'authorization_url': auth_url}) def facebook_callback(request):     error = request.GET.get('error')     if error == 'access_denied':         prefix = 'test/' if os.getenv('PROD') == 'blue' else ''         cancel_redirect_url = (             "http://localhost/" + prefix + "#/home/connections"              if os.getenv('DEVELOPMENT') == 'True'              else "https://platform.webalyze.ai/" + prefix + "#/home/connections"         )         return redirect(cancel_redirect_url)          state = request.GET.get('state')     if state != request.session.pop('oauth_state', None):         return JsonResponse({'error': 'Invalid state parameter'}, status=400)     code = request.GET.get('code')     if not code:         return JsonResponse({'error': 'No code provided'}, status=400)     token_exchange_url = "https://graph.facebook.com/v21.0/oauth/access_token"     redirect_uri = request.build_absolute_uri(request.path)     print('REDIRECT (facebook_callback):', redirect_uri)     params = {         'client_id': settings.META_APP_ID,         'redirect_uri': redirect_uri,         'client_secret': settings.META_APP_SECRET,         'code': code,     }     response = requests.get(token_exchange_url, params=params)     data = response.json()     if 'access_token' in data:         access_token = data['access_token']         saveMetaTokenToDatabase(request.user, access_token)         prefix = 'test/' if os.getenv('PROD') == 'blue' else ''         if os.getenv('DEVELOPMENT') == 'True':             return redirect("http://localhost/" + prefix + "#/home/connections")         else:             return redirect("https://platform.webalyze.ai/" + prefix +"#/home/connections")     else:         return JsonResponse({'error': 'Failed to obtain access token'}, status=400) 

What am I missing so I can do this in live mode?

I'm working on a Django API that integrates with the Meta API for WhatsApp product feeds. This endpoint works perfectly on my local machine, but when I deploy it to production, it returns a 504 Gateway Timeout error.

Details:

Local Request (Works):

curl -X POST http://127.0.0.1:8000/api/whatseat/save-changes/ -d "business_id=2"

Production Request (504 Gateway Timeout):

curl -X POST https://<production-url>/api/whatseat/save-changes/ -H "Authorization: Token <token>" -d '{"business_id": 2}'

Key Observations:

  • Error happens only in production—locally, the endpoint works fine.
  • When this endpoint is called without the necessary WhatsApp data, it correctly returns a prompt to complete settings. So, the problem seems to occur during an external API request to the Meta (WhatsApp) API.
 def post(self, request):     business_id = request.data.get('business_id')          try:         whatsapp_business = WhatsApp.objects.get(business=business_id)     except ObjectDoesNotExist:         return Response({"message": "Complete WhatsApp setup in settings"}, status=400)          access_token = whatsapp_business.access_token     product_catalog_id = whatsapp_business.catalog_id          if not all([access_token, product_catalog_id]):         return Response({"error": "Missing Access Token or Catalog ID"}, status=400)     # External API request (seems to be the timeout issue in production)     try:         product_feed_data = request.build_absolute_uri(reverse('get-product-feeds'))         response = requests.get(product_feed_data, params={             'access_token': access_token,             'product_catalog_id': product_catalog_id         })         response.raise_for_status()     except requests.RequestException as e:         return Response({'error': str(e)}, status=500)     # Other logic... (contains another call to graph api for uploading the new data feed) 

Troubleshooting Attempts:

  • Local vs. Production Testing: Locally, the endpoint works without issues.

  • Error Isolation: Confirmed the timeout is likely due to the Meta Products Feed API request.

What might cause a 504 Gateway Timeout when accessing the Meta Products Feed API in production, but not locally? Could this be due to server or network configuration differences, or specific Meta API requirements in production? Any advice on addressing API timeouts in Django would be helpful.

I'm trying to generate the response for the WhatsApp flow using the WhatsApp business API with the following code

The decryption part is functioning correctly, but when I attempt to send the response, I'm receiving the error: "Could not decrypt the response received from the server."

I've referred to the documentation here, but I'm still struggling to find the correct approach for generating and validating the response.

Is there anyone who has experience with this API or can provide guidance on how to properly format and send the response? Any examples or links to relevant resources would be greatly appreciated.

def post(self, request, *args, **kwargs):         try:             dict_data = json.loads(request.body.decode('utf-8'))             encrypted_flow_data_b64 = dict_data['encrypted_flow_data']             encrypted_aes_key_b64 = dict_data['encrypted_aes_key']             initial_vector_b64 = dict_data['initial_vector']                          flipped_iv = self.flip_iv(initial_vector_b64.encode('utf-8'))                          encrypted_aes_key = b64decode(encrypted_aes_key_b64)             key_private = open('*******.pem', 'rb').read().decode('utf-8')             private_key = load_pem_private_key(key_private.encode('utf-8'), password="*************".encode('utf-8'))                          aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))             aes_key_b64 = b64encode(aes_key).decode('utf-8')                          flow_data  = b64decode(encrypted_flow_data_b64)             key = b64decode(aes_key_b64)             iv = b64decode(initial_vector_b64)                          encrypted_flow_data_body = flow_data[:-16]             encrypted_flow_data_tag = flow_data[-16:]             cipher = Cipher(algorithms.AES(key), modes.GCM(iv,encrypted_flow_data_tag))             decryptor = cipher.decryptor()             decrypted_data = decryptor.update(encrypted_flow_data_body) + decryptor.finalize()             flow_data_request_raw = decrypted_data.decode("utf-8")                          hello_world_text = "HELLO WORLD"                          response_data = {                 "version": "3.0",                 "screen": "MY_FIRST_SCREEN",                 "data": {                     "hello_world_text": hello_world_text                 }             }             response_json = json.dumps(response_data)                          # Obtendo a chave AES após descriptografar encrypted_aes_key             fb_aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))             # Usando a chave AES para criptografar a resposta             response_cipher = Cipher(algorithms.AES(fb_aes_key), modes.GCM(iv))             encryptor = response_cipher.encryptor()             encrypted_response = (                 encryptor.update(response_json.encode("utf-8")) +                 encryptor.finalize() +                 encryptor.tag             )             encrypted_response_b64 = b64encode(encrypted_response).decode("utf-8")                          # Construct the final response             final_response = {                 "encrypted_flow_data": encrypted_response_b64,                 "encrypted_aes_key": encrypted_aes_key_b64,                 "initial_vector": initial_vector_b64             }                          return JsonResponse(final_response, status=200)         except Exception as e:             print(e)             return HttpResponse(status=500, content='ok')          def flip_iv(self, iv):         flipped_bytes = []         for byte in iv:             flipped_byte = byte ^ 0xFF             flipped_bytes.append(flipped_byte)         return bytes(flipped_bytes) 

The entire decoding part is working normally but when returning the response I receive the error "Could not decrypt the response received from the server. "I can't find how to send the correct answer or how to validate it. The documentation can be found at https://developers.facebook.com/docs/whatsapp/flows/reference/implementingyourflowendpoint#data_exchange_request

Can anyone help me or show me a link I can test?

I'm trying to get the account name and ID of all the Google Ads accounts that the logged user has access to, so the user can later check the stats of each of those accounts.

I've managed to get the IDs using the code on https://developers.google.com/google-ads/api/docs/account-management/listing-accounts?hl=es-419.

But I need the names too and apparently you have to make one API call for each ID to get their account names or any other info.

I've tried with the following Python (Django) code, but it's not working (it probably could be improved a lot and maybe has mistakes, I'm a Python beginner):

def one(request):     client = credenciales(request)     ga_service = client.get_service("GoogleAdsService")     # Get customer resource names from the original code     customer_service = client.get_service("CustomerService")     accessible_customers = customer_service.list_accessible_customers()     customer_resource_names = accessible_customers.resource_names     # Prepare a list to store customer data     list_clients = []     # Iterate through each customer resource name     for resource_name in customer_resource_names:         # Extract the customer ID from the resource name         custom_id = resource_name.split('/')[-1]         # Create a query using the customer_id         query = f'''             SELECT             customer_client.descriptive_name,             customer_client.id,             customer_client.status             FROM customer_client         '''         stream = ga_service.search_stream(customer_id=custom_id, query=query)                  for batch in stream:             for row in batch.results:                 data_clients = {}                 data_clients["descriptive_name"] = row.customer_client.descriptive_name                 data_clients["id"] = row.customer_client.id                 data_clients["status"] = row.customer_client.status                 list_clients.append(data_clients)     # Pass the list of customer data to the template     context = {         'list_clients': list_clients,     }     return render(request, 'one.html', context) 

It gives me the error "authorization_error: USER_PERMISSION_DENIED" (which I don't understand, because it should be automatically showing the accounts that the user has permission to access, I'm not giving those accounts/IDs manually).

I would like call google ads API with django application and I am unable to find refresh_token

I am using below code

credentials = { 'developer_token': 'xxxx', 'refresh_token': '', 'client_id': 'xxx.apps.googleusercontent.com', 'client_secret': 'xxx'}

adwords_client = GoogleAdsClient.load_from_dict(credentials) 

And getting below code in django

('invalid_request: Missing required parameter: refresh_token', '{\n "error": "invalid_request",\n "error_description": "Missing required parameter: refresh_token"\n}')