转摘自:https://blog.csdn.net/gahoyeung/article/details/94593695
公司项目后续需要增加小程序前端,而公司项目用户使用时需要输入该项目用户的用户名与密码,用户每次使用都需要输入就非常不方便,所以通过小程序API接口取到用户唯一标识openid后可以与后台数据库中存储的批量openid进行对比查找,如果用户账号所对应的openid在数据库中则跳过登录界面直接使用。
目前只是写了一个demo:
小程序前端index.js通过wx.login获取登录凭证(code),然后通过RequestTask wx.request(Object object)发起 HTTPS 网络请求,向后台传输code,后台通过code去调用接口取到openid和session_key后返回给前端
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,请求地址是
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_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