Skip to main content
Solved

Inser subscribe on manychat


Visto.bio

I need help with entering data via API

I built the model and it is only inserting the basic data of the person's name and WhatsApp, but not other data, and I am following the documentation.

for phone and email data it is telling me that I have access denied.

The others were not even included in the contact.

Does anyone know how to give me guidance or send me a model they use?
I'm an account admin

Best answer by Gustavo Boregio

You need to do 2 requests:

  1. createSubscriber > get the User ID here on the reply
  2. setCustomFields > use the User ID that you got before and set the Custom Fields

You won’t be able to do it all in one request as far as I’m aware.

View original

2 replies

Visto.bio
  • Author
  • Up-and-comer
  • March 22, 2024

I need help with entering data via API

I built the model and it is only inserting the basic data of the person's name and WhatsApp, but not other data, and I am following the documentation.

for phone and email data it is telling me that I have access denied.

The others were not even included in the contact.

Does anyone know how to give me guidance or send me a model they use?
I'm an account admin

 

this is my code to send a data iformation 
 


# Configuração da conexão com a API do ManyChat
conn = http.client.HTTPSConnection("api.manychat.com")
headers = {
'Authorization': 'Bearer 3xxxxxxxxx',
'Content-Type': 'application/json'
}

# Dicionário para armazenar informações do cliente
client_data = {}

def format_as_string(value):
"""Converte qualquer valor em string, formatando datas para ISO 8601."""
if isinstance(value, (datetime.date, datetime.datetime)):
return value.isoformat()
elif value is None:
return 'NULL'
else:
return str(value)

for row in results: # Ajuste para a sua estrutura de dados
print(f"Processando CPF: {format_as_string(row['cliente_documento'])}")

# Ajuste as linhas abaixo de acordo com sua estrutura de dados
phone = format_as_string(row.get('client_telefone'))
# Verificar se o telefone está presente e possui um formato válido
if phone:
# Remover caracteres não numéricos do número de telefone
phone = ''.join(filter(str.isdigit, phone))
# Adicionar o código de país "+55" ao número de telefone
phone = f"+55{phone}"
else:
phone = 'NULL'

email = format_as_string(row.get('cliente_email'))
whatsapp_phone = format_as_string(f"+{row.get('cliente_ddi')}{row.get('client_telefone')}") if row.get('cliente_ddi') and row.get('client_telefone') else 'NULL'
waid = format_as_string(row.get('cliente_documento'))

custom_fields = {
"cliente_documento": waid,
"data_criacao": format_as_string(row.get('data_criacao')),
"cobrancas_realizada": format_as_string(row.get('cobrancas_realizada')),
"cliente_id": format_as_string(row.get('cliente_id')),
"status": format_as_string(row.get('status')),
"plano_nome": format_as_string(row.get('plano_nome')),
"plano_valor": format_as_string(row.get('plano_valor')),
"plano_cobrancas": format_as_string(row.get('plano_cobrancas')),
"metodo_de_pagamento": format_as_string(row.get('metodo_de_pagamento')),
"data_fim_prevista": format_as_string(row.get('data_fim_prevista')),
"Vigente": format_as_string(row.get('Vigente')),
"Fonte": format_as_string(row.get('Fonte')),
"last_package_code": format_as_string(row.get('last_package_code')),
"vnda_client_id": format_as_string(row.get('vnda_client_id')),
"ultimo_pedido": format_as_string(row.get('ultimo_pedido')),
"last_expected_delivery_date": format_as_string(row.get('last_expected_delivery_date')),
"last_order_code": format_as_string(row.get('last_order_code')),
"tracking_code_vnda": format_as_string(row.get('tracking_code_vnda')),
"url_rastreamento": format_as_string(row.get('url_rastreamento'))
}

payload = json.dumps({
"first_name": row.get('cliente_nome', '').split()[0] if row.get('cliente_nome') else "",
"last_name": " ".join(row.get('cliente_nome', '').split()[1:]) if row.get('cliente_nome') else "",
"phone": phone,
"email": email,
"whatsapp_phone": whatsapp_phone,
"has_opt_in_sms": True,
"has_opt_in_email": True,
"consent_phrase": "Eu concordo em receber comunicações.",
"custom_fields": custom_fields
})

try:
conn.request("POST", "/fb/subscriber/createSubscriber", body=payload, headers=headers)
response = conn.getresponse()
data = json.loads(response.read().decode("utf-8"))

if response.status != 200:
print(f"Erro ao criar/atualizar assinante para CPF {row.get('cliente_documento')}: {data}")
else:
client_data[row.get('cliente_documento')] = {
"id": data['data']['id'],
"phone": phone,
"email": email
}
print(f"Assinante criado/atualizado com sucesso para CPF {row.get('cliente_documento')}: {data}")
except Exception as e:
print(f"Erro ao processar CPF {row.get('cliente_documento')}: {str(e)}")

time.sleep(0.1)

# Feche a conexão após o processamento
conn.close()

# Imprimir a tabela de dados do cliente
print("\nTabela de dados do cliente:")
print("{:<15} {:<20} {:<20} {:<10}".format('CPF', 'ID ManyChat', 'Email', 'Telefone'))
for cpf, info in client_data.items():
print("{:<15} {:<20} {:<20} {:<10}".format(cpf, info['id'], info['email'], info['phone']))

 


Gustavo Boregio
Forum|alt.badge.img+7
  • Community Moderator & Expert
  • Answer
  • March 22, 2024

You need to do 2 requests:

  1. createSubscriber > get the User ID here on the reply
  2. setCustomFields > use the User ID that you got before and set the Custom Fields

You won’t be able to do it all in one request as far as I’m aware.