Example #1
0
 /**
  * Request a registration code from WhatsApp.
  *
  * @param string $method
  *   Accepts only 'sms' or 'voice' as a value.
  * @param string $countryCode
  *   ISO Country Code, 2 Digit.
  * @param string $langCode
  *   ISO 639-1 Language Code: two-letter codes.
  *
  * @return object
  *   An object with server response.
  *   - status: Status of the request (sent/fail).
  *   - length: Registration code lenght.
  *   - method: Used method.
  *   - reason: Reason of the status (e.g. too_recent/missing_param/bad_param).
  *   - param: The missing_param/bad_param.
  *   - retry_after: Waiting time before requesting a new code.
  *
  * @throws \Exception
  */
 public function codeRequest($method = 'sms', $countryCode = null, $langCode = null)
 {
     if (!($phone = $this->dissectPhone())) {
         throw new \Exception('The provided phone number is not valid.');
     }
     if ($countryCode == null && $phone['ISO3166'] != '') {
         $countryCode = $phone['ISO3166'];
     }
     if ($countryCode == null) {
         $countryCode = 'US';
     }
     if ($langCode == null && $phone['ISO639'] != '') {
         $langCode = $phone['ISO639'];
     }
     if ($langCode == null) {
         $langCode = 'en';
     }
     // Build the token.
     $token = Token::generateRequestToken($phone['country'], $phone['phone']);
     // Build the url.
     $host = 'https://' . static::WHATSAPP_REQUEST_HOST;
     $query = array('cc' => $phone['cc'], 'in' => $phone['phone'], 'to' => $this->phoneNumber, 'lg' => $langCode, 'lc' => $countryCode, 'method' => $method, 'mcc' => $phone['mcc'], 'mnc' => '001', 'token' => urlencode($token), 'id' => $this->identity);
     if ($this->debug) {
         print_r($query);
     }
     $response = $this->getResponse($host, $query);
     if ($this->debug) {
         print_r($response);
     }
     if ($response->status == 'ok') {
         $this->eventManager()->fireCodeRegister($this->phoneNumber, $response->login, $response->pw, $response->type, $response->expiration, $response->kind, $response->price, $response->cost, $response->currency, $response->price_expiration);
     } else {
         if ($response->status != 'sent') {
             if (isset($response->reason) && $response->reason == "too_recent") {
                 $this->eventManager()->fireCodeRequestFailedTooRecent($this->phoneNumber, $method, $response->reason, $response->retry_after);
                 $minutes = round($response->retry_after / 60);
                 throw new \Exception("Code already sent. Retry after {$minutes} minutes.");
             } else {
                 $this->eventManager()->fireCodeRequestFailed($this->phoneNumber, $method, $response->reason, $response->param);
                 throw new \Exception('There was a problem trying to request the code.');
             }
         } else {
             $this->eventManager()->fireCodeRequest($this->phoneNumber, $method, $response->length);
         }
     }
     return $response;
 }