composer require overtrue/wechat
After the installation, include the EasyWeChat autoload file in the project:
require_once 'vendor/autoload.php';
Next, we need to configure EasyWeChat. Create a config.php file in the project root directory and configure it as follows:
<?php return [ 'app_id' => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', 'token' => 'YOUR_TOKEN', 'log' => [ 'level' => 'debug', 'file' => 'path/to/log.log', ], ];
Replace YOUR_APP_ID, YOUR_APP_SECRET, and YOUR_TOKEN with your Mini Program's AppID, AppSecret, and Token. The log configuration is optional and used for logging purposes.
$wechat = new EasyWeChat\Foundation\Application(require_once 'config.php'); $accessToken = $wechat->access_token; $token = $accessToken->getToken();
$shareLink = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $token . '&path=pages/index/index&scene=123';
The path parameter specifies the page path of the Mini Program, and the scene parameter specifies the scene value.
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $token); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'touser' => 'OPENID', 'msgtype' => 'news', 'news' => [ 'articles' => [ [ 'title' => 'Share Title', 'description' => 'Share Description', 'url' => $shareLink, 'picurl' => 'Share Image URL', ], ], ], ], JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch);
Replace OPENID with the user's openid, and title, description, url, and picurl with the share title, description, link, and image URL respectively.