uniapp微信小程序,使用fastadmin完成一个一键获取微信手机号的功能

前端部分

点击按钮,获取手机号

html 复制代码
<button open-type="getPhoneNumber" @getphonenumber="bindGetPhoneNumber" hover-class="none"
						class="btn-purity">一键获取</button>

传入openid和code

javascript 复制代码
			bindGetPhoneNumber(e) {
				var that = this;
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					uni.showModal({
						title: '温馨提示',
						content: '您已拒绝授权,无法获取手机号!',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.$emit("getContract", {});
								uni.navigateBack();
								// uni.switchTab({
								// 	url: "/pages/home/index/index"
								// })
							}
						}
					});
					return;
				} else {
					var json = {
						openid: this.userInfo.openid,
					};
					let version = uni.getSystemInfoSync().SDKVersion;
						// json['encryptedData'] = e.detail.encryptedData;
						// json['iv'] = e.detail.iv;
						json['code'] = e.detail.code;
						
						
					this.$api.user.getPhone(json).then(res => {
						console.log(7777123, res)
						if (res !== false) {
							this.phoneNumber = res.data.mobile
						}
					});

				}
			},

后台部分

初始化EasyWechat的核心类

javascript 复制代码
    private $app;
    public $payment;

    public function __construct()
    {
        $config = get_addon_config('lineup');
            Log::write('[ Log LIST ++++++++++$config ] ' . json_encode($config, JSON_UNESCAPED_UNICODE), 'debug');
        $options = [
            'app_id'      => $config['app_id'],
            'secret'      =>  $config['app_secret'],
            'response_type' => 'array',
        ];

        $payment_config = [
            // 必要配置
            'app_id'             => $config['app_id'] ?? '',
            'mch_id'             => $config['mch_id'] ?? '',
            'key'                => $config['mch_key'] ?? '',   // API 密钥
            // 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '', // XXX: 绝对路径!!!!
            'key_path'           => '',      // XXX: 绝对路径!!!!
            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
        ];

        try {
            $this->app = Factory::miniProgram($options);
            $this->payment = Factory::payment($payment_config);
        } catch (\Exception $e) {
            \think\Log::error('初始化失败:' . $e->getMessage());
        }
    }
    /**
     * 根据 jsCode 获取用户 session 信息
     */
    public function jscode2session($code)
    {
        return $this->app->auth->session($code);
    }

    /**
     * 获取手机号
     * @param $code
     */
    public function getPhoneNumber($code){
        $token = $this->app->access_token->getToken();

        try {
            $data = Http::post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token['access_token'],json_encode(['code'=>$code]));
            $data = json_decode($data,true);
            if($data['errcode'] != '0'){
                throw new Exception("获取手机号失败");
            }
        }catch (ErrorException $exception){
            throw $exception;
        }


        return $data['phone_info'];
    }

    /**
     * 微信小程序消息解密
     */
    public function decryptData($session, $iv, $encryptedData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptedData);
    }

解析出手机号

javascript 复制代码
    public function decryptPhoneNumber($post)
    {
        $wxmini = new \app\common\library\lineup\Wxmini();
        //新版本授权
        try {
            if(!empty($post['code'])){
                $return = $wxmini->getPhoneNumber($post['code']);
            }else if($post['iv'] && $post['encryptedData']){
                $return = $wxmini->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
            }else{
                throw new Exception("参数错误");
            }
        }catch (Exception | ErrorException $e){
            return [
                'status' => false,
                'info'   => $e->getMessage(),
                'data' => [],
            ];
        }
        return [
            'status' => true,
            'data' => [
                'mobile' => isset($return['phoneNumber']) ? $return['phoneNumber'] : '',
            ],
        ];
    }
相关推荐
2501_9160088910 小时前
全面介绍Fiddler、Wireshark、HttpWatch、SmartSniff和firebug抓包工具功能与使用
android·ios·小程序·https·uni-app·iphone·webview
webYin10 小时前
解决 Uni-App 运行到微信小程序时 “Socket合法域名校验出错” 问题
微信小程序·小程序·uni-app
说私域21 小时前
日本零售精髓赋能下 链动2+1模式驱动新零售本质回归与发展格局研究
人工智能·小程序·数据挖掘·回归·流量运营·零售·私域运营
程序媛徐师姐21 小时前
Java基于微信小程序的模拟考试系统,附源码+文档说明
java·微信小程序·java模拟考试系统小程序·模拟考试微信小程序·模拟考试系统小程序·模拟考试小程序·java模拟考试小程序
大尚来也21 小时前
微信小程序开发费用全解析:从SaaS到定制的多元选择
微信小程序
奔跑的web.21 小时前
UniApp 路由导航守
前端·javascript·uni-app
如果你好1 天前
UniApp 路由导航守卫
前端·微信小程序
特立独行的猫a1 天前
主要跨端开发框架对比:Flutter、RN、KMP、Uniapp、Cordova,谁是未来主流?
flutter·uni-app·uniapp·rn·kmp·kuikly
大尚来也1 天前
小程序怎么开发自己的小程序
微信小程序
码云数智-园园1 天前
小程序开发平台有哪些?小程序第三方开发平台评测对比
微信小程序