您的位置:首页 > 移动开发 > 微信开发

微信小程序前端+后台php实现用户免登录

2020-02-01 18:17 811 查看

公司项目后续需要增加小程序前端,而公司项目用户使用时需要输入该项目用户的用户名与密码,用户每次使用都需要输入就非常不方便,所以通过小程序API接口取到用户唯一标识openid后可以与后台数据库中存储的批量openid进行对比查找,如果用户账号所对应的openid在数据库中则跳过登录界面直接使用。

目前只是写了一个demo:

小程序前端index.js通过wx.login获取登录凭证(code),然后通过RequestTask wx.request(Object object)发起 HTTPS 网络请求,向后台传输code,后台通过code去调用接口取到openid和session_key后返回给前端

[code]Page({
data: {

},
getOpenId: () => {
wx.login({
success: res => {
console.log(res.code)
wx.request({
url: 'http://127.0.0.1/test.php',
data: {
code: res.code
},

success: res => {
console.log(res.data)
}
})
}
})
}
})

后台test.php需要有对应小程序的appid和appsecret,这两个都是开发者id,即开发者申请小程序开发后就有的,同一开发者名下所有小程序要用的appid和appsecret都是这个。test.php通过$_GET[ ]得到前端传过来的code,利用这个code调用微信小程序的auth.code2Session接口换取使用该小程序用户对应的openid,请求地址是

[code]GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
[code]<?php

define("WX_APPID", "wx0230c92de862ad84");
define("WX_SECRET", "b10a359aa0576a947fc9e5e9085ee840");

$code = $_GET["code"];

function getWX ($code) {
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' .WX_APPID .'&secret=' . WX_SECRET . '&js_code='. $code .'&grant_type=authorization_code';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

$resp = getWX($code);
echo $resp;

?>

wx.login API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

wx.request API:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

auth.code2Session 服务端接口:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
subwaysamurai 发布了14 篇原创文章 · 获赞 0 · 访问量 1259 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: