微信公眾平台提供建立永久/臨時二維碼 API,本文封裝完整 Weixin 類別,涵蓋 Access Token 獲取、二維碼 Ticket 換取、圖片下載儲存、錯誤日誌記錄,可直接用於專案。
namespace Home\Common;
class Weixin {
static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";
// 公開方法:生成二維碼並下載儲存
public function getEwm($wechatid, $fqid, $type = 1) { ... }
// 內部方法:組裝請求、HTTP POST、下載圖片、錯誤日誌
protected function getQrcodeurl($access_token, $fqid, $type) { ... }
protected function getToken($appid, $secret) { ... }
protected function http_post_data($url, $data_string) { ... }
protected function DownLoadQr($url, $filestring) { ... }
private function ErrorLogger($errMsg) { ... }
}
/cgi-bin/token,快取 7200 秒(建議加入快取層)。QR_LIMIT_SCENE):scene_id 為數字 ID,數量限制較少。QR_SCENE):expire_seconds 最大 2592000(30天),數量無限制。showqrcode,直接下載二進位圖片儲存至 ./Uploads/qrcode/。ErrorLog.txt。$weixin = new \Home\Common\Weixin();
// 生成永久二維碼,scene_id = 12345
$qrPath = $weixin->getEwm($wechatId = 1, $fqid = 12345, $type = 1);
echo "二維碼已儲存至:$qrPath";
$wechatid、$fqid 合法性,防止注入攻擊。exit(),讓上層統一處理 HTTP 回應。此類別提供開箱即用的微信二維碼生成功能,配合上述優化可滿足高併發生產需求。