最近开始从头开始做微信小程序的登录功能,项目使用的是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。