獲取微信公眾號或小程序的access_token


<?php

/**
 * User: Eden
 * Date: 2019/3/21
 * 共有內容
 */

namespace Common\Service;

use Vendor\Func\Http;

class AccessTokenService extends CommonService
{
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 獲取access_token
     * 小程序的appid,secret
     * 或者
     * 公眾號的appid,secret 公眾號獲取access_token需要配置ip白名單
     */ 
    public function get_access_token($app_id, $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);
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM