123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace App\Helper;
- use App\Helper\UniPlatform\BaseAPI;
- use App\Helper\UniPlatform\BaseUniPlatform;
- use Carbon\Carbon;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\GuzzleException;
- /**
- * Class Kuaishou
- *
- * @package App\Helper
- * @property-read string $appId
- * @property-read string $slat
- * @property-read string $secret
- * @property-read string $token
- * @property-read string $accessTokenFile
- * @property-read string $accessToken
- * @property-read string $noticeUrl
- * @property-read string $validTimestamp
- */
- class Kuaishou extends BaseUniPlatform
- {
- public function __construct(BaseAPI $api)
- {
- $this->API = $api;
- }
- /**
- * @param string $code
- * @return array|mixed
- * @throws \Exception
- */
- public function login($code = ''): array
- {
- return $this->post($this->API::LOGIN, [
- 'app_id' => $this->appId,
- 'app_secret' => $this->secret,
- 'js_code' => $code,
- ]);
- }
- protected function createOrder($outOrderNo, $totalAmount): array
- {
- // TODO: Implement createOrder() method.
- }
- protected function getAccessToken(): string
- {
- $res = $this->post($this->API::ACCESS_TOKEN, [
- 'app_id' => $this->appId,
- 'app_secret' => $this->secret,
- 'grant_type' => 'client_credentials',
- ]);
- if (!isset($res['result']) || $res['result'] != 1) {
- throw new \Exception('获取access token 错误');
- }
- file_put_contents($this->accessTokenFile, json_encode([
- 'access_token' => $res['access_token'],
- 'expires_at' => Carbon::now()->timestamp + $res['expires_in']
- ]));
- return $res['access_token'];
- }
- protected function setAccessFileDir(): void
- {
- $this->accessTokenDir = storage_path('app/kuaishou');
- }
- protected function setAccessFilePath(): void
- {
- $this->accessTokenFile = storage_path('app/kuaishou/kuaishou_access_token.json');
- }
- /**
- * @param string $uri
- * @param array $data
- * @return array
- * @throws \Exception
- */
- protected function post($uri = '', $data = []): array
- {
- try {
- $client = new Client();
- $url = $uri.'?'.http_build_query($data);
- $res = $client->post($url, [
- 'verify' => false,
- 'headers' => ['Content-Type' => 'x-www-form-urlencoded'],
- ]);
- $stringBody = (string)$res->getBody();
- $res = json_decode($stringBody, true);
- if(!isset($res['result']) || $res['result'] != 1){
- throw new \Exception("请求快手API接口错误,错误码:{$res['result']},错误信息:{$res['error_msg']}");
- }
- return $res;
- } catch (GuzzleException $e) {
- \Log::error($e->getMessage());
- throw new \Exception($e->getMessage());
- }
- }
- }
|