1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?php
- namespace app\api\controller;
- use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Dingtalk;
- use \Exception;
- use AlibabaCloud\Tea\Exception\TeaError;
- use AlibabaCloud\Tea\Utils\Utils;
- use Darabonba\OpenApi\Models\Config;
- use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Models\GetAccessTokenRequest;
- use think\cache\driver\Redis;
- class Dingtoken extends Base
- {
- /**
- * 使用 Token 初始化账号Client
- * @return Dingtalk Client
- */
- public static function createClient(){
- $config = new Config([]);
- $config->protocol = "https";
- $config->regionId = "central";
- return new Dingtalk($config);
- }
- /**
- * 获取企业内部应用的accessToken
- **/
- public function main()
- {
- $options = \think\Config::get('redis');
- $redis = new Redis($options);
- $key = 'dingtalk_access_token';
- $access_token_data = $redis->get($key);
- if ($access_token_data) {
- return json_decode($access_token_data, true);
- }
- $client = self::createClient();
- $getAccessTokenRequest = new GetAccessTokenRequest([
- "appKey" => "dingekepwoyycxfbtyvg",
- "appSecret" => "EjM9WohvKHo3eNqZGGbQHhbjM80QzapdC_f_reYiOCyEFOtaG1qoG2KzEfpSoLWe"
- ]);
- try {
- $res = $client->getAccessToken($getAccessTokenRequest);
- }
- catch (Exception $err) {
- if (!($err instanceof TeaError)) {
- $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
- }
- if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
- // err 中含有 code 和 message 属性,可帮助开发定位问题
- }
- }
- if($res->body){
- $data = [
- 'accessToken'=>$res->body->accessToken,
- 'expireIn'=>$res->body->expireIn,
- ];
- $redis->set($key, json_encode($data), 7000);
- return $data;
- }
- }
- }
|