微信小程序登录就是通过官方提供的登录能力快捷的获取用户身份标识,快速建立小程序内的用户体系。
最新登录流程大致为:
说明
- 调用 wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
- 调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key。
之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。
客户端(也就是小程序端获取到openid,通过openid可以获取到用户信息,再提交服务端进行保存)
1:代码片段
$appid = $appid; //小程序appid$secret = $secret; //小程序密钥$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";$res = httpRequest($url);$res = json_decode($res, true); //这里返回了openid session_keyreturn $res;
2:通过上面代码片段(1) 我们给小程序端传递了 openid session_key ,小程序端就可以获取到用户信息,然后你写个接口接收用户信息保存就好啦。
如果您觉得有用,浏览下微信小程序【成语闯关,24点数学口算】支持吧,想要源码案例可以咨询我们。
3:公共函数代码
function httpRequest($url, $data='', $method='GET'){$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_AUTOREFERER, 1); if($method=='POST'){curl_setopt($curl, CURLOPT_POST, 1); if ($data != ''){curl_setopt($curl, CURLOPT_POSTFIELDS, $data); }}curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result;}