token = $token; } $this->appid = env('wechat.appid'); $this->appsecret = env('wechat.appsecret'); $this->redis = new \Redis(); $this->redis->connect('127.0.0.1', 6379); } public function wechatChekToken($signature, $timestamp, $nonce): bool { $data = array($this->token, $timestamp, $nonce); sort($data, SORT_STRING); $str = sha1(implode($data)); if ($str == $signature) { return true; } return false; } /** * 获取accessToken * @return mixed|\Redis|string * @throws FuncException */ public function getAccessToken(): string { $access_token = $this->redis->get('wechat_access_token'); if ($access_token) { return $access_token; } $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}"; $http = new Http(); $res = $http::get($url); if ($res['code'] != 200) { throw new FuncException($res['msg']); } $data = json_decode($res['data'], true); if (isset($data['errcode']) && $data['errcode'] != 0) { throw new FuncException($data['errmsg']); } $this->redis->set('wechat_access_token', $data['access_token'], 7200); return $data['access_token']; } /** * * @param $url * @return array * @throws FuncException */ public function getJsSdkSignature($url): array { $timestamp = time(); $nonceStr = generate_random_string(16); $jsapi_ticket = $this->getJsApiTicket(); $str = "jsapi_ticket={$jsapi_ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}"; $signature = sha1($str); return [ 'appId' => env('wechat.appid'), 'timestamp' => $timestamp, 'nonceStr' => $nonceStr, 'signature' => $signature ]; } /** * * @throws FuncException */ protected function getJsApiTicket() { $access_token = $this->getAccessToken(); $ticket = $this->redis->get('wechat_js_api'); if ($ticket) { return $ticket; } $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=jsapi'; $res = Http::get($url); if ($res['code'] != 200) { throw new FuncException($res['msg']); } $data = json_decode($res['data'], true); if (isset($data['errcode']) && $data['errcode'] != 0) { throw new FuncException($data['errmsg']); } $this->redis->set('wechat_js_api', $data['ticket'], 7200); return $data['ticket']; } }