微信小程序登录功能实现

2021/7/30 20:38:49

本文主要是介绍微信小程序登录功能实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最近开始从头开始做微信小程序的登录功能,项目使用的是uniapp功能。
1.使用uni.login Api,会返回一个code用于后端获取openid以及其他信息

doLogin() {
				uni.login({
					success(res) {
						uni.request({
							url: "url", //请求地址
							method: "POST",
							data: {
								code: res.code
							},
							success(res) {
								console.log(res);
							}
						})
					}
				})
			}

2.后台api接口

<?php

namespace App\Controller;

use Think\Controller;

class LoginController extends Controller
{
    
    public function doLogin()
    {
        $post = I('post.');
        $code = $post['code'];
        $find = M('login')->find();
        $appId = $find['appid'];
        $appSceret = $find['app_secret'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSceret&js_code=$code&grant_type=authorization_code";
        $info = json_decode($this->curl($url), true);
        var_dump($info);
        
        echo $info;
    }
    
    protected function curl($url, $data = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($data) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $info = curl_exec($ch);
        curl_close($ch);
        return $info;
    }
    
    
}

其中appid是你的appid,$appSceret是密钥。
注意,如果项目获取openid,必须需要在微信公众平台设置你的服务器域名,否则是没办法获取到你的openid。
在这里插入图片描述



这篇关于微信小程序登录功能实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程