thomasvargiu/tmv-whatsapi

该包已被废弃,不再维护。未建议替代包。

用于与WhatsApp服务通信的完整OOP库

维护者

详细信息

github.com/thomasvargiu/TmvWhatsApi

安装: 309

依赖者: 1

建议者: 0

安全: 0

星标: 22

关注者: 10

分支: 11

该包尚未发布版本,信息有限。


README

Build Status Code Coverage Scrutinizer Code Quality Dependency Status Latest Stable Version Total Downloads Latest Unstable Version License

状态:开发

最后更新:2014年11月13日(见下方的变更列表)

不要在生产环境中使用!

关于WhatsAPI

WhatsAPI是一个用于使用WhatsApp服务的客户端库。

这是一个基于原始WhatsAPI的新项目:请参阅原始项目或新的WhatsApi官方版

为什么创建新项目?

原始的WhatsAPI库与composer不兼容,不支持PSR规范,并且非常老旧。我想开发这个新的库,使其更加可用。如果你想帮忙,请随意:)

如何开始使用此库

(未来可能有所变化)

号码注册

首先,你需要一个身份。这个字符串标识一个设备。你可以这样生成一个

use Tmv\WhatsApi\Service\IdentityService;

$identityId = IdentityService::generateIdentity();

每次连接到服务时都需要它,所以你应该将其保存以标识你的设备(你可以使用urlencodeurldecode`来保存)。

现在,你可以请求一个验证码以验证你的号码

use Tmv\WhatsApi\Service\LocalizationService;
use Tmv\WhatsApi\Service\IdentityService;
use Tmv\WhatsApi\Service\PcntlListener;
use Tmv\WhatsApi\Service\MediaService;
use Tmv\WhatsApi\Entity\Phone;
use Tmv\WhatsApi\Entity\Identity;
use Tmv\WhatsApi\Client;
use Tmv\WhatsApi\Options;
use Zend\EventManager\EventInterface;

// Initializing client
// Creating a service to retrieve phone info
$localizationService = new LocalizationService();
$localizationService->setCountriesPath(__DIR__ . '/data/countries.csv');
$identityService = new IdentityService();
$identityService->setNetworkInfoPath(__DIR__ . '/data/networkinfo.csv');

// Creating a phone object...
$phone = new Phone(''); // Your number with international prefix (without ```+``` or ```00```)
// Injecting phone properties
$localizationService->injectPhoneProperties($phone);

$identity = new Identity();
$identity->setNickname($nickname); // Nickname to use for notifications
$identity->setIdentityToken($identityId); // Previously generated identity
$identity->setPhone($phone);

$res = $identityService->codeRequest($identity);
/*
var_dump() of $res:
array(4) {
  'status' =>
  string(4) "sent"
  'length' =>
  int(6)
  'method' =>
  string(3) "sms"
  'retry_after' =>
  int(25205)
}
*/

如果发生错误,将抛出异常。如果一切顺利,将向你的号码发送包含验证码的短信。`IdentityService::codeRequest()`的第二个参数可以接受两个字符串

  • sms:将向你的号码发送包含验证码的短信
  • voice:你会接到电话,语音会告诉你验证码

现在你需要输入验证码

// ...
$res = $identityService->codeRegister($identity, $code);
/*var_dump() of $res:
array(10) {
  'status' =>
  string(2) "ok"
  'login' =>
  string(12) "39123456789"
  'pw' =>
  string(28) "xxxxxxxxxxxxxxx="
  'type' =>
  string(3) "new"
  'expiration' =>
  int(1454786892)
  'kind' =>
  string(4) "free"
  'price' =>
  string(8) "€ 0,89"
  'cost' =>
  string(4) "0.89"
  'currency' =>
  string(3) "EUR"
  'price_expiration' =>
  int(1426348327)
}
*/

结果是简单的,你可以理解它。最重要的键是pw。这是你的密码,保存它!

初始化客户端

use Tmv\WhatsApi\Service\LocalizationService;
use Tmv\WhatsApi\Entity\Phone;
use Tmv\WhatsApi\Entity\Identity;
use Tmv\WhatsApi\Client;
use Tmv\WhatsApi\Service\PcntlListener;
use Tmv\WhatsApi\Service\MediaService;
use Tmv\WhatsApi\Options;
use Zend\EventManager\EventInterface;

// Initializing client
// Creating a service to retrieve phone info
$localizationService = new LocalizationService();
$localizationService->setCountriesPath(__DIR__ . '/data/countries.csv');

// Creating a phone object...
$phone = new Phone(''); // your phone number with international prefix
// Injecting phone properties
$localizationService->injectPhoneProperties($phone);

// Creating identity
$identity = new Identity();
$identity->setNickname(''); // your name
$identity->setIdentityToken('');    // your token
$identity->setPassword(''); // your password
$identity->setPhone($phone);

// Initializing client
$client = new Client($identity);
$client->setChallengeDataFilepath(__DIR__ . '/data/nextChallenge.dat');

// Attach PCNTL listener to handle signals (if you have PCNTL extension)
// This allow to kill process softly
$pcntlListener = new PcntlListener();
$client->getEventManager()->attach($pcntlListener);

// Creating MediaService for media messages
$mediaServiceOptions = new Options\MediaService();
$mediaServiceOptions->setMediaFolder(sys_get_temp_dir());
$mediaServiceOptions->setDefaultImageIconFilepath(__DIR__ . '/data/ImageIcon.jpg');
$mediaServiceOptions->setDefaultVideoIconFilepath(__DIR__ . '/data/VideoIcon.jpg');
$mediaService = new MediaService($mediaServiceOptions);
$client->setMediaService($mediaService);

// Attaching events...
// ...

$client->getEventManager()->attach('onConnected', function(EventInterface $e) {
    /** @var Client $client */
    $client = $e->getTarget();

    // Actions
    // ...
});

// Connect, login and process messages
// Automatically send presence every 10 seconds
$client->run();

同步号码

在向一个号码发送消息之前,你必须同步你的联系人。

use Tmv\WhatsApi\Message\Action;

$client->getEventManager()->attach('onConnected', function(EventInterface $e) {
    /** @var Client $client */
    $client = $e->getTarget();

    $action = new Action\SyncContacts($client->getIdentity()->getPhone()->getPhoneNumber());
    $action->addNumber('+39123456789');
    $client->send($action);
});

// Connect, login and process messages
// Automatically send presence every 10 seconds
$client->run();

发送消息

use Tmv\WhatsApi\Message\Action;
use Tmv\WhatsApi\Entity\MediaFileInterface;

$number = ''; // number to send message
// Sending composing notification (simulating typing)
$client->send(new Action\ChatState($number, Action\ChatState::STATE_COMPOSING));
// Sending paused notification (typing end)
$client->send(new Action\ChatState($number, Action\ChatState::STATE_PAUSED));

// Creating text message action
$message = new Action\MessageText($identity->getNickname(), $number);
$message->setBody('Hello');

// OR: creating media (image, video, audio) message (beta)
$mediaFile = $client->getMediaService()
    ->getMediaFileFactory()
    ->factory('/path/to/image.png', MediaFileInterface::TYPE_IMAGE);
$message = new Action\MessageMedia();
$message->setTo($number)
    ->setMediaFile($mediaFile);

// Sending message...
$client->send($message);

接收消息

use Tmv\WhatsApi\Event\MessageReceivedEvent;
use Tmv\WhatsApi\Message\Received;

// onMessageReceived event
$client->getEventManager()->attach(
    'onMessageReceived',
    function (MessageReceivedEvent $e) {
        $message = $e->getMessage();
        echo str_repeat('-', 80) . PHP_EOL;
        echo '** MESSAGE RECEIVED **' . PHP_EOL;
        echo sprintf('From: %s', $message->getFrom()) . PHP_EOL;
        if ($message->isFromGroup()) {
            echo sprintf('Group: %s', $message->getGroupId()) . PHP_EOL;
        }
        echo sprintf('Date: %s', $message->getDateTime()->format('Y-m-d H:i:s')) . PHP_EOL;

        if ($message instanceof Received\MessageText) {
            echo PHP_EOL;
            echo sprintf('%s', $message->getBody()) . PHP_EOL;
        } elseif ($message instanceof Received\MessageMedia) {
            echo sprintf('Type: %s', $message->getMedia()->getType()) . PHP_EOL;
        }
        echo str_repeat('-', 80) . PHP_EOL;
    }
);

调试

可以通过附加事件进行调试。可以监听附加到'*'事件的全部事件。

use Zend\EventManager\EventInterface;

// Debug events
$client->getEventManager()->attach(
    'node.received',
    function (EventInterface $e) {
        $node = $e->getParam('node');
        echo sprintf("\n--- Node received:\n%s\n", $node);
    }
);
$client->getEventManager()->attach(
    'node.send.pre',
    function (EventInterface $e) {
        $node = $e->getParam('node');
        echo sprintf("\n--- Sending Node:\n%s\n", $node);
    }
);

公共事件

  • onMessageReceived(所有消息的通用事件)
  • onMessageTextReceived
  • onMessageMediaImageReceived
  • onMessageMediaAudioReceived
  • onMessageMediaVideoReceived
  • onMessageMediaVcardReceived
  • onMessageMediaLocationReceived
  • onConnected
  • onLoginFailed
  • onReceiptServer
  • onReceiptClient
  • onPresenceReceived
  • onGroupParticipantAdded
  • onGroupParticipantRemoved
  • onGetGroupsResult
  • onGetGroupInfoResult

变更列表

2014年11月13日

  • 图像和视频的图标生成
  • 为视频图标生成建议的composer可选依赖

2014年11月9日

  • 添加了MessageMedia动作以发送图片、视频和音频消息(尚不支持生成的图标)