hcportal-dev/Aiko/Libs/WhatsApp.php

571 lines
21 KiB
PHP

<?php
namespace Aiko;
use GuzzleHttp\Client;
use modules\endpoint\webhook\model\Webhook;
use Aiko\Model;
use Error;
use PDOException;
use ErrorException;
use PDO;
class WhatsApp extends Model
{
/** @var $registry hcportal registry */
protected $registry;
/** @var $sender phone number for sender */
private $sender;
/** @var Client $client guzzle http client */
private $client;
/** @var Array $messageType allowed message type */
private $messageType = ['text', 'image', 'video', 'document'];
/**
* constructor
*
* @param $registry hcportal registry
* @param String|null $baseURL
*
* @return void
*/
public function __construct($registry, $baseURL = null)
{
parent::__construct($registry);
$this->init($baseURL);
}
/**
* init component
*
* @param String|null $baseURL
*/
private function init($baseURL = null)
{
$this->sender = $this->registry->config->whatsapp_sender;
$this->client = new Client([
'base_uri' => $baseURL ?? $this->registry->config->whatsapp_endpoint,
'headers' => ['Authorization' => $this->registry->config->whatsapp_api_token, "Accept" => "application/json"],
]);
}
public function getTokenAccess(){
try{
$client= new Client();
$token='';
if($this->registry->config->wa_token_need_reload){
$data = array(
'username'=>$this->registry->config->wa_username,
'password'=>$this->registry->config->wa_password,
'grant_type'=>$this->registry->config->wa_grant_type,
'client_id'=>$this->registry->config->wa_client_id,
'client_secret'=>$this->registry->config->wa_client_secret,
);
$response = $client->post($this->registry->config->wa_auth_url, [
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
$data=json_decode($response->getBody());
$result=$this->_saveTokenAcces($data);
if(!$result){
throw new ErrorException('failed save access token to db');
}
$token=$data->access_token;
}else{
$stmt=$this->registry->db->prepare('select access_token from wa_qontak_auth where `name`=:name');
$stmt->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()==0){
throw new ErrorException('token access empty');
}
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
$token=$rs[0]['access_token'];
}
return $token;
}catch(PDOException $e){
$this->registry->log->error('WhatsApp/getTokenAccess:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}catch(ErrorException $e){
$this->registry->log->error('WhatsApp/getTokenAccess:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}
}
private function _saveTokenAcces($data){
try{
// $this->registry->db->beginTransaction();
$stmtCheck=$this->registry->db->prepare("select id from `wa_qontak_auth` where name=:name");
$stmtCheck->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
$stmtCheck->execute();
if($stmtCheck->rowCount()>0){
$stmtUpdate=$this->registry->db->prepare('update `wa_qontak_auth` set access_token=:access_token,
token_type=:token_type,
expires_in=:expires_in,
refresh_token=:refresh_token,
created_at=:created_at where `name`=:name');
$stmtUpdate->bindValue(':access_token',$data->access_token,PDO::PARAM_STR);
$stmtUpdate->bindValue(':token_type',$data->token_type,PDO::PARAM_STR);
$stmtUpdate->bindValue(':expires_in',$data->expires_in,PDO::PARAM_STR);
$stmtUpdate->bindValue(':refresh_token',$data->refresh_token,PDO::PARAM_STR);
$stmtUpdate->bindValue(':created_at',$data->created_at,PDO::PARAM_STR);
$stmtUpdate->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
$stmtUpdate->execute();
}else{
$stmtInsert=$this->registry->db->prepare('insert into `wa_qontak_auth` (
access_token,
token_type,
expires_in,
refresh_token,
created_at,
name
)values
(:access_token,
:token_type,
:expires_in,
:refresh_token,
:created_at,
:name)');
$stmtInsert->bindValue(':access_token',$data->access_token,PDO::PARAM_STR);
$stmtInsert->bindValue(':token_type',$data->token_type,PDO::PARAM_STR);
$stmtInsert->bindValue(':expires_in',$data->expires_in,PDO::PARAM_STR);
$stmtInsert->bindValue(':refresh_token',$data->refresh_token,PDO::PARAM_STR);
$stmtInsert->bindValue(':created_at',$data->created_at,PDO::PARAM_STR);
$stmtInsert->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
$stmtInsert->execute();
}
// $this->registry->db->commit();
return true;
}catch(PDOException $e){
$this->registry->db->rollBack();
$this->registry->log->error('WhatsApp/_saveTokenAcces:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}catch(ErrorException $e){
$this->registry->db->rollBack();
$this->registry->log->error('WhatsApp/_saveTokenAcces:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}
}
/**
* set sender
* @param String $sender phone number
*
* @return Aiko\Whatsapp
*
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Send message to many recepient
*
* @param Array $payload
* example of param
* [
* [
* 'phone' => '081xxx',
* 'message' => 'hi',
* 'link' => 'https://xxxx',
* 'type' => 'image' // default text-only
* ]
* ]
*/
public function sendBulkMessage($payload = [])
{
if (!is_array($payload)) {
$this->registry->log->customError('WhatsApp', "Parameter must be an array");
return false;
}
$report = [];
foreach ($payload as $value) {
$send = $this->sendMessage($value['phone'], $value['message'], $value['type'], $value['link']);
array_push($report, $send);
}
return $report;
}
public function sendBulkMessageQontak($payload = [])
{
if (!is_array($payload)) {
$this->registry->log->customError('WhatsApp', "Parameter must be an array");
return false;
}
$report = [];
foreach ($payload as $value) {
$send = $this->sendMessageQontak($value['phone'], $value['name'],$value['parameter'], $value['template']);
array_push($report, $send);
}
return $report;
}
public function sendMessage($toNumber, $message, $type = 'text', $link = null)
{
if (!in_array($type, $this->messageType)) {
$this->registry->log->customError('WhatsApp', "Message type not allowed : $type");
return false;
}
$endpoint = 'send-message';
$payload = array(
'phone' => $toNumber,
'message' => $message,
'secret' => false, // or true
'priority' => false, // or true
);
switch ($type) {
case 'image':
$endpoint = 'send-image';
$payload = array(
'phone' => $toNumber,
'caption' => $message,
'image' => $link,
'secret' => false, // or true
'priority' => false, // or true
);
break;
case 'video':
$endpoint = 'send-video';
$payload = array(
'phone' => $toNumber,
'caption' => $message,
'document' => $link,
'secret' => false, // or true
'priority' => false, // or true
);
break;
case 'document':
$endpoint = 'send-document';
$payload = array(
'phone' => $toNumber,
'document' => $link,
'secret' => false, // or true
'priority' => false, // or true
);
break;
}
// $request = $this->client->post($endpoint, array('form_params' => $payload));
// $response = $request->getBody();
// $contents = json_decode($response->getContents());
// if ($contents) {
// $webhook = new Webhook($this->registry);
// if (isset($contents->data)) {
// $data = $contents->data->message;
// foreach ($data as $value) {
// $webhook->create([
// 'phone' => $value->phone,
// 'status' => $value->status,
// 'note' => $value->text,
// 'id' => $value->id,
// 'deviceId' => $this->registry->config->whatsapp_device_id,
// ]);
// }
// }
// }
// return $contents;
return true;
}
public function sendMessageQontak($toNumber, $toName,$parameters, $templateName)
{
// try{
// // $toNumber='+6282214258200';
// $tokenAccess=$this->getTokenAccess();
// $client = new Client();
// // var_dump($templateName);
// // var_dump($this->_getTemplateId($templateName));
// // exit();
// $templateID=$this->_getTemplateId($templateName);
// if($templateID===-1){
// $this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
// return true;
// }
// $data=array(
// "to_name"=>$toName,
// "to_number"=>\Helper::formatPhoneNumber($toNumber),
// "message_template_id"=>$templateID,
// "channel_integration_id"=>$this->registry->config->channel_integration_id,
// "language"=> array(
// "code"=> "id"
// ),
// "parameters"=>array(
// "body"=>$parameters
// )
// );
// $client = new Client();
// $request = $client->request('POST', $this->registry->config->whatsapp_endpoint, [
// 'headers' => [
// 'Authorization' => 'Bearer '.$tokenAccess,
// 'Content-Type' => 'application/json', 'Accept' => 'application/json'],
// 'body' => json_encode($data)]
// );
// $response = $client->send($request);
// dd($response->json());
// $response = $client->post($this->registry->config->whatsapp_endpoint, [
// 'headers' => [
// 'Authorization' => 'Bearer '.$tokenAccess,
// 'Content-Type' => 'application/json', 'Accept' => 'application/json'],
// 'body' => json_encode($data)
// ]);
// var_dump(json_encode($responseData));
// exit();
// $responseData=json_decode($response->getBody());
// if(property_exists($responseData,'status')){
// if(!$responseData->status=='success'){
// throw new ErrorException('Gagal kirim WA');
// }
// }else{
// throw new ErrorException('Gagal kirim WA, response undefined');
// }
// return true;
// }catch(ErrorException $e){
// $this->registry->log->error('WhatsApp/sendMessageQontak:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
// return false;
// }
try {
$tokenAccess=$this->getTokenAccess();
$client = new Client();
$templateID=$this->_getTemplateId($templateName);
if($templateID===-1){
$this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
return true;
}
$data=array(
"to_name"=>$toName,
"to_number"=>\Helper::formatPhoneNumber($toNumber),
"message_template_id"=>$templateID,
"channel_integration_id"=>$this->registry->config->channel_integration_id,
"language"=> array(
"code"=> "id"
),
"parameters"=>array(
"body"=>$parameters
)
);
$request = $client->post($this->registry->config->whatsapp_endpoint, [
'headers' => [
'Authorization' => 'Bearer '.$tokenAccess,
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
$this->response = json_decode($request->getBody()->getContents());
return true;
} catch (\GuzzleHttp\Exception\RequestException $e) {
$this->errors = json_decode($e->getResponse()->getBody()->getContents());
$this->registry->log->error('WhatsApp/sendMessageQontak:'.$this->errors->error->messages[0].', user: '.\Helper::getSessionVar('username'));
}
return false;
}
private function _getTemplateId($name){
try{
$stmt=$this->registry->db->prepare('select id from wa_templates where `name`=:templateName');
$stmt->bindValue(':templateName',$name,PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()==0){
// throw new ErrorException('template id dengan name :'.$name.' kosong');
//jika template tidak ada return -1 bisa jadi sudah di non activekan
return -1;
}
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
return $rs[0]['id'];
}catch(PDOException $e){
$this->registry->log->error('WhatsApp/_getTemplateId:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}catch(ErrorException $e){
$this->registry->log->error('WhatsApp/_getTemplateId:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}
}
public function sendDocumentLocally($toNumber, $filePath, $config)
{
$handle = fopen($filePath, "r");
$file = fread($handle, filesize($filePath));
$config['size'] = filesize($filePath);
$endpoint = 'send-document-from-local';
$payload = array(
'phone' => $toNumber,
'file' => base64_encode($file),
'data' => json_encode($config),
);
$request = $this->client->post($endpoint, array('form_params' => $payload));
$response = $request->getBody();
$contents = json_decode($response->getContents());
return $contents;
}
/**
* Send message to many recepient in very sumple terms
*
* @param Array $payload
* example of param
* [
* [
* 'phone' => '081xxx',
* 'message' => 'hi',
* 'secret' => false,
* 'priority' => false
* ]
* ]
*/
public function simpleBulkMessage($params = [])
{
$endpoint = 'v2/send-bulk/text';
$request = $this->client->post($endpoint, array('body' => json_encode($params)));
$response = $request->getBody();
$contents = json_decode($response->getContents());
return $contents;
}
public function sendDocument($toNumber, $urlPath, $caption = '')
{
// $endpoint = 'send-document';
// $payload = array(
// 'phone' => $toNumber,
// 'document' => $urlPath,
// 'caption' => $caption,
// 'isGroup' => false,
// );
// $request = $this->client->post($endpoint, array('form_params' => $payload));
// $response = $request->getBody();
// $contents = json_decode($response->getContents());
// return $contents;
return true;
}
public function sendDocumentQontak($toNumber, $toName,$parameters, $templateName,$header)
{
try{
$tokenAccess=$this->getTokenAccess();
$client = new Client();
// var_dump($templateName);
// var_dump($this->_getTemplateId($templateName));
// exit();
$data=array(
"to_name"=>$toName,
"to_number"=>\Helper::formatPhoneNumber($toNumber),
"message_template_id"=>$this->_getTemplateId($templateName),
"channel_integration_id"=>$this->registry->config->channel_integration_id,
"language"=> array(
"code"=> "id"
),
"parameters"=>array(
"header"=> $header,
"body"=>$parameters
)
);
$response = $client->post($this->registry->config->whatsapp_endpoint, [
'headers' => [
'Authorization' => 'Bearer '.$tokenAccess,
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
$responseData=json_decode($response->getBody());
if(property_exists($responseData,'status')){
if(!$responseData->status=='success'){
throw new ErrorException('Gagal kirim WA');
}
}else{
throw new ErrorException('Gagal kirim WA, response undefined');
}
return true;
}catch(ErrorException $e){
$this->registry->log->error('WhatsApp/sendDocumentQontak:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
return false;
}
}
public function sendMessageQontakTermination($toNumber, $toName,$parameters, $templateName)
{
try {
$tokenAccess=$this->getTokenAccess();
$client = new Client();
$templateID=$this->_getTemplateId($templateName);
if($templateID===-1){
$this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
return true;
}
$data=array(
"to_name"=>$toName,
"to_number"=>\Helper::formatPhoneNumber($toNumber),
"message_template_id"=>$templateID,
"channel_integration_id"=>$this->registry->config->channel_integration_id,
"language"=> array(
"code"=> "id"
),
"parameters"=>array(
"body"=>$parameters
)
);
$request = $client->post($this->registry->config->whatsapp_endpoint, [
'headers' => [
'Authorization' => 'Bearer '.$tokenAccess,
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
$this->response = json_decode($request->getBody()->getContents());
return $this->response;
} catch (\GuzzleHttp\Exception\RequestException $e) {
// $this->registry->log->error('WhatsApp/sendMessageQontak:'.$this->errors->error->messages[0].', user: '.\Helper::getSessionVar('username'));
$this->errors = json_decode($e->getResponse()->getBody()->getContents());
return $this->errors;
}
}
}