<?php
/**
* User: Eden
* Date: 2019/3/21
* 共有内容
*/
namespace CommonUtil;
use VendorFuncHttp;
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);
}
}
}