PHP code example of megakit / php-huawei-pushkit

1. Go to this page and download the library: Download megakit/php-huawei-pushkit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

megakit / php-huawei-pushkit example snippets




use MegaKit\Huawei\PushKit\Data\Destination\TokenDestination;
use MegaKit\Huawei\PushKit\Data\Message\Android\AndroidClickAction;
use MegaKit\Huawei\PushKit\DataBuilder\Message\Android\AndroidClickActionBuilder;
use MegaKit\Huawei\PushKit\DataBuilder\Message\Android\AndroidConfigBuilder;
use MegaKit\Huawei\PushKit\DataBuilder\Message\Android\AndroidNotificationBuilder;
use MegaKit\Huawei\PushKit\DataBuilder\Message\MessageBuilder;
use MegaKit\Huawei\PushKit\DataBuilder\Message\NotificationBuilder;
use MegaKit\Huawei\PushKit\Exceptions\HuaweiException;
use MegaKit\Huawei\PushKit\Factory\SenderFactory;
use MegaKit\Huawei\PushKit\HttpConfigBuilder;
use MegaKit\Huawei\PushKit\HuaweiConfigBuilder;

$config = [
    'app_id' => '<APP_ID>',
    'oauth_client_id' => '<OAUTH_CLIENT_ID>',
    'oauth_client_secret' => '<OAUTH_CLIENT_SECRET>',
];

$tokens = [
    '<PUSH_TOKEN_OF_TARGET_USER>',
];

$huaweiConfig = HuaweiConfigBuilder::withDefaults()
    ->setAppId($config['app_id'])
    ->setOAuthCredentials($config['oauth_client_id'], $config['oauth_client_secret'])
    ->build();

$httpConfig = HttpConfigBuilder::withDefaults()->build();

$senderFactory = new SenderFactory();
$sender = $senderFactory->createSenderWithConfig($huaweiConfig, $httpConfig);

$notification = NotificationBuilder::make()
    ->setTitle('Hello')
    ->setBody('World')
    ->build();

$androidNotification = AndroidNotificationBuilder::make()
    ->setClickAction(
        AndroidClickActionBuilder::make()
            ->setType(AndroidClickAction::TYPE_START_APP)
            ->build()
    )
    ->build();

$androidConfig = AndroidConfigBuilder::make()
    ->setNotification($androidNotification)
    ->build();

$message = MessageBuilder::make()
    ->setNotification($notification)
    ->setAndroid($androidConfig)
    ->setData(['hello' => 'world'])
    ->build();

$destination = new TokenDestination($tokens);

try {
    $sender->sendMessage($message, $destination);
    echo 'Message sent successfully' . PHP_EOL;
} catch (HuaweiException $e) {
    echo 'Error sending message: ' . $e->getMessage() . ' (' . $e->getCode() . ')' . PHP_EOL;
}
shell script
$ composer