Pavan tej
Pavan tej

Reputation: 183

Redeliver existing form submission to new webhook

I have set up a webhook between salesforce and Typeform and it's working fine. But Typeform has already filled form submissions. Now I want to deliver these responses to a new webhook is there a way to resync existing form submissions?

Upvotes: 1

Views: 199

Answers (1)

mathio
mathio

Reputation: 578

I dont think this is possible out of the box. You will need to fetch your responses via Typeform Responses API and feed them to your script or webhook.

It looks like the webhook payload is quite similar to the response returned by the API. You can write a script like this to feed all your existing responses from your typeform to a new webhook:

import fetch from 'node-fetch'
import crypto from 'crypto'
import { createClient } from '@typeform/api-client'

const token = process.env.TF_TOKEN // https://developer.typeform.com/get-started/personal-access-token/
const webhookSecret = process.env.SECRET
const uid = process.env.FORM_ID

const typeformAPI = createClient({ token })

const sleep = async (ms) => new Promise(res => setTimeout(res, ms))

// based on https://glitch.com/edit/#!/tf-webhook-receiver
const calculateSignature = (payload) => {
  const hash = crypto
    .createHmac('sha256', webhookSecret)
    .update(payload)
    .digest('base64')
  return `sha256=${hash}`
}

const feedResponses = (before) => {
  typeformAPI.responses.list({ uid, before }).then(async ({ items }) => {
    if (items.length > 0) {
      // process each response
      for (let i=0; i<items.length; i+=1) {
        const item = items[i]
        const body = JSON.stringify({
          "event_id": Date.now(),
          "event_type": "form_response",
          "form_response": item
        })
        const response = await fetch('/your-endpoint', {
          method: 'POST',
          headers: {
            'Typeform-Signature': calculateSignature(body)
          },
          body,
        })
        const webhookResponse = await response.text()
        console.log(webhookResponse)
        await sleep(250) // rate-limit the requests
      }

      // continue with next page of responses
      const { token } = items.at(-1)
      feedResponses(token)
    }
  })
}

feedResponses()

Upvotes: 2

Related Questions