How to link a phone to a user

Dears, good evening.

I have some questions regarding the creation of Telephones from the tab ("Phone Management" on the platform) via API. From the documentation I followed this instruction

I even managed to create a WebRTC phone, I managed to link it to a WebRTC person, but what I need is, via API, to go to the user and add a default phone for him and that's what I'm having difficulty with, because in the documentation I didn't find anything related to make PUT on 'phones'.
I need to know which URL I should use to link a phone to a user

Thanks in advance!

Forgive me if I've misread your question, but it sounds like you're looking for something in the StationsAPI to select the users phone. I can't recall exactly, but you'd first get the station by user id:

get_stations

Then you use:

put_user_station_defaultstation_station_id

Hope this at leasts points in the right direction.

So I tried using
PUT /api/v2/users/{userId}/station/defaultstation/{stationId}

However, when collecting the phone ID I created and putting it into the stationId variable, a station with that ID is not found.
I don't know if the problem is with the way I'm creating the phone and that's resulting in the error.

This is the code I'm using to
• Create a user
• Add it to a permissions group
• Create a Phone/station
• Add phone/station to user

import base64, requests, sys, os
import pandas as pd
import json


URL = 'https://login.sae1.pure.cloud/oauth/token'
client_id = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxx'
client_secret = 'xxxxxxxxxxxxxxxxxxxxxx'
credentials = f'{client_id}:{client_secret}'
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')


headers = {
	'Content-Type': 'application/x-www-form-urlencoded',
	'Authorization': f'Basic {encoded_credentials}'
}
request_body = {'grant_type': 'client_credentials'}


login_response = requests.post(URL, headers=headers, data=request_body)

# Verificar se a solicitação foi bem-sucedida
if login_response.status_code == 200:
	# Exibir o token de acesso
	access_token = login_response.json().get('access_token')
	#print(f'Token de Acesso: {access_token}')



	# Leitura do arquivo CSV
	csv_file_path = r'C:\Users\ygorsm.DOMAIN\Downloads\genesys\usuarios.csv'
	df = pd.read_csv(csv_file_path, delimiter=';', header=None, skiprows=1, names=['Nome', 'Email'])

	# Iteração sobre as linhas do DataFrame

	
	for index, row in df.iterrows():
		name = row['Nome']  # Substitua 'Nome' pelo nome da coluna correspondente ao nome
		email = row['Email']
		
		if pd.notna(name) and pd.notna(email):
			print(f'\nCriando usuário para {name} ({email})...')

			# POST USERS
			URL_POST_USERS = 'https://api.sae1.pure.cloud/api/v2/users'
			
			headers_post = {
				'Content-Type': 'application/json',
				'Authorization': f'Bearer {access_token}'
			}


			request_body_post = {
				"name": name,
				"email": email,
				"divisionId": "e3b68a69-eee1-412d-bf48-b6a1cf888721",
				"state": "active"
				}

			user_id = None
			
			try:
				users_response = requests.post(URL_POST_USERS, headers=headers_post, json=(request_body_post))

				if users_response.status_code == 200:
					print(f'O usuário {name} foi criado com sucesso!')

				
					#Transformar em json
					users_response_json = users_response.json()
					user_id = users_response_json['id']
					
					# ADICIONAR AS PERMISSÕES PADRÃO PARA OS USUARIOS
					URL_PUT_USERS_ROLES = f'https://api.sae1.pure.cloud/api/v2/users/{user_id}/roles'
					request_body_put = ["a33cbea6-8780-4051-9547-f6be91383ce0", "c37a7c3f-6da0-4401-be45-b51c4c3db5e1"]#GRUPOS: AGENTE, EMPLOYEE

					users_response_put = requests.put(URL_PUT_USERS_ROLES, headers=headers_post, json=(request_body_put))
					
					if users_response_put.status_code == 200:
						print(f'Usuário foi adicionado ao grupo de permissões padrão com sucesso!')


				elif users_response.status_code == 400:
						print(f'O usuário já existe!')
			
			except requests.exceptions.RequestException as e:
				print(f'Erro na solicitação: {e}')
					####################################################################################



			# CRIAR RAMAL
			URL_POST_PHONE = 'https://api.sae1.pure.cloud/api/v2/telephony/providers/edges/phones'
			
			request_body_post_phone = {        
				"name": f"{name}_WebRTC",
				"edgeGroup": {
					"id": "2afbcc3a-6c04-46f5-9d3d-23cf1eb83104"
				},
				"site": {
					"id": "b687b7fc-4d6c-499f-bf9c-bb5f6dd632cf"
				},
				"phoneBaseSettings": {
					"id": "98d5df0d-e2e1-4882-a86f-966c74130253"
				},
				"lines": [
				{
					"name":"",
					"lineBaseSettings": {
						"id":"fb4c5887-c0b3-4256-8864-d023565b2cdf",
						"name":"WebRTC_1",
					},
					"properties": {
						"station_label": {
						"type": "string",
						"value": {
							"default": 'PureCloud WebRTC Softphone',
							"instance": 'PureCloud WebRTC Softphone'
								}
							}
						},
					"loggedInUser":{
						"id": user_id,
						"name": name
						},
					"defaultForUser": {
						"id": user_id,
						"name": name
						},
					},
				],
				"status": {
					"operationalStatus": "OPERACIONAL"
				},
				"webRtcUser": {
					"id": user_id,
					"name": name
				},     
			}


		   


			try:
				phone_response = requests.post(URL_POST_PHONE, headers=headers_post, json=request_body_post_phone)
				
				if phone_response.status_code == 200:
					print(f'O ramal foi criado com sucesso!')

					phone_response_json = phone_response.json()
					print(phone_response_json)
					phone_id = phone_response_json['id']
					print(phone_id)


				# ATRELAR RAMAL AO USUARIO / Pessoa conectada / Padrão para pessoa
					phoneId = phone_id
					URL_PUT_USERS_PHONE = f'https://api.sae1.pure.cloud/api/v2/users/{user_id}/station/defaultstation/{phone_id}'
					print(URL_PUT_USERS_PHONE)

					try:
						phone_response_put = requests.put(URL_PUT_USERS_PHONE, headers=headers_post)
						print(phone_response_put.json())

						if phone_response_put.status_code == 200:
							print(f'O Ramal foi adicionado ao usuário com sucesso!')

						else:
							print("ERRO", phone_response_put.json())  
					except Exception as error:
						print(error)
				
				elif phone_response.status_code == 400:
					print(f'O ramal já está associado ao usuario!')
					print(phone_response.json())
			except Exception as e:
				print(e)

		else:
			print(f'Nome ou e-mail inválido para a linha {index}. Ignorando...')

else:
	# Exibir mensagem de erro se a solicitação falhar
	print(f'Erro na solicitacao: {login_response.status_code} - {login_response.text}')

These are not the same thing... first get the stationID by the phone's webRtcUser.
GET /api/v2/stations

The problem is that when I do a GET in /api/v2/stations, all WebRTC appear except the WebRTC phone that I created via API, (For example: user_teste07_WebRTC) but in the web interface, I can find this WebRTC phone, only via API that doesn't.
Did I make a mistake when creating the WebRTC phone?

Hello Smith_Warren.

Thank you very much for your support, I managed to collect the WebRTC ID information, my code was not showing all the information in the correct paginations.
I managed to add a default station for the user.

Hug,
Ygor

Good job!!
thanks for letting me know that you got it working.

1 Like

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.