Sending unique codes via SMS automation

106 Views Asked by At

I have a guest wifi that required the user to have a voucher code in order to access the wifi network.

What am trying to achieve is for the user to send a sms message to my twilio phone number. I would for the user to be somehow validated. once validated a sms message would be sent to the user with a unique voucher code.

Each voucher code would be unique and i would need a way to upload them so that twilio can grab a new code each time and send to the user.

I would really appreciate if someone would be willing to help me on this.

I have already created a sms automation using twilio studio. It does everything that i want it to do except for the validation part and i am not sure how to send a unique code each time the flow is triggered.

Thanks!

1

There are 1 best solutions below

0
On

Okay, you didn't mention the framework or language you are using to communicate with the Twilio API. but I will explain the principle.

first, I will recommend that you have a data table where you store the codes you send and the user who received it. ( if you are working with a database you can set the code field to unique, so you can be sure about the duplication )

then before going to send the code to Twilio API so it can forward it in an SMS to the user you should validate it by checking if the newly generated code is already used or not.

this is an example using the nodejs and the mongoose ORM ( Mongo DB database ):

const mongoose = require( "mongoose" );
const Schema = mongoose.Schema;
const uniqueValidator = require( "mongoose-unique-validator" );

const CodeSchema = new Schema( {
    owner: { type: Schema.Types.ObjectId, ref: "User" },
    code: { type: Number, index: true, unique: true }
} ,{ timestamps: true } );
CodeSchema.plugin( uniqueValidator, { message: "is already taken." } );

CodeSchema.pre( "validate", function( next ){
    if( !this.code )  {
        this.code = Math.floor( Math.random() * Math.pow( 36, 6 ) | 0 );
    }
    next();
} );
module.exports = mongoose.model( "Code", CodeSchema ) || mongoose.models.Code;

then when you create the schema this pre-validate function will execute and fill the code field with a unique code.