Build
Google Forms guide
An Apps Script trigger rewards each response, no server of your own.
How it fits together
Google Forms runs Apps Script on each response, on Google's servers, so you need no server of your own: the script
calls POST /rewards with a restricted key kept in the script's properties. Apps Script is a server, not a
browser, so the key is never shown to respondents. The script below sets itself up and checks itself, so you are
never left guessing whether it ran.
Set it up, step by step
- Pick a mode and stay in it. In the dashboard's Developers page, switch to Test to try it first (nothing reaches a real phone, and test rewards show in the Rewards tab), or Live to pay real airtime from your Jusa Credit. A test key only sees test programs and a live key only sees live ones.
- Make a program in that mode (Rewards → New program) and copy its short name
(for example
survey). Its id, which startsprg_, works too. - Make a restricted key in the same mode (Keys → Restricted) with the scopes
rewards:readandrewards:write. Copy it when it is shown: it is shown once. - Add a short-answer question for the mobile number to your form. Its title must match
PHONE_QUESTIONat the top of the script (Mobile number unless you change it). - In the form, open Extensions → Apps Script, delete what is there, and paste the script below. Save.
- Open Project Settings (the cog) → Script Properties →
Add script property, twice:
JUSA_KEYset to the key, andJUSA_PROGRAMset to the program's short name. - Back in the editor, choose setUp in the function menu next to Debug (it may
say
onSubmit; either works), and press Run. Google asks you to authorise the script the first time: choose your account, then Advanced → Go to (your project), then Allow. It is your own script, which is why Google calls it unverified. - Read the Execution log under the editor. It says Ready with the program's name, mode and budget, or says exactly what to fix. Fix it and run setUp again until it says Ready.
- Submit the form once yourself. In Apps Script, open Executions (the list icon on the left) to see the run and what Jusa answered; the reward also shows in the dashboard's Rewards tab.
Apps Script runs the function picked in the menu next to Debug, not the one your cursor is in. If
it still says onSubmit when you press Run, that is fine: run by hand, onSubmit has no form
response to pay, so it does the set-up instead.
The script
// The title of your form's mobile-number question, exactly as it reads in the form.
const PHONE_QUESTION = 'Mobile number';
const JUSA_API = 'https://jusa.localhost.co.zw/dev/v1';
const HTTP_OK = 200;
const HTTP_REDIRECT = 300;
const HTTP_UNAUTHORIZED = 401;
const HTTP_PAYMENT_REQUIRED = 402;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_SERVER_ERROR = 500;
// Run this once from the editor: it installs the form-submit trigger and checks
// that the key and the program belong together.
function setUp() {
const form = FormApp.getActiveForm();
ScriptApp.getProjectTriggers()
.filter((trigger) => trigger.getHandlerFunction() === 'onSubmit')
.forEach((trigger) => ScriptApp.deleteTrigger(trigger));
ScriptApp.newTrigger('onSubmit').forForm(form).onFormSubmit().create();
console.log('Trigger installed: every response to "' + form.getTitle() + '" now runs onSubmit.');
findPhoneQuestion(form);
checkJusa();
}
function settings() {
const scriptProperties = PropertiesService.getScriptProperties();
const apiKey = (scriptProperties.getProperty('JUSA_KEY') || '').trim();
const programId = (scriptProperties.getProperty('JUSA_PROGRAM') || '').trim();
if (!apiKey) throw new Error('Set the script property JUSA_KEY to your restricted key (Project Settings → Script Properties).');
if (!programId) throw new Error('Set the script property JUSA_PROGRAM to your program\'s short name (e.g. survey) or its id (prg_…).');
return { apiKey, programId };
}
function findPhoneQuestion(form) {
const wanted = PHONE_QUESTION.trim().toLowerCase();
const titles = form.getItems().map((item) => item.getTitle());
if (!titles.some((title) => title.trim().toLowerCase() === wanted)) {
throw new Error('No question titled "' + PHONE_QUESTION + '". The form has: ' + titles.join(' | ')
+ '. Change PHONE_QUESTION or the question title.');
}
console.log('Phone question found: "' + PHONE_QUESTION + '".');
}
function checkJusa() {
const { apiKey, programId } = settings();
const jusaAnswer = UrlFetchApp.fetch(JUSA_API + '/programs/' + encodeURIComponent(programId), {
headers: { Authorization: 'Bearer ' + apiKey },
muteHttpExceptions: true,
});
const status = jusaAnswer.getResponseCode();
if (status === HTTP_UNAUTHORIZED) throw new Error('Jusa does not know this key: copy it again from the dashboard into JUSA_KEY.');
if (status === HTTP_FORBIDDEN) throw new Error('The key cannot read rewards: give it the scopes rewards:read and rewards:write.');
if (status === HTTP_NOT_FOUND) {
throw new Error('No program ' + programId + ' for this key. Check the id, and that the key and the program '
+ 'were both made in the same mode (Test or Live).');
}
if (status !== HTTP_OK) throw new Error('Jusa answered ' + status + ': ' + jusaAnswer.getContentText());
const program = JSON.parse(jusaAnswer.getContentText());
const mode = program.livemode ? 'LIVE: rewards pay real airtime from your Jusa Credit' : 'TEST: nothing reaches a real phone';
console.log('Ready. Program "' + program.name + '" (' + program.status + '), ' + program.remaining + ' '
+ program.currency + ' left, ' + program.default_amount + ' each. Mode ' + mode + '.');
if (program.status !== 'active') console.warn('The program is ' + program.status + ': activate it in the dashboard, or rewards are refused.');
}
// Runs on every form response, started by the trigger setUp installed. Run by
// hand from the editor (no response to read), it sets up instead.
function onSubmit(formSubmitEvent) {
if (!formSubmitEvent || !formSubmitEvent.response) {
console.log('Run by hand, so there is no form response to pay: setting up instead.');
setUp();
console.log('Now submit the form once, and watch Executions for the run.');
return;
}
const status = payResponse(formSubmitEvent.response);
if (status === HTTP_PAYMENT_REQUIRED) {
throw new Error('Top up Jusa Credit, then run payMissed: nothing was charged.');
}
if (status >= HTTP_SERVER_ERROR) {
throw new Error('Jusa unavailable (' + status + '); run payMissed once it is back.');
}
}
// Run this from the editor after a top-up or an outage. It asks Jusa to pay
// every response; one already paid is answered with its first reward (the
// response id is the completion_id), so nothing is ever paid twice.
function payMissed() {
const formResponses = FormApp.getActiveForm().getResponses();
let rewarded = 0;
let refused = 0;
for (const formResponse of formResponses) {
const status = payResponse(formResponse);
if (status === HTTP_PAYMENT_REQUIRED || status >= HTTP_SERVER_ERROR) {
console.warn('Stopped at status ' + status + ': ' + rewarded + ' rewarded so far. Fix that, then run payMissed again.');
return;
}
if (status < HTTP_REDIRECT) rewarded += 1; else refused += 1;
}
console.log(formResponses.length + ' responses: ' + rewarded + ' rewarded (new or already), ' + refused + ' refused.');
}
// Asks Jusa to reward one form response; returns Jusa's HTTP status.
function payResponse(formResponse) {
const { apiKey, programId } = settings();
const wanted = PHONE_QUESTION.trim().toLowerCase();
const phoneAnswer = formResponse.getItemResponses()
.find((itemResponse) => itemResponse.getItem().getTitle().trim().toLowerCase() === wanted);
if (!phoneAnswer) throw new Error('This response has no answer to "' + PHONE_QUESTION + '".');
const responseId = formResponse.getId(); // unique per response: one reward each, however often it runs
const jusaAnswer = UrlFetchApp.fetch(JUSA_API + '/rewards', {
method: 'post',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + apiKey,
'Idempotency-Key': 'gform-' + responseId,
},
payload: JSON.stringify({
program: programId,
recipient: { phone: String(phoneAnswer.getResponse()).trim() },
completion_id: responseId,
}),
muteHttpExceptions: true,
});
const status = jusaAnswer.getResponseCode();
// A refusal (a cap, a number that is not a Zimbabwean mobile) is final: it is logged here.
console.log('Response ' + responseId + ': Jusa answered ' + status + ': ' + jusaAnswer.getContentText());
return status;
}
If nothing happens
- No run under Executions after a submission: the trigger is missing. Run
setUpagain from the form's own Apps Script (Extensions → Apps Script in the form, not a separate script). - "Jusa does not know this key" or "No program": the key and the program were made in different modes, or one was copied wrongly. Make both again in the same mode.
- "No question titled": the message lists your form's titles; set
PHONE_QUESTIONto the phone question's title. - A run that ends in 400, 403 or 409: Jusa refused that response, for a reason given in the log: a number that is not a Zimbabwean mobile, a phone already paid by a one-per-phone program, a per-person cap, or a spent budget.
- "Top up Jusa Credit" (402): the program draws from your Jusa Credit and it is empty. Top up in the same mode, then run payMissed.
- Test mode: the reward appears in the dashboard's Rewards tab in Test mode, not on a phone. Switch the key and the program to Live to pay real airtime.
The response id is the completion_id: an edited or re-run response is still one reward. Running out of
Jusa Credit, or Jusa being unreachable, fails the run so it shows under Executions; nothing was charged. Apps Script
cannot rerun a trigger's run, so top up (or wait for Jusa) and run payMissed from the editor: it
goes through every response, pays the ones not yet paid, and gets the first reward back for the rest.
Want no key in the script at all? Sign the body with the program's completions secret instead and post to
/programs/{id}/completions: Utilities.computeHmacSha256Signature(timestamp + '.' + body, secret),
hex-encoded, in Jusa-Signature: t=…,v1=….