composer require overtrue/wechat
安装完成后,在项目中引入EasyWeChat的自动加载文件:
require_once 'vendor/autoload.php';
接下来,我们需要配置EasyWeChat。在项目根目录下创建一个config.php文件,并按照以下代码进行配置:
<?php
return [
'app_id' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'token' => 'YOUR_TOKEN',
'log' => [
'level' => 'debug',
'file' => 'path/to/log.log',
],
];
将YOUR_APP_ID、YOUR_APP_SECRET和YOUR_TOKEN替换为你的小程序的AppID、AppSecret和Token。log配置可选,用于记录日志。
$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';
其中,path参数用于指定小程序的页面路径,scene参数用于指定场景值。
$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' => '分享标题',
'description' => '分享描述',
'url' => $shareLink,
'picurl' => '分享图片URL',
],
],
],
], JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
将OPENID替换为用户的openid,title、description、url和picurl分别为分享的标题、描述、链接和图片URL。