Firebase with Twilio - Angular4中的短信应用程序

时间:2017-12-14 07:11:25

标签: angular firebase twilio angularfire twilio-api

我正在尝试将Twilio与Firebase集成在angular4中。 我跟着https://angularfirebase.com/lessons/sms-texting-with-twilio/这个文档。所有配置都没有错误。但是当我在浏览器中打开应用程序时,我遇到了错误。

Errors

我在firebase中的数据如下所示。我手动添加了

enter image description here

下面是我的代码

披萨组件ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
@Component({
  selector: 'pizza-status',
  templateUrl: './pizza-status.component.html',
  styleUrls: ['./pizza-status.component.css']
})
export class PizzaStatusComponent implements OnInit {
  numberForm: FormGroup;
  order: any;
  constructor(private db: AngularFireDatabase, private fb: FormBuilder) { }
  ngOnInit() {
    this.buildForm();
    this.order = this.db.object('/orders/testPizza123');
    console.log(this.order);
  }
  updatePhoneNumber() {
      this.order.update({ phoneNumber: this.e164 })
  }
  buildForm() {
    this.numberForm = this.fb.group({
      country: this.validateMinMax(1, 2),
      area:    this.validateMinMax(3, 3),
      prefix:  this.validateMinMax(3, 3),
      line:    this.validateMinMax(4, 4)
    });
  }
  /// helper to add validations to form based on min/max length
  validateMinMax(min, max) {
    return ['', [
      Validators.required,
      Validators.minLength(min),
      Validators.maxLength(max),
      Validators.pattern('[0-9]+')  // validates input is digit
    ]]
  }
  /// converts the current form values to E164
  get e164() {
    const form = this.numberForm.value
    const num = form.country + form.area + form.prefix + form.line
    return `+${num}`
  }
}

** pizza component html **

<h1>Order Status: 
  <span class="tag is-large" 
        [ngClass]="{
                  'is-dark'    : pizza.status == 'submitted' ,
                  'is-warning' : pizza.status == 'cooking',
                  'is-primary' : pizza.status == 'on its way',
                  'is-success' : pizza.status == 'delivered'
                  }">

    {{ pizza.status }}
  </span>
</h1>
<ul>
  <li>Order Number: {{ pizza.$key }}</li>
  <li>Topping: {{ pizza.topping }}</li>
  <li>Price: {{ pizza.price }}</li>
</ul>
<hr>
<h1>Get Updates via Text Message</h1>
<form [formGroup]="numberForm" (ngSubmit)="updatePhoneNumber()" novalidate>
  <input type="text" formControlName="country"  placeholder="1">
  <input type="text" formControlName="area"     placeholder="916">
  <input type="text" formControlName="prefix"   placeholder="555">
  <input type="text" formControlName="line"     placeholder="5555">
  <input type="submit" value="Get SMS Updates" [disabled]="numberForm.invalid">
</form>
<p *ngIf="numberForm.invalid && numberForm.touched">That's not a valid phone number</p>
<h3> Updates will be texed to {{ pizza.phoneNumber || 'none' }}</h3>

** firebase函数文件夹中的索引js **

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const twilio = require('twilio');
const accountSid = functions.config().twilio.sid
const authToken  = functions.config().twilio.token
const client = new twilio(accountSid, authToken);
const twilioNumber = '+91xxxxxxxxxx' // your twilio phone number
/// start cloud function
exports.textStatus = functions.database
       .ref('/orders/{orderKey}/status')
       .onUpdate(event => {
    const orderKey = event.params.orderKey
    return admin.database()
                .ref(`/orders/${orderKey}`)
                .once('value')
                .then(snapshot => snapshot.val())
                .then(order => {
                    const status      = order.status
                    const phoneNumber = order.phoneNumber
                    if ( !validE164(phoneNumber) ) {
                        throw new Error('number must be E164 format!')
                    }
                    const textMessage = {
                        body: `Current order status: ${status}`,
                        to: phoneNumber,  // Text to this number
                        from: twilioNumber // From a valid Twilio number
                    }
                    return client.messages.create(textMessage)
                })
                .then(message => console.log(message.sid, 'success'))
                .catch(err => console.log(err))
});
/// Validate E164 format
function validE164(num) {
    return /^\+?[1-9]\d{1,14}$/.test(num)
}

我应该在这里进行任何配置

const accountSid = functions.config().twilio.sid
const authToken  = functions.config().twilio.token
const client = new twilio(accountSid, authToken);
const twilioNumber = '+91xxxxxxxxxx' // your twilio phone number

更新

现在,我可以更新firebase中的数据。数据正在更新,但我没有收到任何消息到输入的手机号码。

0 个答案:

没有答案