INTEGRATIONS · GENESYS CLOUD IVR
Genesys IVR Setup
This is the procedure and the contract: which endpoints exist, what authenticates them, which Data Actions ship in the repo, what the Architect flow has to do, and how to exercise the whole thing with curl before Genesys is involved at all.
It is not the mechanism. How one POST per answer becomes a single Response row, why callId is the merge key, and where the pipeline fan-out goes are all in IVR Webhook Flow. Read that first if you want to know why; read this if you have to make it work.
New here? Start with the Quickstart below: the HiveCFM side step by step, with screenshots from a run on dev.hivecfm.io. The Reference after it is the code-verified contract.
Quickstart
Verified on 14 Oct 2026: survey cmv7425uk003an2012d3f0wtw (Zain IVR Test, EN + AR, one CSAT question) in environment cmt5pjft9000ikq01uokfllc8, Genesys EU-West org, flow copied from HiveCFM IVR SurveySurveyThe core HiveCFM object. A definition of questions, logic, and targeting — shown to respondents to collect feedback. v45. Uploaded WAVs played and keypad answers were saved through a Genesys debug call (English only). The Arabic path and a call over a real DID have not been run yet.
1. Connect HiveCFM to Genesys
In Genesys: Menu → IT and Integrations → OAuth → Add Client, grant type Client Credentials, and a role that can manage Architect prompts. Copy the Client ID; the secret is shown only when the client is created (or reset).
In HiveCFM: Configuration → Integrations → Genesys Cloud. Paste the Client ID and secret, set the Environment URL, Test Connection, Save.
The Environment URL must be the API host of your region. client.ts derives the OAuth host by replacing ://api. with ://login., and prompt calls go to {environmentUrl}/api/v2/architect/prompts — a login. URL makes sync fail with 405.
https://api.mypurecloud.ie
2. Upload audio per card and language
Create the survey with channel Voice and the languages you need. On each spoken card — Welcome (if on), every question, Ending — choose Audio Source → Upload, pick the WAV, then switch the language selector and upload the next language.
WAV, 8 or 16 kHz mono, up to 5 MB. Save after each card.
Prompt names are only returned when audio exists: genesysPromptName is set when the element has an uploaded file for the requested language or for default, otherwise it is null and the flow falls back to TTS of questionText.
3. Sync to Genesys
Sync to Genesys in the editor creates one User Prompt per element (plus _welcome, _ending) and uploads one resource per language. The language tag is toGenesysLanguage(alias || code): en → en-us, ar → ar-sa.
Check in Architect → Prompts → User Prompts, filter hivecfm_<surveyId>.
Saving the integration form later resets the stored prompt mappings (config.data) — sync again after any integration change.
hivecfm_<surveyId>_<elementId>
hivecfm_<surveyId>_welcome
hivecfm_<surveyId>_ending

4. Upsert the contact, then select the survey
Do these two calls first, at the top of the flow, before any survey audio. Upsert makes sure the caller exists and gives you the identifier to send; selection turns the call context (channel, language, interaction type) into the surveyId the rest of the flow uses.
a. Upsert the contact. PUT /api/v2/management/contacts/upsert with a key that has write on the environment. Send a stable customer identifier (the CIC or customer id) as userId.
b. Select the survey. POST /api/v1/management/survey/select-relevant-survey (a read-scoped key is enough). Send surveyType: "voice" so only voice surveys are candidates. It is read-only: no response is created. 200 returns surveyId; 404 means no eligible survey — play a goodbye prompt and disconnect rather than calling the IVR endpoints.
c. Run the survey with that surveyId: pass the same userId value as CONTACT_ID to HiveCFM_GetSurveyQuestions, so the response row is linked to the contact.
Pass the userId value you upserted, never the id the upsert returns. The IVR route accepts either to find the contact, but Response.contactId is linked only through the userId attribute. A contact primary key logs “contact identified” and still writes an anonymous response.
Selection parameters
| Key | Send | Notes |
|---|---|---|
environmentId | always | required |
contactId | the userId value from step a | required unless the survey allows anonymous responses (the migrated STC-BH surveys do not) |
surveyType | voice | narrows the candidates |
channel | the channel code | migrated environments bind it on every survey, so omitting it matches nothing |
language | the survey’s language code, en or ar (the same value as Flow.language) | not the en-US locale in the top-level languageCode, which is never matched on |
interactionType | only when the surveys you target bind one | sending it excludes every survey that has no interactionType condition |
Any other string key in parameters is also treated as a selection attribute. A survey is selectable only if all four hold: status inProgress; selection enabled; a condition for every attribute you sent, with every condition it carries true; and a resolvable contactId unless it allows anonymous responses.
language is matched with isSet on multilingual surveys, and isSet accepts any non-empty value. A wrong language can still return a survey, so a 200 does not prove the language matched.
Adding channel and language is a breaking change per environment. Once they are in the catalog, a caller that does not send them selects nothing. Update every flow that points at the environment together.
No selection configured? In an environment where no survey has selection enabled, every call is 404. Keep a fixed Flow.surveyId and skip step b.
Genesys side. Add two Data Actions ahead of HiveCFM_GetSurveyQuestions: an upsert (PUT, JSON body) and a selection (POST), both authenticated with x-api-key. Set Flow.surveyId from the selection output instead of a fixed value. These two Data Actions are not shipped in the repository, and HiveCFM_GetSurveyQuestions does not bind CONTACT_ID in the published flow (see Registering the Data Actions), so bind it yourself. This sequence has not been run through a live Genesys org.
curl -X PUT https://dev.hivecfm.io/api/v2/management/contacts/upsert \
-H "x-api-key: $HIVE_KEY" -H "Content-Type: application/json" \
-d '{
"environmentId": "cmt5pjft9000ikq01uokfllc8",
"identifiers": ["userId"],
"attributes": { "userId": "CIC-10042" }
}'curl -X POST https://dev.hivecfm.io/api/v1/management/survey/select-relevant-survey \
-H "x-api-key: $HIVE_KEY" -H "Content-Type: application/json" \
-d '{
"sessionId": "<Call.ConversationId>",
"languageCode": "en-US",
"parameters": {
"environmentId": "cmt5pjft9000ikq01uokfllc8",
"contactId": "CIC-10042",
"surveyType": "voice",
"channel": "<channel code from the catalog>",
"language": "en"
}
}'{
"surveyId": "cmv7425uk003an2012d3f0wtw",
"surveyType": "voice",
"match": { "matchedCount": 1, "isFallback": false }
}Then step 5: set Flow.surveyId to the returned surveyId and send CONTACT_ID = CIC-10042.
The upsert merges: every contact that matches an identifier key is a merge candidate, and all but the survivor are deleted (up to 25). Identify only on a key that is unique per customer, and use a throwaway id when testing against a live tenant. It also needs the Contacts feature licensed.
5. Point the Genesys flow at the survey
Open HiveCFM IVR Survey in Architect, Save As a new flow, and in the copy set:
| Flow item | Field | Value |
|---|---|---|
| main → Update Data 14 | Flow.surveyId | the surveyId returned by selection in step 4, or a fixed id when no selection is configured |
| main → Update Data 15 | Flow.language | "en" or "ar" (fixed per flow) |
| main → Call Data Action 16 (GetSurveyQuestions) | HOST | "dev.hivecfm.io" (no https://) |
ENVIRONMENT_ID | the environment id | |
API_KEY | HiveCFM key, pasted by you | |
| SubmitAndNext → Call Data Action 48 (SubmitAnswer) | same three | same values |
Validate (one speech-recognition warning is expected), then Publish, then route a DID to the flow under Admin → Routing → Call Routing.
{ "data": {
"survey": {
"language": "en",
"welcomeGenesysPromptName": "hivecfm_cmv7425uk003an2012d3f0wtw_welcome",
"thankYouGenesysPromptName": "hivecfm_cmv7425uk003an2012d3f0wtw_ending"
},
"questions": [{
"questionId": "brumwnbewk1rzqcjkc4of7n3",
"type": "rating",
"genesysPromptName": "hivecfm_cmv7425uk003an2012d3f0wtw_brumwnbewk1rzqcjkc4of7n3",
"inputConfig": { "inputType": "numeric", "min": 1, "max": 5 }
}]
}}The Data Action maps $.data.questions[*].genesysPromptName → promptNames; the flow plays FindUserPrompt(Flow.currentPromptName).
6. Test without a phone number
Genesys debug mode needs no DID, but supports English-only flows. In a copy of the flow: remove Arabic under Supported Languages, set Set Language 83 to en-us and Flow.language to "en", then Publish ▾ → Debug and dial the address it shows from the Genesys phone:
<FlowName>-debug@localhostDebug mode reads out each action before the audio plays — wait for the welcome WAV, press a digit, hear the ending. Each finished call is one Completed response in HiveCFM.

Known issues found while testing
| Issue | Effect | Workaround |
|---|---|---|
Environment URL on login. host | sync fails, 405 | use https://api.<region> |
Language Alias holds a display name (e.g. English) | sync fails, 400 invalid language | leave Alias empty or use a locale code |
| Typing fast in Welcome/Ending fields (ReactReactThe component-based UI library every HiveCFM frontend is written in. Components are TypeScript functions returning JSX. #185) | editor crash, unsaved text lost | paste text, save often |
IVR preview shows raw <p><strong> HTML as TTS text | preview only | use uploaded audio |
| API key stored in plain text in Update Data / Data Action inputs | visible to Architect users | environment-scoped key, rotate if shared |
Reference
The auth model
There is no request signing. No HMAC, no timestamp, no nonce, anywhere in the four routes, and replay protection is nothing more than callId uniqueness.
But the key is not a shared secret compared inline, and the environment in the URL is not trusted. Four things happen on every request.
-
The route subtree forces authentication.
isIvrApiRoutematches^\/api\/v\d+\/client\/[^/]+\/ivr\/(endpoint-validator.ts:23-26).getRouteTypeuses that single regex to hand IVR routesAuthenticationMethod.ApiKeywhile every other/api/v1/client/route getsAuthenticationMethod.None(with-api-logging.ts:262). The IVR subtree is the authenticated island inside the otherwise-open client API. -
The key is resolved against an
ApiKeyrow, not compared to a config value.authenticateRequestreads thex-api-keyheader (auth.ts:13) and callsgetApiKeyWithPermissions. Afbk_-prefixed key is looked up by an indexed SHA-256lookupHash, then verified with bcrypt againsthashedKey; when no row matches, bcrypt still runs against aCONTROL_HASHso the miss takes the same time as a hit (api-key.ts:82-99). Comparison is bcrypt’s own constant-time compare, and the timing oracle on existence is closed deliberately. Legacy keys without the prefix take a plain SHA-256 equality lookup onhashedKey(api-key.ts:100-109) — no bcrypt, but also no secret comparison in application code. -
Environment scope is enforced per request, not inferred from the URL.
checkIvrApiKeyAccess(authentication, environmentId, method)callshasPermission, which requires anApiKeyEnvironmentrow for exactly theenvironmentIdin the path (api-key-auth.ts:20,api-keys/lib/utils.ts:22-24). A key scoped to a different environment in the same organization is rejected. -
Method maps to permission level.
methodPermissionMapgivesGET → readandPOST → write(api-keys/lib/utils.ts:5-11). So the three GET routes need a read key andPOST .../responsesneeds a write key. A read-only key gets a 401 on the answer POST.
A permission failure returns 401 unauthorized, not 403. responses.unauthorizedResponse sets status 401 (app/lib/api/response.ts:156-173), and api-key-auth.test.ts:36-56 asserts 401 for both the wrong-environment and the insufficient-permission case. Do not write a Genesys error branch that keys on 403 for auth.
Prerequisites
| What | Detail |
|---|---|
| A survey with voice-compatible elements | This is the real gate — see below. SurveyType has exactly three members, link, app and voice (schema.prisma:393-397), but no IVR route checks survey.type. The type field is convention, not a gate. |
| An API key scoped to the target environment | Organization Settings → API Keys. read for the three GETs, write for the answer POST. One key with write covers all four, since write implies read (api-keys/lib/utils.ts:34-36). |
| A Genesys Cloud org with Web Services Data Actions | The three shipped actions are integrationType: "custom-rest-actions". |
A publicly reachable WEBAPP_URL | Media URLs in the metadata payload are always built from WEBAPP_URL, never from the request host (ivr/[surveyId]/route.ts:104-105), so a Docker-internal value like 0.0.0.0:3000 produces unusable audio URLs. |
The element filter is the real prerequisite
linearizeSurveyForIvr drops elements through two independent silent filters:
- Anything not in
VOICE_COMPATIBLE_ELEMENT_TYPES—nps,rating,multipleChoiceSingle,cta,openText(packages/types/channel.ts:131-137) — is skipped (lib/ivr.ts:367-369). - Anything
buildInputConfigreturnsnullfor is skipped (lib/ivr.ts:371-372). Thatdefault: return nullbranch catches every other type.
Neither filter warns. A survey built with multipleChoiceMulti, consent, matrix, ranking, date, fileUpload, address, or contactInfo questions returns questions: [] and totalQuestions: 0 with HTTP 200. The published Architect flow’s Has Questions? decision then takes the no-branch, plays an error prompt, and disconnects. If a survey produces a silent hang-up, count the voice-compatible elements first.
docs/ivr-integration-api.md:55 lists the compatible types as “NPS, Rating, MultipleChoiceSingle, CTA” and omits openText. The code includes it, as inputType: "speech" with maxDurationSeconds: 30 and silenceTimeoutSeconds: 3 (lib/ivr.ts:168-175). The code wins.
The four endpoints
All four live under /api/v1/client/{environmentId}/ivr/{surveyId}. All four expose OPTIONS, and all four set Access-Control-Allow-Origin: * on their normal responses — including the auth failures, deliberately, so an IVR caller can read the error body (api-key-auth.ts:10).
| Method | Path suffix | Key needs | Accepts / returns | When Genesys calls it |
|---|---|---|---|---|
GET | (none) | read | Returns data.survey config plus data.questions[], the linearized voice question list. With createSession=true, also creates or reuses a Response row and returns data.responseId. | Once, on call start |
GET | /prompts | read | Returns data.prompts, a map of element id to promptName and promptId, plus requestedLanguage and availableLanguages. Only elements with an audioUrl entry for the requested language or a default entry appear. | Optional; the shipped flow does not call it |
GET | /media/{questionId} | read | Streams the audio bytes for one element, proxied from storage with an inferred Content-Type and a 1-hour cache. questionId also accepts the literals welcome and ending. | Only if the platform fetches audio over HTTP rather than playing a Genesys prompt |
POST | /responses | write | Accepts callId, answers, finished and friends. Returns data.responseId, data.status (created or updated), data.answersCount. | Once per answered question |
Metadata GET — the query string is load-bearing
reservedParams is exactly environmentId, surveyId, lang, languageCode, createSession (ivr/[surveyId]/route.ts:91). Every other query parameter becomes a hidden field, and hidden fields are written straight into Response.data when a session is created (route.ts:92-97, route.ts:216). That is how contactId, conversationId, agentId, channel, serviceCode, and interactionType reach the response row — they are not special-cased, they are just unreserved params.
Two of them do more than get stored:
contactIddrives contact identification. It is matched first against auserIdcontact attribute in this environment, then againstContact.iddirectly; a miss logs a warning and the response stays anonymous (route.ts:116-153).conversationIdbecomes the row’ssingleUseId(route.ts:160-164).(surveyId, singleUseId)is unique (schema.prisma:257), so a repeated GET for the same conversation reuses the session instead of creating a second one, and a create that loses the race falls back to the winner’s row rather than failing the call (route.ts:238-255).
Hidden fields are also fed to the block-logic evaluator, so filterBlocksByLogic can include, skip, and reorder blocks server-side from them before the question list is built (lib/ivr.ts:272-316). Question order is not simply block order when logic is present.
languageCode is the documented parameter; lang is still accepted for Data Actions downloaded before the rename (route.ts:99-102). resolveIvrLangCode matches a survey language’s code or its configured alias case-insensitively, then falls back to the primary subtag, so ar-ae resolves to ar (lib/ivr.ts:97-109).
Answer POST — the accepted body is wider than the shipped Data Action
ZIvrResponseInput (responses/route.ts:22-39):
| Field | Type | Required | Note |
|---|---|---|---|
callId | string, min 1 | yes | Stored as singleUseId and written into data.callId |
answers | record of string or number | yes | Keyed by survey element id |
finished | boolean | yes | Drives responseFinished and the quota check |
callerNumber | string | no | Stored at data.callerNumber and meta.callerNumber |
userId | string | no | Contact identification; falls back to callerNumber when absent |
languageCode | string | no | Preferred name |
language | string | no | Legacy alias, still read (responses/route.ts:108) |
hiddenFields | record of string or number | no | Merged into data |
meta.source | string | no | Defaults to "ivr" |
meta.callDuration | number | no | Validated, then dropped — the create path builds meta from source, callerNumber and a synthetic userAgent only (responses/route.ts:276-284) |
None of userId, hiddenFields, or meta are sent by HiveCFM_SubmitAnswer, whose requestTemplate carries only callId, callerNumber, language, answers and finished. userId and hiddenFields are also missing from the field table in docs/ivr-integration-api.md:171-180. If you need them, extend the Data Action.
answersCount is not the answer count. It is Object.keys(mergedData).length on the merge path (responses/route.ts:256) and Object.keys(data).length on the create path (:316), and data always carries callId, usually callerNumber, and every hidden field. It is a size, not a tally. Do not surface it to a caller as “questions answered”.
Registering the Data Actions
Three definitions ship at hivecfm-core/genesys-data-actions/. Import each into Web Services Data Actions; the console click-path is Genesys’ own and is documented in the Genesys Cloud developer docs rather than paraphrased here.
| Action | Method + URL template | Declared inputs |
|---|---|---|
HiveCFM_GetSurveyQuestions | GET https://{HOST}/api/v1/client/{ENVIRONMENT_ID}/ivr/{SURVEY_ID}?lang={LANGUAGE}&createSession=true&contactId=…&serviceCode=…&agentId=…&channel=…&conversationId=…&interactionType=… | Required: HOST, ENVIRONMENT_ID, SURVEY_ID, API_KEY, LANGUAGE. Optional: CONTACT_ID, SERVICE_CODE, AGENT_ID, CHANNEL, CONVERSATION_ID, INTERACTION_TYPE |
HiveCFM_GetPromptNames | GET …/ivr/{SURVEY_ID}/prompts?lang={LANGUAGE} | Same five required inputs |
HiveCFM_SubmitAnswer | POST …/ivr/{SURVEY_ID}/responses | Required: HOST, ENVIRONMENT_ID, SURVEY_ID, API_KEY, CALL_ID, ANSWERS_JSON, FINISHED, LANGUAGE. Optional: CALLER_NUMBER, HIDDEN_FIELDS_JSON |
Declared is not sent. The published v28 flow binds only the five required inputs on HiveCFM_GetSurveyQuestions — API_KEY, ENVIRONMENT_ID, HOST, LANGUAGE, SURVEY_ID. All six optional context inputs are absent from its inputs block, and HIDDEN_FIELDS_JSON on SubmitAnswer is explicitly noValue: true. So the shipped artifact sends no contactId — it performs no contact identification at all, and every response it writes is anonymous — and no conversationId, which is the defect called out under the Architect flow shape. If you want the context fields listed under the metadata GET above, you have to bind them yourself.
All three send the key as a x-Api-Key request header bound to ${input.API_KEY}. HTTP header names are case-insensitive, so this reaches request.headers.get("x-api-key") correctly.
All three also use the legacy language names: ?lang= in the two URL templates, and "language" in the SubmitAnswer body. languageCode is the current name for both, and both spellings are still read (ivr/[surveyId]/route.ts:99-102, responses/route.ts:108), so this is backwards compatibility rather than a bug — but new callers should send languageCode.
HiveCFM_GetSurveyQuestions is the only one with a real translationMap. It flattens the nested payload into parallel arrays that Architect can index — questionIds from $.data.questions[*].questionId, promptNames from $.data.questions[*].genesysPromptName, inputTypes / inputMins / inputMaxes from the matching inputConfig fields, plus scalars for totalQuestions, inputTimeout, maxRetries, and the welcome/thank-you prompt names. The other two use successTemplate: "${rawResult}" and pass the body through unshaped.
Four defects in the shipped artifacts
These are in the repo files, not in the API. Fix them in your own copies.
-
SubmitAnswernever sendsHIDDEN_FIELDS_JSON. It is a declared input with a documented example (HiveCFM_SubmitAnswer.json:47-50,README.md:34), but therequestTemplateon line 9 references onlyCALL_ID,CALLER_NUMBER,LANGUAGE,ANSWERS_JSON, andFINISHED. The input is inert. -
SubmitAnswer’s declared output does not match the wire. ItssuccessSchemadeclares top-levelresponseIdandmessage(HiveCFM_SubmitAnswer.json:79-87), but the route returns{ "data": { "responseId", "status", "answersCount" } }(responses/route.ts:251-259,:311-319). No code path in the route ever emitsmessage, andstatusandanswersCountare undeclared. -
Every recorded execution of
SubmitAnswerfailed. The six*.execution-data.*.jsontraces committed alongside the flows are real Genesys execution records. Reading eachactionCallData’soutputPathId,HiveCFM_GetSurveyQuestionstakes__SUCCESS__every time (6/6) andHiveCFM_SubmitAnswertakes__FAILURE__every time (10/10), each with"outputVariables": []. The traces record no error body, so they do not prove the cause. What defect 2 does prove is that the flow’sresponseId→Flow.responseIdbinding could not work even on a 200: it reads a top-levelresponseIdthat the wire never carries, andSubmitAnswer’stranslationMapis empty, so nothing lifts it out ofdata. Treat the shippedSubmitAnsweras unproven and validate it with the curl loop before wiring a flow to it. -
The exported flows carry credentials inline. Seven
*.yamlflow exports and six execution traces undergenesys-data-actions/contain a live-format HiveCFM API key as a literal Data Action input, alongside a real environment id and host."secure": falseon all three action definitions means the key lives in the action’s inputs rather than in a Genesys credential. Scrub these files before sharing them, and configureAPI_KEYfrom a Genesys credential rather than a literal.
The Architect flow shape
A published export, _HiveCFM IVR Survey_v28-0.yaml, is the ground truth for what the flow has to do. It is an inboundCall flow with defaultLanguage: ar-sa, 27 Flow.* variables, and four tasks. Describing the required outcome is more durable than describing clicks; build these tasks however your Architect version wants you to.
Call metadata once, at the top. HiveCFM_GetSurveyQuestions runs before the question loop and never again. Its outputs are bound to flow variables: Flow.questionIds, Flow.promptNames, Flow.inputTypes, Flow.inputMins, Flow.inputMaxes, Flow.totalQuestions, Flow.welcomePromptName, Flow.thankYouPromptName. The published export leaves questionTexts, inputTimeout, maxRetries, audioSources, welcomeMessage, thankYouMessage and both *AudioSource outputs at noValue: true, and hard-codes the retry cap at 3 and the timeouts in the collectInput action instead. responseId is the costly gap: it is the one declared output the export omits from the block altogether, yet this action’s translationMap maps it to $.data.responseId — where the route actually puts it — so binding it here is the only place the flow can obtain a response id that works.
Loop by index, not by iterator. AskQuestion compares Flow.currentIndex >= Flow.totalQuestions and jumps to EndSurvey or extracts question n by array index from the parallel arrays. SubmitAndNext increments Flow.currentIndex and jumps back to AskQuestion. There is no loop construct; it is three reusable tasks and jumpToTask.
Collect input against the config, not against a guess. The export’s collectInput takes 1–2 digits with a 1-second inter-digit timeout and an 8-second no-entry timeout, playing AudioPlaybackOptions(ToAudio(FindUserPrompt(Flow.currentPromptName)), true). Range validation happens in SubmitAndNext, comparing ToInt(Flow.dtmfInput) against Flow.currentMin and Flow.currentMax — the values that came from inputConfig. On a range failure or a no-input, Flow.retryCount increments; at 3 the flow abandons that question, bumps the index, and moves on rather than hanging up.
Signal the last answer with isFinished. Flow.isFinished is set to (Flow.currentIndex == Flow.totalQuestions - 1) and passed as FINISHED. This is what turns the last POST into a completion: finished: true is what fires responseFinished into the pipeline and what triggers the completed-response quota check.
One POST per answer, and the payload is cumulative. Flow.currentAnswerJson starts as {"<id>":"<digit>"} at index 0 and thereafter is extended with Replace(Flow.currentAnswerJson, "}", ",\"<id>\": \"<digit>\"}"). So every POST resends every prior answer. That is harmless — the server merges {...existing.data, ...incoming} (responses/route.ts:220) — but it means the request body grows with each question and answersCount climbs accordingly.
callId must equal the conversation id. The export binds CALL_ID to Call.ConversationId and CALLER_NUMBER to Call.Ani. Both bindings are literally correct, and both cause a problem downstream — the first because the other end of the pair is never sent, the second because of what Call.Ani contains.
callId and conversationId must be the same value, and in the v28 export they are not. ivr/[surveyId]/route.ts:155-159 states the requirement in its own comment: the answer POST looks up by singleUseId = callId, so the Architect flow must send callId = conversationId. The export does not bind CONVERSATION_ID at all — it is absent from the HiveCFM_GetSurveyQuestions inputs block, and absent from the recorded inputs of all six committed execution traces. hiddenFields.conversationId || undefined (route.ts:160) collapses both “absent” and “empty string” to undefined, so the createSession=true row is written with no singleUseId. The answer POST’s findFirst({ surveyId, singleUseId: callId }) then misses and creates a second Response row.
The orphan is the session row, and it has zero answers — which under the answeredQuestionsCount rule makes it an invitation, not a response. Count responses without that filter and this defect inflates the total. See Genesys and IVR queries.
Call.Ani arrives with its URI scheme attached (tel:+… in the recorded traces), so data.callerNumber is stored with the tel: prefix, and because effectiveUserId = userId || callerNumber (responses/route.ts:265) that prefixed string is also what contact identification is attempted against. Strip it in the flow if you want a bare E.164 number.
DTMF mapping
Two different things are called “DTMF mapping”, and only one of them happens server-side.
What the metadata endpoint advertises. buildInputConfig emits one of three shapes (lib/ivr.ts:129-180):
| Element type | inputType | Shape |
|---|---|---|
nps | numeric | min / max from getNPSBounds(scale, startsAt) |
rating | numeric | min: 1, max: range |
multipleChoiceSingle | dtmf_choice | min: 1, max: choices.length, plus options[] of key (the 1-based index as a string) and label |
cta | dtmf_choice | min: 1, max: 1, single option key: "1", label: "Continue" |
openText | speech | min: 0, max: 0, maxDurationSeconds: 30, silenceTimeoutSeconds: 3 |
Choices are truncated to VOICE_MAX_MULTIPLE_CHOICE_OPTIONS = 9 (channel.ts:140, applied at lib/ivr.ts:148) because there are only nine usable digits. A tenth choice is silently unreachable. The label falls back to Option N when the choice has no text for the requested language.
What the answer POST rewrites. Only multipleChoiceSingle is translated (responses/route.ts:161-176). The lookup is 1-indexed: choices[dtmfDigit - 1], so digit 1 selects the first choice, and the stored value becomes that choice’s id, not the digit.
Two things happen before it, in order:
- Any answer value that is an all-digits string is coerced with
parseInt(responses/route.ts:141-142). So"3"is already the number3by the time the choice mapping runs. - The guard is
!isNaN(dtmfDigit) && dtmfDigit >= 1 && dtmfDigit <= choices.length.
Out of range fails open. A digit outside 1..choices.length — or a non-numeric value — skips the rewrite and the raw value is stored as-is. Because of step 1 that means Response.data[elementId] ends up holding a bare integer where a choice id string belongs. It matches no choice, so every report that resolves choices by id treats it as unanswerable. There is no error and no log line.
Numeric answers are never range-checked server-side. inputConfig.min and max are advisory. Nothing in responses/route.ts validates an nps or rating value against them, so a 99 on a 0–10 NPS is accepted and stored. Range enforcement is the Architect flow’s job — which is exactly what SubmitAndNext’s Validate Numeric Input decision does.
Prompts and media
There are two independent ways to get audio to the caller, and the shipped flow uses the first.
Genesys prompts, referenced by name. linearizeSurveyForIvr returns a genesysPromptName per question — hivecfm_{surveyId}_{elementId}, non-alphanumerics replaced with _, and null when the element has no audio (lib/ivr.ts:393-395). Same pattern for welcomeGenesysPromptName and thankYouGenesysPromptName. The flow feeds these to FindUserPrompt(...) and Genesys plays its own resource, picking the language variant from the flow language.
The media endpoint, fetched over HTTP. GET .../media/{questionId} resolves the element’s audioUrl — an i18n map, with a legacy plain-string form still handled — for the requested language, falling back to the default key (media/[questionId]/route.ts:113-122). A storage URL of the form .../storage/{environmentId}/{public|private}/{fileName} is parsed, signed, fetched, and proxied back with a Content-Type from the upstream response or inferred from the extension (wav, mp3, m4a, ogg), a 1-hour cache, and permissive CORS. A URL that does not parse as a storage path is assumed external and returned as a 302 redirect (:162-166). questionId accepts the literals welcome and ending as well as any element id.
This endpoint still requires the x-Api-Key header. Any player that takes a bare URL and cannot attach headers — Asterisk Playback(), an MRCP media reference — must pre-download server-side with the header and play the local file.
What /prompts adds. It returns the same prompt-name map plus each element’s saved promptId from the environment’s genesysCloud integration config, matched on promptName prefix and elementId (prompts/route.ts:102-104). hasAudioForLang gates each entry (prompts/route.ts:85-92, applied at :99): an i18n map qualifies on the requested language or on its default key, and a legacy plain-string audioUrl always qualifies. So the map is a subset of the question list — but not one narrowed to the requested language. It also returns requestedLanguage and availableLanguages, and it is the only JSON route whose success body is cacheable — public, s-maxage=60, max-age=60 (prompts/route.ts:151), where the metadata GET returns the default private, no-store.
One more thing /prompts does not do: it is the only one of the four routes that never validates environmentId. It goes straight from await props.params to the auth gate (prompts/route.ts:33-36), with no ZEnvironmentId.safeParse.
The two endpoints disagree about prompt names for non-default languages. prompts/route.ts:73 builds a promptSuffix of _{lang} whenever the requested language is not the survey default, and appends it (:101). lib/ivr.ts:394 appends nothing, and two comments say so explicitly — :423 reads “No language suffix — single prompt per element, Genesys uses flow language to pick resource”, and :381 says the same in the question loop. genesys-data-actions/README.md:58-59 documents both forms — unsuffixed for the default language, _{langCode} for the others — so the README and prompts/route.ts agree with each other and lib/ivr.ts is the outlier.
The published flow settles which one is in use: it takes promptNames from HiveCFM_GetSurveyQuestions — the unsuffixed names — and never calls HiveCFM_GetPromptNames at all (it appears in no flow YAML, only in its own definition and the README). The traces agree, and date the change: the v16/v19/v23 records carry _ar-suffixed prompt names, the v26/v27/v28 records carry unsuffixed ones. If you do call /prompts for a non-default language, expect names that will not resolve against prompts uploaded under the unsuffixed convention.
Testing without Genesys
The whole loop is four HTTP calls. Run them before you build a flow; a failure here is a HiveCFM problem, a failure after is a Genesys problem.
The ids below are placeholders; substitute your own. Both of the obvious ways to get auth wrong land on the same status: omitting the header entirely returns 401 not_authenticated from the wrapper, and fbk_REPLACE_ME_WITH_A_REAL_KEY is well-formed enough to pass parseApiKeyV2 but then fails bcrypt verification, which also returns 401 not_authenticated. Step 0 uses the first form as a control — if it does not return 401, you are not talking to an IVR route.
HOST=https://hivecfm.example.internal
ENV=cenv0000000000000000000a # must satisfy z.string().cuid()
SURVEY=csrv0000000000000000000a
KEY=fbk_REPLACE_ME_WITH_A_REAL_KEY
CALL=11111111-2222-3333-4444-555555555555 # use this as BOTH conversationId and callId
# 0. Control: prove the key is actually being checked.
# No x-Api-Key header at all. Expect 401.
curl -s -o /dev/null -w '%{http_code}\n' \
"$HOST/api/v1/client/$ENV/ivr/$SURVEY"
# 1. Metadata + session. conversationId MUST equal the callId you will POST.
curl -s -H "x-Api-Key: $KEY" \
"$HOST/api/v1/client/$ENV/ivr/$SURVEY?languageCode=en&createSession=true&conversationId=$CALL" \
| jq '{responseId: .data.responseId,
total: .data.survey.totalQuestions,
q: [.data.questions[] | {questionId, type, inputConfig}]}'Take two element ids out of that questions array, then post them one at a time. The second POST carries finished: true.
Q1=<questionId from step 1>
Q2=<second questionId from step 1>
# 2. First answer. status should be "updated" — it merges into the session row
# from step 1, because callId == the conversationId you sent.
curl -s -X POST -H "x-Api-Key: $KEY" -H 'Content-Type: application/json' \
-d "{\"callId\":\"$CALL\",\"callerNumber\":\"+10000000000\",
\"languageCode\":\"en\",\"answers\":{\"$Q1\":8},\"finished\":false}" \
"$HOST/api/v1/client/$ENV/ivr/$SURVEY/responses" | jq .
# 3. Final answer. finished:true fires responseFinished into the pipeline.
curl -s -X POST -H "x-Api-Key: $KEY" -H 'Content-Type: application/json' \
-d "{\"callId\":\"$CALL\",\"languageCode\":\"en\",
\"answers\":{\"$Q1\":8,\"$Q2\":\"1\"},\"finished\":true}" \
"$HOST/api/v1/client/$ENV/ivr/$SURVEY/responses" | jq .
# 4. Re-post to the finished row. Expect 400 bad_request.
curl -s -X POST -H "x-Api-Key: $KEY" -H 'Content-Type: application/json' \
-d "{\"callId\":\"$CALL\",\"answers\":{\"$Q1\":9},\"finished\":true}" \
"$HOST/api/v1/client/$ENV/ivr/$SURVEY/responses" | jq .status: "updated" on step 2 is the assertion that matters. If it says created, the session row from step 1 was not found — you sent a callId that does not match the conversationId, which is precisely the defect in the v28 export.
Verify the row
One Response row, one callId, one environment. The tenant filter is explicit on purpose: never rely on RLS here, because an unset app.current_tenant GUC makes every tenant’s rows visible.
SELECT r.id,
r.finished,
r.answered_questions_count,
r.data ->> 'callId' AS call_id,
r.data ->> 'callerNumber' AS caller_number,
r.language,
r.created_at
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :environment_id
AND r."surveyId" = :survey_id
AND r."singleUseId" = :call_id;Planned on devhub_ref (the exact origin/development schema): it resolves through the unique index Response_surveyId_singleUseId_key, then Survey_environmentId_updated_at_idx. Note the mixed quoting — "surveyId" and "singleUseId" are camelCase and must be quoted, answered_questions_count and created_at are not. That is per-table, not a convention you can apply.
This query runs against the origin/development schema only. answered_questions_count does not exist in the older migration-era database, so drop that column if you are querying one. The rest of the statement — the join, the tenant filter, "singleUseId" — executes against both, because those columns exist on both. It will not return rows from a database that predates the IVR path: singleUseId is only ever written by a callId or a conversationId.
answered_questions_count > 0 is the response filter and = 0 is the invitation filter; a createSession=true row that never received an answer sits at 0. More recipes, including the two meta.source values below, are in Genesys and IVR queries.
meta.source is not one value. A row created by createSession=true gets "genesys_ivr" (ivr/[surveyId]/route.ts:221). A row created by the answer POST gets meta.source from the body or defaults to "ivr" (responses/route.ts:277). The update path never passes meta at all, so a session row keeps "genesys_ivr" for its whole life no matter how many answers land on it. A query that filters on either value alone misses half the rows.
Failure modes
Every row below is a real branch in the route code. The error body shape is always { code, message, details } (app/lib/api/response.ts:9-24).
| Condition | Status | code | Where |
|---|---|---|---|
No x-api-key header, or a key that matches no row | 401 | not_authenticated | Wrapper, before the handler (with-api-logging.ts:346-348). details carries "x-Api-Key": "Header not provided or API Key invalid" |
Key has no entry for this environmentId | 401 | unauthorized | api-key-auth.ts:20-22; asserted at api-key-auth.test.ts:36-43 |
Read-only key on POST .../responses | 401 | unauthorized | methodPermissionMap maps POST to write (api-keys/lib/utils.ts:7) and the read case returns false for it (:37-39); asserted at api-key-auth.test.ts:49-56 |
environmentId is not a cuid | 400 | bad_request | ZEnvironmentId = z.string().cuid(), checked on metadata, media, and responses. Not on /prompts, which skips the check entirely and so answers a malformed id with 401 instead |
| SurveySurveyThe core HiveCFM object. A definition of questions, logic, and targeting — shown to respondents to collect feedback. id does not exist | 404 | not_found | All four routes, details.resource_type: "Survey" |
| SurveySurveyThe core HiveCFM object. A definition of questions, logic, and targeting — shown to respondents to collect feedback. exists but belongs elsewhere | 400 | bad_request | "Survey is part of another environment", with both ids in details. All four routes check survey.environmentId !== environmentId |
| Malformed JSON body | 400 | bad_request | "Invalid JSON in request body" (responses/route.ts:86-94) |
| Body fails the zod schema | 400 | bad_request | "Fields are missing or incorrectly formatted", per-field detail from transformErrorToDetails |
Duplicate callId, row not finished | 200 | — | Not an error. This is the merge path: status: "updated" |
Duplicate callId, row already finished | 400 | bad_request | "Response already finished. Cannot update a completed response.", details.responseId set (responses/route.ts:210-218) |
| Session past its frozen deadline | 410 | gone | details.code: "SURVEY_SESSION_EXPIRED" plus expiredAt, and expirySource only when the row or the error carries one (route.ts:198, responses/route.ts:335). message is the resolved expire-card text, ready to speak. Raised on the metadata GET when reusing a session (route.ts:187-204) and on the POST from SurveySessionExpiredError (:327-341) |
| Organization license invalid | 403 | forbidden | message is the license reason (responses/route.ts:180-186) |
| Completed-response quota exhausted | 403 | forbidden | "Completed response limit reached (current/limit)". Only checked when finished is true (:188-198) |
| Either check when no organization resolves | — | — | Both are skipped. getOrganizationByEnvironmentId returning nothing means license and quota are not enforced at all (:179-199) |
| Rate limit | 429 | too_many_requests | Two limits apply per request: api:v1 at 100/min keyed on apiKeyId, and api:client at 100/min keyed on IP (modules/core/rate-limit/rate-limit-configs.ts:12,14; with-api-logging.ts:79-93). The IP-keyed one is shared by everything arriving from one egress address |
| Unhandled throw | 500 | internal_server_error | Handler-local catch returns error.message (route.ts:271, responses/route.ts:344); anything escaping that is caught by executeHandler and returns "An unexpected error occurred." (with-api-logging.ts:112-120) |
The two silent successes
Neither of these is an error, and both are easy to ship without noticing.
An answer for an unknown element id is accepted and stored. answers is copied key by key into data with no membership check against the survey (responses/route.ts:139-146). The DTMF loop only walks real survey elements, so an unknown key never even gets looked at — it lands in Response.data verbatim and returns 200. A typo in ANSWERS_JSON, or a flow still pointing at a deleted question, produces a response that looks fine and answers nothing.
An out-of-range value is accepted and stored. Covered under DTMF mapping: multipleChoiceSingle falls through to the raw integer, and nps / rating are never validated at all.
docs/ivr-integration-api.md is wrong about duplicates. Lines 141 and 307-308 say submitting the same callId twice “will fail with a duplicate error” and that retrying is safe because “the system will reject duplicates”. It does not. responses/route.ts:203-206 looks the row up by (surveyId, singleUseId) and merges into it — the duplicate callId is the mechanism, which is why one call can POST an answer at a time. The only rejection is a row already marked finished. Retrying a POST is safe, but for the opposite reason to the one the doc gives: it is idempotent-by-merge, not deduplicated-by-rejection.
Where to look in the code
Paths are relative to hivecfm-core at origin/development.
apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/route.ts— metadata GET,createSession, hidden-field extraction, contact identification, session reuse and the create race.apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/responses/route.ts—ZIvrResponseInput, numeric coercion, the DTMF-to-choice rewrite, license and quota gates, merge-or-create.apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/prompts/route.ts— prompt-name map, the_{lang}suffix,genesysCloudintegration mappings.apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/media/[questionId]/route.ts—parseStorageUrl, signed download, audio proxying, the external-URL 302.apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/lib/ivr.ts—linearizeSurveyForIvr,buildInputConfig,resolveIvrLangCode,filterBlocksByLogic.apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/lib/api-key-auth.tsandapi-key-auth.test.ts— the shared auth gate, and the tests that pin 401-not-403.apps/web/app/middleware/endpoint-validator.ts—isIvrApiRoute, the regex that makes this subtree authenticated.apps/web/app/api/v1/auth.tsandapps/web/modules/organization/settings/api-keys/lib/api-key.ts— header read, lookup hash, bcrypt verification,CONTROL_HASH.apps/web/modules/organization/settings/api-keys/lib/utils.ts—hasPermissionandmethodPermissionMap.apps/web/app/lib/api/response.ts— every status code and body in the table above.apps/web/lib/survey/session-ttl.ts— the frozen-deadline model behind the 410.apps/web/modules/core/rate-limit/rate-limit-configs.ts— the two 100/min limits in the table above.packages/types/channel.ts—VOICE_COMPATIBLE_ELEMENT_TYPES,VOICE_MAX_MULTIPLE_CHOICE_OPTIONS.genesys-data-actions/HiveCFM_GetSurveyQuestions.json,HiveCFM_GetPromptNames.json,HiveCFM_SubmitAnswer.json— the three importable definitions.genesys-data-actions/_HiveCFM IVR Survey_v28-0.yaml— the published flow. Contains a live-format API key; scrub before sharing.docs/ivr-integration-api.md— the prose API doc. Useful for intent; wrong about duplicatecallIdand incomplete on element types.
Read next
- IVR Webhook Flow — the merge-on-
callIdmechanism and the pipeline fan-out. - Genesys Bot Connector — the same surveys over chat, with a different auth model and server-side navigation state.
- Genesys and IVR queries — verified SQL for IVR responses, the two
meta.sourcevalues, and the invitation filter. - Integrations — the seven doors in and out of HiveCFM.