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。