小程式封裝獲取太陽碼
阿新 • • 發佈:2020-07-03
<?php /** * User: Eden * Date: 2019/3/21 * 共有內容 */ namespace Common\Util; use Vendor\Func\Http; class WxUtil extends CommonUtil { public function __construct() { parent::__construct(); } /** * 獲取太陽碼 * scene 為傳入的引數 * page 為小程式的頁面路徑,務必是釋出之後存在的路徑 */ public function get_xcx_code($scene, $page) { $request_data = [ 'scene' => $scene, 'page' => $page, 'width' => 280 ]; $wxUtil = new WxUtil(); $access_token = $wxUtil->get_access_token(); if (!$access_token){ return false; } $request_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token; $result = Http::doPostJson($request_url,$request_data); $decode_result = json_decode($result,true); if ($decode_result['errcode']){ return false; } // 存入cdn $uploadUtil = new UploadUtil(); $cdn_result = $uploadUtil->uploadCdn($result,'suncode'); if ($cdn_result['errno'] == 0){ return $cdn_result['save_name']; } else { return false; } } /** * 獲取access_token * 小程式的appid,secret * 或者 * 公眾號的appid,secret 公眾號獲取access_token需要配置ip白名單 */ public function get_access_token($app_id = '', $app_secret = '') { $app_id = $app_id ?: C('APP_ID'); $app_secret = $app_secret ?: C('APP_SECRET'); // 查詢快取中是否存在 $key = "access_token_" . $app_id; $ttl = $this->red->ttl($key); if ($ttl == -2) { // 不存在 // step1 獲取 $request_url = "https://api.weixin.qq.com/cgi-bin/token?"; $request_url .= "grant_type=client_credential&appid=" . $app_id . "&secret=" . $app_secret; $data = json_decode(Http::doGet($request_url, 5), true); // step2 儲存 $this->red->setex($key, $data['expires_in'] - 1000, $data['access_token']); return $data['access_token']; } else { return $this->red->get($key); } } }