PHP code example of tourze / wechat-official-account-bundle
1. Go to this page and download the library: Download tourze/wechat-official-account-bundle 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/ */
tourze / wechat-official-account-bundle example snippets
use WechatOfficialAccountBundle\Entity\Account;
use WechatOfficialAccountBundle\Service\OfficialAccountClient;
// Create account entity
$account = new Account();
$account->setName('My WeChat Account');
$account->setAppId('your-app-id');
$account->setAppSecret('your-app-secret');
$account->setToken('your-token'); // Optional
$account->setEncodingAesKey('your-encoding-aes-key'); // Optional
$account->setValid(true);
// Persist to database
$entityManager->persist($account);
$entityManager->flush();
use WechatOfficialAccountBundle\Service\OfficialAccountClient;
use WechatOfficialAccountBundle\Request\Token\GetTokenRequest;
// Inject the client service
public function __construct(
private OfficialAccountClient $client
) {}
// Get access token
$tokenRequest = new GetTokenRequest();
$tokenRequest->setAccount($account);
$response = $this->client->request($tokenRequest);
// Response contains: ['access_token' => '...', 'expires_in' => 7200]
use WechatOfficialAccountBundle\Entity\CallbackIP;
$callbackIP = new CallbackIP();
$callbackIP->setIp('127.0.0.1');
$callbackIP->setDescription('Development server');
$callbackIP->setAccount($account);
$account->addCallbackIP($callbackIP);
use WechatOfficialAccountBundle\Request\WithAccountRequest;
class GetUserInfoRequest extends WithAccountRequest
{
private string $openid;
public function getRequestPath(): string
{
return 'https://api.weixin.qq.com/cgi-bin/user/info';
}
public function getRequestOptions(): ?array
{
return [
'query' => [
'openid' => $this->openid,
'lang' => 'zh_CN',
],
];
}
public function getRequestMethod(): ?string
{
return 'GET';
}
public function setOpenid(string $openid): void
{
$this->openid = $openid;
}
}
use WechatOfficialAccountBundle\Exception\WechatApiException;
try {
$response = $this->client->request($request);
} catch (WechatApiException $e) {
// Handle WeChat API specific errors
$errorCode = $e->getErrorCode();
$errorMessage = $e->getErrorMessage();
}
// The bundle automatically refreshes tokens when:
// 1. Token is null or empty
// 2. Token has expired (with 10-second buffer)
// 3. API returns token-related error
$tokenRequest = new GetTokenRequest();
$tokenRequest->setAccount($account);
$tokenRequest->setForceRefresh(true); // Force token refresh