获取微信小程序AccessToken

<?php

/**
 * User: Eden
 * Date: 2019/3/21
 * 共有内容
 */
namespace Common\Service;
use Common\Util\JsonUtil;
use Vendor\Func\Http;
use Vendor\Func\Red;

class WxService extends CommonService {
    /**
     * 获取小程序token
     * $app_id
     * $app_secret
     */
    public function getXcxAccessToken($app_id,$app_secret) {
        // 存到redis中
        $red_key = 'xcx:access_token:'.$app_id;
        $redis = Red::create();
        $access_token = $redis->get($red_key);
        if (!$access_token) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret;
            $return_data = Http::doGet($url);
            $return_data = JsonUtil::jsonDecode($return_data);
            $redis->set($red_key,JsonUtil::jsonEncode($return_data['access_token']),$return_data['expires_in'] - 1000); // 存两小时以内
            $access_token = $return_data['access_token'];
        } else {
            $access_token = JsonUtil::jsonDecode($access_token);
        }
        return $access_token;
    }
}
posted @ 2021-12-17 16:34  TBHacker  阅读(402)  评论(0编辑  收藏  举报