Posts tagged with python

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 am building WhatsApp Flow to retrieve orders. I am receiving the request and decrypting the message successfully. But I have trouble to encrypt response to WhatsApp. I got error: Invalid response from endpoint. I am using Python 3.9 and Pipedream. Some help?

See my encrypt code bellow:

from base64 import b64decode, b64encode from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import json def handler(pd: "pipedream"):     # Getting the decrypted AES key and IV     aes_key_b64 = pd.steps["Decrypt_WhatsApp_Key"]["$return_value"]["decrypted_aes_key"]     iv_b64 = pd.steps["trigger"]["event"]["body"]["initial_vector"]     # Decoding AES key and base64 IV to bytes     aes_key = b64decode(aes_key_b64)     iv = b64decode(iv_b64)     # Preparing the inverted IV     iv_flipped = flip_iv(iv)     # Preparing response     response = {         "version": "3.0",         "screen": "SUCCESS",         "data": {             "extension_message_response": {                 "params": {                     "flow_token": pd.steps["Decrypt_WhatsApp_Message"]["$return_value"]["flow_token"],                     "status": pd.steps["shopify_developer_app"]["$return_value"]["orders"][0]["id"]                 }             }         }     }     response = json.dumps(response)     # Encrypting the response     cipher = Cipher(algorithms.AES(aes_key), modes.GCM(iv_flipped))     encryptor = cipher.encryptor()     encrypted = encryptor.update(response.encode("utf-8")) + encryptor.finalize() + encryptor.tag     encrypted_response = b64encode(encrypted).decode("utf-8")     # Response return     return {         "status": 200,         "body": encrypted_response,         "headers": {             "Content-Type": "application/json"         }     } def flip_iv(iv):     flipped_bytes = []     for byte in iv:         flipped_byte = byte ^ 0xFF         flipped_bytes.append(flipped_byte)     return bytes(flipped_bytes)``` 

I have generated developer_token, access_token and refresh token with googleads read permission. While using in code using google-ads-api I am getting below error.

Code:

from google.ads.googleads.client import GoogleAdsClient googleads_client = GoogleAdsClient.load_from_storage(path="./googleads.yaml", version="v14") 

Error:

  googleads_client = GoogleAdsClient.load_from_storage(path="./googleads.yaml", version="v14") 

I followed this tutorial to generate developer token, access token and refresh_token.

Here is permissions in the app and during authorization screenshot

I was using Google Ads API v12 in python until today (28/08/2023). It's now deprecated and I'm not able to pull data from v13 or v14. Can someone help? My script is very similar to the one on the google documentation. Here they are simply replacing the version number and have

googleads_client = GoogleAdsClient.load_from_storage(version="v14")

https://developers.google.com/google-ads/api/samples/get-account-hierarchy?hl=it#python

Making no changes to this script and running it on my computer I have the following error:

ModuleNotFoundError: No module named 'google.ads.googleads.v14' ValueError: Specified Google Ads API version "v14" does not exist. Valid API versions are: "v8", "v7" 

I have the following packages installed: google-ads 14.0.0 and googleads 39.0.0

Thank you

I am trying to send WhatsApp message, using WhatsApp Business API and GraphQL.

But I am getting this error:

Failed to send message to :  {     "error":{         "message":"(#132012) Parameter format does not match format in the created template",         "type":"OAuthException",         "code":132012,         "error_data": {             "messaging_product":"whatsapp",             "details":"header: Format mismatch, expected IMAGE, received UNKNOWN"         },         "fbtrace_id":"AyPLLsvyikPmg66DWF_ZfYU"     } } 

This is the code I have written. And also I am sharing the message structure.

import requests import openpyxl access_token = "" template_name = "healthy_sports_b2s_2"  # Replace with your template name language_code = "en" wb = openpyxl.load_workbook("numbers.xlsx") sheet = wb.active for row in sheet.iter_rows(min_row=2, values_only=True):     customer_number = row[0]     url = f"https://graph.facebook.com/v17.0/XXXXXXXXXXXXXXX/messages"     headers = {         "Authorization": f"Bearer {access_token}",         "Content-Type": "application/json",     }     message_payload = {         "messaging_product": "whatsapp",         "to": customer_number,         "type": "template",         "template": {"name": template_name, "language": {"code": language_code}},         "components": [             {                 "parameters": [                     {                         "type": "template",                         "image": {                             "link": "https://res.cloudinary.com/dapnrioqr/image/upload/v1691648851/02_wgucrp.jpg"                         },                     }                 ]             }         ],     }     response = requests.post(url, json=message_payload, headers=headers)     if response.status_code == 200:         print(f"Message sent to {customer_number}")     else:         print(f"Failed to send message to {customer_number}: {response.text}") 

What can I do to solve this

This is the actual message