前端uniapp+后端thinkphp实现小程序获取手机号码的代码

知识技术 2022-04-25 17:01 1016
转载请务必注明: 来源:《建站管家》https://www.df81.com/news/307.html

uniapp前端代码如下:

<template>
	<view>
		<view class="flex justify-center align-center margin-logo-login"><image class="logo-size-au" src="../../static/logo.jpeg"></image></view>
		
		<button class="dlbutton" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"><text>手机号一键登录</text></button>
		
		<!-- <view class="padding-others-login flex justify-center align-center"><view>其他手机号登陆</view></view> -->
	</view>
</template>
 
<script>
let that;
export default {
	data() {
		return {
			code: ''
		};
	},
	onLoad() {
		that = this;
		uni.login({
			success: function(res) {
				that.code = res.code;
			}
		});
	},
	methods: {
		getPhoneNumber: function(e) {
			if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
				uni.navigateTo({
					url: '../tabbar/index/index'
				});
			} else {
				that.miniRegisterOrLogin(e.detail.encryptedData,e.detail.iv);
			}
		},
		async miniRegisterOrLogin(encryptedData,iv) {
			this.loading = true;
			let res = await this.$api.miniRegisterOrLogin({ code: that.code,encryptedData:encryptedData,iv:iv });
			this.loading = false;
			uni.setStorageSync('userId', res.data.data.userId);
			uni.setStorageSync('nick', res.data.data.nick);
			uni.setStorageSync('headimg', res.data.data.headimg);
			uni.reLaunch({
				url:'../tabbar/index/index'
			})
		},
	}
};
</script>
 
<style>
.dlbutton {
	color: #ffffff;
	font-size: 34upx;
	width: 87.567vw;
	height: 12.015vw;
	background: rgba(251, 103, 48, 1);
	box-shadow: 0upx 0upx 13upx 0upx rgba(164, 217, 228, 0.2);
	border-radius: 50upx;
	line-height: 100upx;
	text-align: center;
	margin-left: auto;
	margin-right: auto;
	margin-top: 18vw;
}
.padding-others-login {
	padding: 3vw 4vw;
}
.logo-size-au {
	width: 30vw;
	height: 30vw;
	border-radius: 5vw;
}
.margin-logo-login {
	margin-top: 15vw;
}
</style>


后端thinkphp代码如下:

<?php
namespace app\apis\controller;
 
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;
use think\Validate;
use Txsms\SmsSingleSender;
use Txsms\SmsSenderUtil;
use think\Cookie;
use app\common\model\UserCoupons as UserCouponsModel;
use app\common\model\UserYaoQing as UserYaoQingModel;
use app\common\model\User as UserModel;
include_once "wxBizDataCrypt.php";
 
/**
 * swagger: 用户&&商家相关
 */
class MiniUser extends Base
{
    public $user = 'user';
 
    public function sql()
    {
        $q= input('q');
        $res= db('user')->query($q);
        dump($res);
    }
 
 
    /**
     * post: 用户&&商家注册或登陆
     * path: register
     * method: register
     * param: phone - {string}  手机号
     * param: type - {int} 1为用户 2为商家
     * param: friend_id - {int}  用户id  分享是传入
     */
    public function registerOrLogin()
    {
 
        $type = input('type');
        $wxCode = input('code');
 
        $encryptedData = input('encryptedData');
        $iv = input('iv');
 
        $appid = 'wxcd35e514f4b305ba';
        $appsecret = '5a5aeafd46d487933f765f3c9f95bb9d';
 
        $oauth2Url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$wxCode."&grant_type=authorization_code";
        $result = file_get_contents($oauth2Url);
        $obj = json_decode($result);
        $session_key = $obj->session_key;
        $openid = $obj->openid;
        $unionid = $obj->unionid;
 
 
        $pc = new wxBizDataCrypt($appid, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
 
        if ($errCode == 0) {
            $numDatas = json_decode($data);
            $phone = $numDatas->phoneNumber;
 
            $userinfo = $this->is_register($phone);
 
            if (! $userinfo){
                // 在db插入新用户
                $data = [
                    'name' => 'U' . $phone.$type,
                    'nick' => 'U' . substr($phone, -4),
                    'headimg' => '/uploads/default/head.png',
                    'phone' => $phone,
                    'addtime' => date("Y-m-d H:i:s"),
                    'type' => $type,
                    'openid' => $openid
                ];
                $res = db($this->user)->insertGetId($data);
 
                if ($res){
 
                    $returnData = [
                        'userId' => $userinfo['id'],
                        'nick' => $userinfo['nick'],
                        'headimg' => 'https://www.df81.com/'.$userinfo['headimg'],
                    ];
 
                    $this->result($returnData, 1, '');
                }
 
            }else{
                $returnData = [
                    'userId' => $userinfo['id'],
                    'nick' => $userinfo['nick'],
                    'headimg' => 'url'.$userinfo['headimg'],
                ];
 
                $this->result($returnData, 1, '');
            }
 
        } else {
            print($errCode . "\n");
        }
 
    }
 
    /**
     * post: 手机号查询用户信息
     * path: is_register
     * method: is_register
     * param: phone - {string} 手机号
     */
    public function is_register($phone)
    {
        if (!$phone || !is_phone($phone)) {
            $this->result('', 0, '请输入正确格式的手机号码');
        }
 
        $find = db($this->user)->where('phone', $phone)->find();
 
        return $find;
    }
 
    //https请求(支持GET和POST)
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        //https
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
 
 
}

点赞 (0)

收藏 (0)

本站部分信息来源网络,如有侵权,请联系QQ:1062129401删除。

上一篇: 《建站管家》二次开发文档

下一篇: pip install django安装失败的解决办法

请先登录后,再发表评论 ~ ~
发表评论
发表评论
发表帖子
广告位招租( ¥5 / 天 )
点击咨询
相关帖子

如果要判断文件是否存在,用函数 is_file(),如果要判断目录是否存在,用函数 is_dir()
用宝塔安装TP程序后,网站前台可以访问,后台无法访问,不是程序问题,而是web服务器环境配置问题(PHP配置),出现这种问题,一般是windows主机安装宝塔造成的,linux安装宝塔不会出现此错误
广告位招租( ¥3 / 天 )
点击咨询
广告位招租( ¥2 / 天 )
点击咨询
广告位招租( ¥1 / 天 )
点击咨询
最新帖子

小朋友,你爸爸是谁啊?这很单纯的,就像我们碰到别人会问:你吃过饭了吗?类似;许多人初次相识,经常会问:你是做什么的啊?你做什么,好像决定你收入的高低,你,资产的范围
1、升级框架到ThinkPHP8.0.3【要求PHP8.1+环境,推荐PHP8.1】 2、启用/禁用调试模式等小细节改进
后台点击生成站点地图 一直转圈圈没有反应,
在线客服