Ejemplo n.º 1
0
 /**
  * 公众号用于调用微信JS接口的临时票据
  *
  * http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95
  * jsapi_ticket 的type为jsapi (腾讯demo中的JSSDK.php代码中type为1 不知为何)
  * 卡券 api_ticket 的type为 wx_card
  *
  * @param string $type
  * @return string
  */
 public static function getJsApiTicket($type = 'jsapi')
 {
     $cacheKey = parent::getApi()->getAppId() . $type . 'jsapi_ticket';
     $ticket = Cache::get($cacheKey);
     if ($ticket !== false) {
         return $ticket;
     }
     $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type={$type}&access_token=ACCESS_TOKEN";
     $data = parent::request($url);
     $ticket = $data['ticket'];
     //jsapi_ticket的有效期为7200秒
     Cache::set($cacheKey, $ticket, $data['expires_in'] - 200);
     return $ticket;
 }
Ejemplo n.º 2
0
 /**
  * 获取公众号的全局唯一票据accessToken,公众号主动调用各接口时都需使用accessToken
  * accessToken默认有效时间为7200秒,每天调用次数有限制,认证服务号每天最多100000次
  *
  * @param bool $useCache 是否使用缓存
  * @return string|null
  */
 public function getAccessToken($useCache = true)
 {
     //缓存key
     $cacheKey = md5(__FILE__ . __METHOD__ . $this->appId);
     //检查是否启用缓存
     if ($useCache) {
         if (empty($this->accessToken)) {
             $this->accessToken = Cache::get($cacheKey);
         }
         if (!empty($this->accessToken)) {
             return $this->accessToken;
         }
     } else {
         $this->accessToken = null;
         Cache::delete($cacheKey);
     }
     //获取accessToken
     $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
     $response = Curl::get(sprintf($url, $this->appId, $this->appSecret));
     //返回格式 {"access_token":"ACCESS_TOKEN","expires_in":7200}
     //{"access_token":"43BKbLBjBnwH600H5TMSlx6AKT9TCZ3BRXjxvT0erRpzHTIaUuaJBDUoUykTqA","expires_in":7200}
     //每日调用超过次数,将提示
     //{"errcode":45009,"errmsg":"reach max api daily quota limit hint: [PuguNA0618vr22]"}
     $arr = Json::parseOrFail($response);
     $this->accessToken = $arr['access_token'];
     //默认时间是7200秒(120分钟)
     $expires = $arr['expires_in'] - 1200;
     if ($expires > 0) {
         Cache::set($cacheKey, $this->accessToken, $expires);
     }
     return $this->accessToken;
 }