PHP code example of sendgo / symfony

1. Go to this page and download the library: Download sendgo/symfony 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/ */

    

sendgo / symfony example snippets



// config/bundles.php

return [
    // ...
    Sendgo\Symfony\SendgoBundle::class => ['all' => true],
];


// src/Controller/OrderController.php

namespace App\Controller;

use App\Entity\Order;
use Sendgo\Php\Sendgo;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

class OrderController extends AbstractController
{
    public function __construct(private Sendgo $sendgo) {}

    #[Route('/orders/{id}/confirm', methods: ['POST'])]
    public function confirm(Order $order): JsonResponse
    {
        $this->sendgo->alimtalk->send([
            'templateCode' => 'ORDER_CONFIRM_001',
            'contacts'     => [
                [
                    'contact' => $order->getUser()->getPhone(),
                    'name'    => $order->getUser()->getName(),
                    'var1'    => $order->getNumber(),
                    'var2'    => number_format($order->getTotal()) . '원',
                ],
            ],
        ]);

        return $this->json(['success' => true]);
    }
}



use Sendgo\Php\Sendgo;

class MyService
{
    // 생성자 오토와이어링으로 자동 주입
    public function __construct(private Sendgo $sendgo) {}
}

$sendgo = $container->get('sendgo'); // Sendgo\Php\Sendgo 인스턴스



use Sendgo\Php\Sendgo;

// 다건 발송
$sendgo->alimtalk->send([
    'templateCode' => 'ORDER_CONFIRM_001',
    'contacts'     => [
        ['contact' => '01011111111', 'name' => '홍길동', 'var1' => 'ORD-001', 'var2' => '29,000원'],
        ['contact' => '01022222222', 'name' => '김철수', 'var1' => 'ORD-002', 'var2' => '15,000원'],
        ['contact' => '01033333333', 'name' => '이영희', 'var1' => 'ORD-003', 'var2' => '52,000원'],
    ],
]);

// 예약 발송
$sendgo->alimtalk->send([
    'templateCode' => 'PROMO_SUMMER_2026',
    'scheduleType' => 'SCHEDULED',
    'at'           => '2026-07-28 09:00:00',
    'contacts'     => [['contact' => '01012345678', 'var1' => '여름 한정 50% 할인']],
]);

// SMS 자동 대체 발송
$sendgo->alimtalk->send([
    'templateCode' => 'DELIVERY_START_001',
    'replaceSms'   => 'Y',
    'smsSubject'   => '[배송 시작 안내]',
    'smsContent'   => "주문하신 상품이 출고되었습니다.\n송장번호: #{var2}",
    'contacts'     => [['contact' => '01012345678', 'var1' => 'ORD-001', 'var2' => '1234567890']],
]);



// 텍스트형
$sendgo->friendtalk->send([
    'content'  => '안녕하세요! 7월 한정 특가 이벤트를 확인해보세요.',
    'contacts' => [['contact' => '01012345678']],
]);

// 이미지형
$sendgo->friendtalk->send([
    'messageType' => 'FI',
    'content'     => '이번 주 특가 상품을 확인하세요!',
    'imageUrl'    => 'https://cdn.example.com/banner.jpg',
    'imageLink'   => 'https://example.com/event',
    'contacts'    => [['contact' => '01012345678']],
]);

// 버튼 포함
$sendgo->friendtalk->send([
    'content'  => '7월 쿠폰이 도착했습니다! 지금 바로 사용하세요.',
    'buttons'  => [
        ['name' => '쿠폰 받기', 'type' => 'WL', 'linkMo' => 'https://example.com/coupon'],
        ['name' => '고객센터', 'type' => 'WL', 'linkMo' => 'https://example.com/cs'],
    ],
    'contacts' => [['contact' => '01012345678']],
]);



// SMS (90자 이하)
$sendgo->sms->sendSms([
    'content'  => '[Sendgo] 인증번호: 123456 (5분 이내 입력)',
    'contacts' => [['contact' => '01012345678']],
]);

// LMS (장문, 2,000자 이하)
$sendgo->sms->sendLms([
    'subject'  => '[중요] 서비스 점검 안내',
    'content'  => "안녕하세요. 서비스 점검이 예정되어 있습니다.\n\n■ 일시: 2026-07-25 02:00 ~ 06:00\n■ 영향: 전체 서비스",
    'contacts' => [['contact' => '01012345678']],
]);

// MMS (이미지 포함)
$sendgo->sms->sendMms([
    'subject'  => '[이벤트] 7월 특가',
    'content'  => '이번 달 특가 상품을 확인하세요!',
    'contacts' => [['contact' => '01011111111'], ['contact' => '01022222222']],
]);


// src/Service/NotificationService.php

namespace App\Service;

use Psr\Log\LoggerInterface;
use Sendgo\Php\Sendgo;
use Sendgo\Php\Exception\SendgoException;

class NotificationService
{
    public function __construct(
        private Sendgo $sendgo,
        private LoggerInterface $logger,
    ) {}

    public function sendOrderConfirm(string $phone, string $orderNo, int $amount): void
    {
        $this->sendgo->alimtalk->send([
            'templateCode' => 'ORDER_CONFIRM_001',
            'contacts'     => [
                ['contact' => $phone, 'var1' => $orderNo, 'var2' => number_format($amount) . '원'],
            ],
        ]);
    }

    public function sendVerificationCode(string $phone, string $code): void
    {
        try {
            // 알림톡 우선, 실패 시 SMS 대체
            $this->sendgo->alimtalk->send([
                'templateCode' => 'VERIFY_CODE_001',
                'replaceSms'   => 'Y',
                'smsContent'   => "[인증] 인증번호: {$code} (5분 이내 입력)",
                'contacts'     => [['contact' => $phone, 'var1' => $code]],
            ]);
        } catch (SendgoException $e) {
            $this->logger->error('Sendgo 인증번호 발송 실패', [
                'phone'      => $phone,
                'error_code' => $e->getErrorCode(),
                'status'     => $e->getStatusCode(),
            ]);
            throw $e;
        }
    }
}


// src/Message/SendAlimtalkMessage.php

namespace App\Message;

class SendAlimtalkMessage
{
    public function __construct(
        public readonly string $templateCode,
        public readonly array $contacts,
    ) {}
}


// src/MessageHandler/SendAlimtalkHandler.php

namespace App\MessageHandler;

use App\Message\SendAlimtalkMessage;
use Sendgo\Php\Sendgo;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class SendAlimtalkHandler
{
    public function __construct(private Sendgo $sendgo) {}

    public function __invoke(SendAlimtalkMessage $message): void
    {
        $this->sendgo->alimtalk->send([
            'templateCode' => $message->templateCode,
            'contacts'     => $message->contacts,
        ]);
    }
}

// 디스패치 예시
$bus->dispatch(new SendAlimtalkMessage('ORDER_CONFIRM_001', [
    ['contact' => '01012345678', 'var1' => 'ORD-001'],
]));



use Sendgo\Php\Exception\SendgoException;

try {
    $sendgo->alimtalk->send([...]);
} catch (SendgoException $e) {
    $logger->error('Sendgo 발송 실패', [
        'status'     => $e->getStatusCode(),
        'error_code' => $e->getErrorCode(),
        'endpoint'   => $e->getEndpoint(),
    ]);

    match ($e->getErrorCode()) {
        'INVALID_ACCESS_KEY',
        'INVALID_SECRET_KEY'    => $this->alertOps('Sendgo 인증키 오류'),
        'INVALID_TEMPLATE_CODE' => $logger->warning('존재하지 않는 템플릿'),
        'PAYMENT_REQUIRED'      => $this->alertOps('Sendgo 크레딧 부족'),
        'IP_NOT_ALLOWED'        => $this->alertOps('허용되지 않은 IP'),
        default                 => null,
    };
}



namespace App\Controller;

use Sendgo\Php\Sendgo;
use Symfony\Component\HttpFoundation\JsonResponse;

class OnboardingController
{
    public function __construct(private Sendgo $sendgo) {}

    public function registerChannel(string $yellowId, string $phone): JsonResponse
    {
        // 1단계 — 카카오가 관리자 휴대폰으로 인증번호를 SMS 발송한다
        $this->sendgo->kakaoSenders->requestToken($yellowId, $phone);

        return new JsonResponse(['message' => '인증번호를 발송했습니다.']);
    }

    public function completeChannel(string $yellowId, string $phone, string $code): JsonResponse
    {
        $created = $this->sendgo->kakaoSenders->create([
            'token'        => $code,
            'yellowId'     => $yellowId,
            'phoneNumber'  => $phone,
            'categoryCode' => '001001',
        ]);

        return new JsonResponse($created['data']['sender']);
    }
}

// 오토와이어링한 Sendgo\Php\Sendgo 인스턴스를 사용합니다.
$sendgo->templateFolders->list(['templateType' => 'notice']);