微信小程序
连接后台测试时一定要勾选:不校验合法域名,否则会报错
注意:开发工具中的appid设置要和开发管理网页中的appid一致
wxml:
<!-- open-type="getUserInfo"获取用户信息:bindgetuserinfo="getUser" 绑定用户信息回调函数 -->
<button open-type="getUserInfo" bindgetuserinfo="getUser" wx:if="{{button}}">微信登录</button>
<image src="{{userInfo.avatarUrl}}" class="userimage"></image>
<view>{{userInfo.nickName}}</view>
wxjs:
getUser:function(e){
//e是回调函数,e.detail.userInfo是用户信息
console.log(e.detail.userInfo);
let userImage = e.detail.userInfo.avatarUrl;
let usernaem = e.detail.userInfo.nickName;
this.setData({
userInfo:e.detail.userInfo,
button:false
})
wx.login({
success (res) {
if (res.code) {
//发起网络请求将获取到的code数据发送给后台
wx.request({
url: 'http://localhost:8080/user/code',
data: {
code: res.code
},
success:function(ret){
console.log(ret.data);
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
后台:使用OkHttpClient需要导包
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
Controller:
package com.wj.wx.Controller;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@org.springframework.stereotype.Controller
@RequestMapping("/user")
public class Controller {
@RequestMapping("/code")
@ResponseBody
public String code(String code) {
//从微信小程序中发送的数据
System.out.println(code);
String appid = "自己的appid";
String secret = "自己的secret";
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
OkHttpClient ohc = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response rp = ohc.newCall(request).execute();
if(rp.isSuccessful()) {
String body = rp.body().string();
//分割字符串拿到我们需要的数据
List<String> idList = Arrays.asList(body.split("\""));
System.out.println("session_key:"+idList.get(3)+"openid:"+idList.get(7));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "13441";
}
}
微信小程序的appid和secret的查看,后台的数据必须和这里的一样