<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;

/**
 * 首页接口
 */
class Qywx extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $corp_id = 'wwf7eea1c591713181';
    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public function getToken($ids=null)
    {
        $corp = Db::name('qywx_corp')->where('id',$ids)->find();
        if (!$corp) {
            $this->error('corp不存在');
        }
        if ($corp['msg_token_endtime'] < time()) {
            $url ='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$this->corp_id.'&corpsecret='.$corp['app_secret'];
            $res = json_decode(file_get_contents($url),true);
            if($res['errcode']==0){
                Db::name('qywx_corp')->where('id',$ids)->update(['msg_token'=>$res['access_token'],'msg_token_endtime'=>time() + 7100]);
                return $res['access_token'];
            }else{
                return false;
            }
        }
        return $corp['msg_token'];
    }
    public function sendmsg($corp_id,$app_id,$user,$content='')
    {
        if(!$app_id || !$user || !$corp_id || !$content){
            $this->error('参数错误');
        }
        $token = $this->getToken($corp_id);
        if (!$token) {
            $this->error('参数获取失败');
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$token;
        $data = [
            'touser' => $user,
            'msgtype'=>'text',
            'agentid'=>$app_id,
            'text' => ['content'=>$content]
        ];
        $res = \fast\Http::post($url,json_encode($data,true));
        
    }
    
    
    
    
}