目录
准备:
开发者工具 | 配置好的小程序 | 后台语言:PHP
微信真的到处是坑,手册写的也不是很清楚,网上的填坑指南大多是把你推到另一个坑里,所以实际上还是一脚一个坑,掉进去就自己爬。
获取用户授权
用户授权其实简单来讲就是几步
①用户同意授权
②触发getuserinfo 获取code值
③后台获取解密用户信息
④缓存用户信息
Html
<button class='code' open-type='getUserInfo' bindgetuserinfo='getuserinfo'>授权登录</button>
授权窗口很快调整为不默认弹出授权申请,而是需要引导式的由用户点击触发
Js
getuserinfo: function (e) {
var that = this;
wx.login({
success: function (res) {
if (res.code) {
wx.getUserInfo({
withCredentials: true,
success: function (res_user) {
wx.request({
//后台接口地址
url: '你的地址',
data: {
code: res.code,
encryptedData: res_user.encryptedData,
iv: res_user.iv
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
wx.setStorageSync('openId', res.data.openId);
console.log(wx.getStorageSync('openId'))
}
})
}, fail: function () {},
complete: function (res) {}
})
}
}
})
},
PHP
include_once "php/wxBizDataCrypt.php";
$appid = '';
$secret = '';
$code = $_GET['code'];
$encryptedData = $_GET['encryptedData'];
$iv = $_GET['iv'];
$URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code&connect_redirect=1";
$apiData=file_get_contents($URL);
if(!isset($apiData['errcode'])){
$sessionKey = json_decode($apiData)->session_key;
$userifo = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $userifo->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
echo $data;
} else {
return false;
}
}
调用其他页面js
1.被调用的js页面要转化成小程序模板语言
module.exports = {
userLogin: userLogin //函数名
};
2.调用页面加载js
var openid = require('../../utils/openid.js');
3.调用函数
openid.userInfo(); //调用函数
Post提交
wx.request({
method: 'POST',
url: '上传地址',
header: { "content-type": "application/x-www-form-urlencoded" },
dataType: "json",
data: {
'name': NameVal,
'mobile': PhoneVal,
'code': YzmVal,
'rid': YqVal,
'openid' : openid,
'nickname' : nickname,
'headerUrl' : headerUrl
},
success: function (res) {
},
})
我遇到的坑是post请求,服务端接收不到数据
① 需要把Content-type改成‘application/x-www-form-urlencoded’才可以正常获取
②修改Content-type后,请求参数不会自动序列化,需要使用JSON.stringify转化字符串才可以正常请求