php 抖音授权登陆

前端:

<view class="form weapp">
    <button v-if="page.agree" open-type="getPhoneNumber" @getphonenumber="ttLogin" class="btn"
        :class="{ disabled: !page.agree, 'ttprefix': page.mode== 'tt' }">
        <text>授权登录</text>
    </button>
    <view v-else class="btn" @click="validateChecked" :class="{ disabled: !page.agree }">
        <text class="text">授权登录</text>
    </view>
</view>

onLoad(({
    type
}) => {
    // #ifdef  MP-TOUTIAO
    page.can_switch = true
    page.mode = 'tt'
    douyinLogin() // 进入就请求抖音login
    // #endif

});

const douyinLogin = () => {
    return new Promise(function(reslove, reject) {
        tt.login({
            success(res) {
                if (res.code && res.anonymousCode) {
                    reslove(res);
                    page.ttcode = res.code
                    page.anonymousCode = res.anonymousCode
                } else {
                    reject('登录失败!' + res.errMsg)
                }
            },
            fail(res) {
                console.log(`login 调用失败`);
            },
        })
    })
}

// 按钮发起请求
// 抖音登陆
const ttLogin = (e) => {
    const account = tt.getEnvInfoSync()
    const appid = account.microapp.appId // 获取appid
    const {
        iv,
        encryptedData
    } = e.detail;
    const code = page.ttcode;
    const anonymous_code = page.anonymousCode;
    if (code) {
        passport.ttlogin({
            appid,
            code
            anonymous_code,
            iv,
            encryptedData
        }).then(({
            data,
            err,
            msg
        }) => {
            if (err === 0) {
                const {
                    token,
                    user
                } = data;
                auth.login(token, {
                    ...user
                });

                uni.showToast({
                    title: "登录成功"
                });

                setTimeout(() => {
                  
                    handleBack();
                }, 1500)


            } else {
                uni.showToast({
                    title: msg,
                    icon: "none"
                });
            }
        });
    } else {
        uni.showModal({
            title: "提示",
            content: "拒绝授权将无法登陆小程序!",
            showCancel: false,
        });
    }
    // ttcheckSession()
}

后端:

/**
     * @notes:抖音授权登陆
     * @return \think\response\Json
     * User: Administrator
     * Author:timeAxis
     * @date: 
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function ttlogin()
    {
        $rules = [
            'appid'     => 'require',
            'code'      => 'require',
            'anonymous_code'    => 'require',
            'source'    => 'string',
            'inviter'    => 'string',
            'iv'        => 'require',
            'encryptedData'      => 'require'
        ];

        $this->validate(request()->param(), $rules);

        $params = request()->only(array_keys($rules));

        $thirdmobile = ThirdPlatformUser::getmobile($params['appid'], $params['code'], $params['anonymous_code']);

        // 解密获取手机号
        $encryptedData = base64_decode($params['encryptedData'],true);
        $sessionKey = base64_decode($thirdmobile['data']['session_key']);
        $iv = base64_decode($params['iv']);
        $output = openssl_decrypt($encryptedData, 'AES-128-CBC',$sessionKey, 1,$iv);

        $output = json_decode($output, true);

        $mobile = $output['phoneNumber'];

        $user = User::where([
            'mobile' => $mobile,
        ])->find();

        if(!$user){
            $lastFourDigits = substr($mobile, -4);
            $user = new User;
            $user->user_id  = User::genID();
            $user->username = $user->user_id;
            $user->mobile   = $mobile;
            $user->nickname = '昵称'.$lastFourDigits;
            $user->save();
        }

        $return = User::login_return($user);

        return success($return);

    }

// 获取抖音授权凭证
public static function getmobile($appid, $code,$anonymous_code= null)
{
	$instance = App::instance([
		'app_id' => $appid,
	]);
	$resultparams = [
         'appid'      => $instance->app_id,
         'secret'     => $instance->secret,
         'code'       => $code,
         'anonymous_code' => $anonymous_code
     ];
     
    $resultstr = json_encode($resultparams);

    $url = "https://developer.toutiao.com/api/apps/v2/jscode2session"; // 地址
//            $url = "https://open-sandbox.douyin.com/api/apps/v2/jscode2session"; // 测试
    $client = new Client;

    $resp = $client->post($url, [
        'body' => $resultstr
    ]);

    $body = $resp->getBody()->getContents();

    $return = json_decode($body, true);

    if ($return['err_no']) {
        throw new \Exception("抖音授权失败: ".$return['errmsg']);
    }
    return $return;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间轴-小文同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值