<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Cache;
use think\Db;

class Douyin extends Model
{
    protected static $config = [];
    
    
    public static function getSet(){
        
        if(empty(self::$config)){
            $config  = Db::name("platform")->where("id",UNIACID)->value("douyin");
            $config = iunserializer($config);
            if(empty($config)){
                $config = [
                    'AppId'=>'ttaf88d93531ef1d7201',
                    'AppSecret'=>'dca91c8b10daf9a2bf15e43d1536f79a6d69bf47',
                    'rsaPrivateKey'=>'',
                ];
            }

            self::$config = $config;
        }
        else{
            $config = self::$config;
        }
        
        return $config;
    }
    
    public static function login($code){
        $config = self::getSet();
        
        if(empty($code)){
            return __json(0,'code错误');
        }
        
        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        $data = [
            'appid'=>$config['AppId'],
            'secret'=>$config['AppSecret'],
            'code'=>$code,
        ];
        $result = ihttp_post($url,json_encode($data),['Content-Type: application/json']);
        $result = json_decode($result['content'],true);
        if($result['err_no'] !== 0){
            return __json(0,'登录失败:'.$result['err_tips']);
        }
        
        return __json(1,"登录成功",$result['data']);
    }

    public static function getPhoneNumber($code){
        $config = self::getSet();
        $result = self::getAccessToken();
        if($result['code'] != 1){
            return $result;
        }
        $access_token = $result['data']['access_token'];
        
        if(empty($code)){
            return __json(0,'code错误');
        }
        
        $url = "https://open.douyin.com/api/apps/v1/get_phonenumber_info/";
        
        $data = ["code"=>$code];
        
        $data = urldecode(json_encode($data)); 
        
        $result = ihttp_post($url,$data,['Content-Type: application/json','access-token:'.$access_token]);
        $result = json_decode($result['content'],true);
        if(empty($result)){
            return __json(0,'接口错误');
        }
        else{
            if($result['err_no'] === 0){

                $encryptData  = $result['data'];

                $dyapp_rsaPrivateKey = $config['rsaPrivateKey'];

                $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($dyapp_rsaPrivateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
                
                openssl_private_decrypt(base64_decode($encryptData), $decryptedData, $privateKey, OPENSSL_PKCS1_PADDING);
                
                $phoneInfo = json_decode($decryptedData, true);

                return __json(1,"操作成功",$phoneInfo['purePhoneNumber']);
            }
            else{
                return __json(0,$result['err_msg']);
            }
        }
    }

    public static function getAccessToken(){
        
        $config = self::getSet();
        
        $appid = $config['AppId'];
        $secret = $config['AppSecret'];
        
        if(empty($appid) || empty($secret)){
            return __json(0,"缺少参数appid或秘钥");
        }
        
        $access_token_key = "dyapp_access_token_".$appid;
        $access_token_expires_time_key = "dyapp_access_token_expires_time_".$appid;
        
        $access_token = Cache::get("{$access_token_key}");
        
        if(!empty($access_token)){
            $access_token_expires_time = (int)Cache::get("{$access_token_expires_time_key}");
            if($access_token_expires_time > time()){
                return __json(1,"操作成功",$access_token);
            }
        }
        $data = [
            'client_key'=>$appid,
            'client_secret'=>$secret,
            'grant_type'=>'client_credential'
        ];
        $result = ihttp_post("https://open.douyin.com/oauth/client_token/",json_encode($data),['Content-Type: application/json']);
        
        $result = json_decode($result['content'],true);
        
        if($result['data']['access_token']){
            
            Cache::set("{$access_token_key}",$result['data']['access_token']);
            Cache::set("{$access_token_expires_time_key}",$result['data']['expires_in'] + time());
            
            return __json(1,"操作成功",$result['data']['access_token']);
        }
        else{
            return __json(0,"获取AccessToken失败",$result['data']);
        }
    }
}