WeChat 공개 계정이 널리 사용됨에 따라 점점 더 많은 기업과 개인이 그래픽 메시지를 통해 사용자에게 콘텐츠를 전달하고 제품을 홍보하기를 희망하고 있습니다. 이 글에서는 준비, access_token 획득, 메시지 작성 및 푸시 프로세스를 포함하여 PHP를 사용하여 WeChat 공식 계정의 이미지 및 문자 메시지 푸시 기능을 구현하는 방법을 소개합니다.
개발을 시작하기 전에 다음 준비를 완료해야 합니다.
WeChat 공식 계정 인터페이스를 호출하기 전에 먼저 access_token을 얻어야 합니다. WeChat 인터페이스에서 호출하는 글로벌 자격 증명입니다. 다음은 access_token을 얻기 위한 PHP 샘플 코드입니다.
function getAccessToken($appId, $appSecret) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
$result = file_get_contents($url);
$result = json_decode($result, true);
return $result['access_token'];
}
$appId = "your_app_id";
$appSecret = "your_app_secret";
$accessToken = getAccessToken($appId, $appSecret);
your_app_id 및 your_app_secret를 공식 계정의 실제 매개변수로 바꾸세요.
access_token을 얻은 후 그래픽 메시지의 데이터 구조를 준비할 수 있습니다. 각 그래픽 메시지에는 제목, 설명, 이미지 링크 및 점프 링크가 포함됩니다. 예는 다음과 같습니다:
$articles = array(
array(
'title' => "그래픽 메시지 제목1",
'description' => "그래픽 메시지 설명1",
'url' => "http://example.com/article1",
'picurl' => "http://example.com/article1.jpg"
),
array(
'title' => "그래픽 메시지 제목2",
'description' => "그래픽 메시지 설명2",
'url' => "http://example.com/article2",
'picurl' => "http://example.com/article2.jpg"
),
);
푸시 정보를 풍부하게 하기 위해 필요에 따라 여러 그래픽 콘텐츠를 추가할 수 있습니다.
그래픽 콘텐츠가 구성된 후 WeChat의 그룹 전송 인터페이스를 통해 푸시될 수 있습니다. 다음은 푸시 요청의 PHP 예입니다.
function sendArticles($accessToken, $articles) {
$url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$accessToken;
$data = array(
'touser' => "@all",
'msgtype' => "news",
'news' => array('articles' => $articles)
);
$jsonData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendArticles($accessToken, $articles);
푸시를 수행하려면 변수 $accessToken을 획득한 access_token으로 바꾸세요.
위의 단계를 통해 위챗 공식 계정의 이미지 및 문자 메시지 푸시 기능을 구현할 수 있습니다. 개발자는 PHP와 WeChat API의 조합을 사용하여 콘텐츠를 팔로어에게 효율적이고 자동으로 푸시할 수 있으므로 공개 계정의 운영 효율성과 사용자 상호 작용 경험이 향상됩니다.
실제 사용 시, 시스템의 안정적인 작동을 보장하기 위해 WeChat의 공식 인터페이스 통화 빈도 제한 및 푸시 규칙에 주의하시기 바랍니다.