本文详解抖音小程序一键获取手机号的完整实现路径。前端通过特定组件触发授权并获取加密数据,后端利用PHP调用接口换取session_key,最终结合AES-128-CBC算法解密出用户真实手机号,确保数据交互的安全性与准确性。
前端授权组件实现
在前端开发环节,主要依赖特定的UI组件来触发用户的授权流程。

<button
v-if="!isFromOrderList"
class="get-phone-btn"
open-type="getPhoneNumber"
@getphonenumber="onGetPhoneNumber"
>
一键获取
</button>// 获取手机号回调
onGetPhoneNumber(e) {
var that = this
tt.login({
force: true,
success(res) {
console.log('获取手机号回调', e)
if (e.detail.errMsg === 'getPhoneNumber:ok') {
// 获取成功,调用后端接口解密手机号
that.decryptPhoneNumber(res.code,e.detail.iv,e.detail.encryptedData)
} else {
uni.showToast({
title: '获取手机号失败',
icon: 'none'
})
}
},
fail(res) {
console.log(`login 调用失败`);
},
});
},
// 解密手机号 后端PHP进行解密
async decryptPhoneNumber(code,iv,encryptedData) {
try {
const res = await orderApi.decryptPhone({
code: code,
iv: iv,
encryptedData: encryptedData
})
if (res.code === 1 && res.data && res.data.phone) {
this.phone = res.data.phone
} else {
throw new Error(res.msg || '获取手机号失败')
}
} catch (error) {
console.error('解密手机号失败:', error)
uni.showToast({
title: error.message || '获取手机号失败',
icon: 'none'
})
}
}后端PHP解密流程
后端逻辑基于PHP语言构建,核心处理流程分为两步:首先利用前端提交的code参数向服务器请求换取session_key,随后使用该session_key对前端传来的手机号加密数据进行解密操作。
/**
* 获取抖音小程序手机号
* @param $code
* @param $iv
* @param $encryptedData
* @return \think\response\Json
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function get_mobile($code, $iv, $encryptedData)
{
$result = $this->code2Session($code);
//解密
$phone = openssl_decrypt(base64_decode($encryptedData, true), 'AES-128-CBC', base64_decode($result['session_key']), OPENSSL_RAW_DATA, base64_decode($iv));
$phone = json_decode($phone, 1);
if (isset($phone['phoneNumber']) && $phone['phoneNumber']) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'phone' => $phone['phoneNumber']
],
]);
} else {
return json([
'code' => 0,
'msg' => '获取失败',
'data' => [
],
]);
}
}
/**
* 通过code换取 session_key
* @param $code
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function code2Session($code)
{
$uri = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
$options = [
'body' => json_encode([
'appid' => config('xinghuo_mp.appid'),
'secret' => config('xinghuo_mp.appsecret'),
'code' => $code,
'anonymous_code' => ''
]),
'headers' => [
'Content-Type' => 'application/json'
]
];
$response = (new \GuzzleHttp\Client)->post($uri, $options);
$stringBody = (string)$response->getBody();
$result = json_decode($stringBody, true);
return ['openid' => $result['data']['openid'], 'session_key' => $result['data']['session_key']];
}上述内容涵盖了抖音小程序中一键获取手机号功能的主要实现逻辑。如需了解更多信息,可查阅本站过往文章或继续浏览后续相关内容,感谢大家的支持。