With the continuous growth of the WeChat Mini Program ecosystem, live streaming has become a key feature for brands and content creators. EasyWeChat, a powerful PHP SDK, makes it easier to integrate WeChat APIs. This tutorial walks you through building a live streaming feature using EasyWeChat and PHP.
Before starting development, ensure you have the following ready:
EasyWeChat SDK installed and integrated into your PHP project.
A WeChat Mini Program account with live streaming functionality enabled.
Log in to the WeChat developer platform and create a new mini program. During setup, make sure to enable the Live Streaming module and take note of your AppID and AppSecret.
Create a wechat.php file in your PHP project root and insert the following configuration:
<?php
return [
'app_id' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => '/tmp/easywechat.log',
],
];
Replace YOUR_APP_ID and YOUR_APP_SECRET with the credentials from your WeChat Mini Program.
Load your configuration and initialize the EasyWeChat Mini Program instance:
<?php
use EasyWeChat\Factory;
$config = require 'wechat.php';
$app = Factory::miniProgram($config);
AccessToken is required to call most WeChat APIs. Retrieve it using:
<?php
$accessToken = $app->access_token->getToken();
Use the following code to create a new live room:
<?php
$response = $app->live->createRoom([
'name' => 'My Live Room',
'cover_img' => 'http://example.com/cover.jpg',
'startTime' => time(),
'endTime' => time() + 3600,
]);
$roomId = $response['roomid'];
To promote your live room, generate a QR code with this code:
<?php
$qrcodeUrl = $app->live->getRoomQrcode($roomId);
Start streaming when your session begins using the following:
<?php
$response = $app->live->start($roomId);
$livePushUrl = $response['push_url'];
Use the component on the mini program frontend to play the stream:
<video src="{{livePushUrl}}" autoplay></video>
Replace {{livePushUrl}} with your actual streaming URL.
To end the stream, use the following code:
<?php
$app->live->stop($roomId);
By following these 11 steps, you’ve successfully built a live video streaming feature into your WeChat Mini Program using PHP and EasyWeChat. This solution is suitable for various scenarios such as e-commerce live sales, event broadcasting, and more.
For more advanced features, consult the official EasyWeChat and WeChat Mini Program documentation, and tailor the integration to your specific project requirements.