Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Enviar notificaciones PUSH a Google API de Firebase Cloud Messaging (V1) usando Python

Tiempo de lectura: 3 minutos

Hoy vamos a aprender cómo podemos enviar un mensaje al endpoint de Firebase Cloud Messaging usando Python. (https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=es-419)

Para ello necesitamos el endpoint de Google:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

Y previamente tenemos que generar un token en nuestra aplicación, para ello vamos a Firebase, seleccionamos nuestro proyecto y pulsamos en Configuración del Proyecto:

Aquí dentro buscamos Cloud Messaging

Ahora vamos a la seccion de API de Firebase Cloud Messaging (V1) y comprobamos que esté habilitada.

Habilitar cloud Messaging (v1)

Ahora buscamos Cuentas de servicio

Cuentas de servicio Firebase

Y generamos una Nueva Clave Privada

Generar nueva clave privada Firebase

este JSON en la raíz del proyecto y creamos un archivo llamado send_push.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
-app.json
-send_push.py
-app.json -send_push.py
-app.json
-send_push.py

Ahora vamos a crear el código send_push.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import json
import requests
import jwt
from datetime import datetime, timedelta
JSON_DIR = "app.json"
def enviar_mensaje_cloud(titulo_enviar, mensaje_enviar, token_enviar):
access_token = get_access_token()
project_id = get_data_json()["project_id"]
url = f'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send'
data = {
'message': {
'token': token_enviar,
'notification': {
'title': titulo_enviar,
'body': mensaje_enviar,
},
'data': {
'key_1': 'Value for key_1',
'key_2': 'Value for key_2',
},
},
}
headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + access_token,
}
response = requests.post(url, json=data, headers=headers)
# Manejar la respuesta según tus necesidades
# Puedes imprimir el resultado para depuración
print(response.text)
def get_access_token():
private_key = get_data_json()["private_key"] # Reemplaza con tu clave privada
cliend_id = get_data_json()["client_id"] # Reemplaza con tu dirección de correo electrónico del cliente
now = datetime.utcnow()
expiration_time = now + timedelta(hours=1)
jwt_payload = {
'iss': cliend_id,
'scope': 'https://www.googleapis.com/auth/firebase.messaging',
'aud': 'https://www.googleapis.com/oauth2/v4/token',
'exp': expiration_time,
'iat': now,
}
encoded_jwt = jwt.encode(jwt_payload, private_key, algorithm='RS256')
data = {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': encoded_jwt,
}
response = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data)
response_data = response.json()
return response_data['access_token']
def get_data_json():
with open(JSON_DIR) as json_file:
data = json.load(json_file)
return data
import json import requests import jwt from datetime import datetime, timedelta JSON_DIR = "app.json" def enviar_mensaje_cloud(titulo_enviar, mensaje_enviar, token_enviar): access_token = get_access_token() project_id = get_data_json()["project_id"] url = f'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send' data = { 'message': { 'token': token_enviar, 'notification': { 'title': titulo_enviar, 'body': mensaje_enviar, }, 'data': { 'key_1': 'Value for key_1', 'key_2': 'Value for key_2', }, }, } headers = { 'Content-type': 'application/json', 'Authorization': 'Bearer ' + access_token, } response = requests.post(url, json=data, headers=headers) # Manejar la respuesta según tus necesidades # Puedes imprimir el resultado para depuración print(response.text) def get_access_token(): private_key = get_data_json()["private_key"] # Reemplaza con tu clave privada cliend_id = get_data_json()["client_id"] # Reemplaza con tu dirección de correo electrónico del cliente now = datetime.utcnow() expiration_time = now + timedelta(hours=1) jwt_payload = { 'iss': cliend_id, 'scope': 'https://www.googleapis.com/auth/firebase.messaging', 'aud': 'https://www.googleapis.com/oauth2/v4/token', 'exp': expiration_time, 'iat': now, } encoded_jwt = jwt.encode(jwt_payload, private_key, algorithm='RS256') data = { 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': encoded_jwt, } response = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data) response_data = response.json() return response_data['access_token'] def get_data_json(): with open(JSON_DIR) as json_file: data = json.load(json_file) return data
import json
import requests
import jwt
from datetime import datetime, timedelta

JSON_DIR = "app.json"

def enviar_mensaje_cloud(titulo_enviar, mensaje_enviar, token_enviar):
    access_token = get_access_token()
    project_id = get_data_json()["project_id"]

    url = f'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send'

    data = {
        'message': {
            'token': token_enviar,
            'notification': {
                'title': titulo_enviar,
                'body': mensaje_enviar,
            },
            'data': {
                'key_1': 'Value for key_1',
                'key_2': 'Value for key_2',
            },
        },
    }

    headers = {
        'Content-type': 'application/json',
        'Authorization': 'Bearer ' + access_token,
    }

    response = requests.post(url, json=data, headers=headers)

    # Manejar la respuesta según tus necesidades
    # Puedes imprimir el resultado para depuración
    print(response.text)

def get_access_token():
    
    private_key = get_data_json()["private_key"]  # Reemplaza con tu clave privada
    cliend_id = get_data_json()["client_id"]  # Reemplaza con tu dirección de correo electrónico del cliente

    now = datetime.utcnow()
    expiration_time = now + timedelta(hours=1)

    jwt_payload = {
        'iss': cliend_id,
        'scope': 'https://www.googleapis.com/auth/firebase.messaging',
        'aud': 'https://www.googleapis.com/oauth2/v4/token',
        'exp': expiration_time,
        'iat': now,
    }

    encoded_jwt = jwt.encode(jwt_payload, private_key, algorithm='RS256')

    data = {
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion': encoded_jwt,
    }

    response = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data)
    response_data = response.json()
    return response_data['access_token']

def get_data_json():
    with open(JSON_DIR) as json_file:
        data = json.load(json_file)
        return data

Deberás cambiar JSON_DIR = «app.json» por la ruta de tu json.

Además hay que instalar jwt:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install PyJWT
pip install PyJWT
 pip install PyJWT

Para enviar un mensaje podrás usar lo siguiente:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enviar_mensaje_cloud('Título del mensaje', 'Cuerpo del mensaje', 'token_del_dispositivo')
enviar_mensaje_cloud('Título del mensaje', 'Cuerpo del mensaje', 'token_del_dispositivo')
enviar_mensaje_cloud('Título del mensaje', 'Cuerpo del mensaje', 'token_del_dispositivo')

Para ‘token_del_dispositivo’, tendrás que usar un Token de dispositivo válido aquí te explico cómo puedes obtenerlo: https://devcodelight.com/?p=7128

0

Deja un comentario