海豚精灵:https://www.whhtjl.com;优课GO:https://mgo.whhtjl.com
相信大家已在网上找了各种资料,也看过了各种文档,对于整个流程我就不再重复啦,有疑惑的小伙伴可以移步微信开放平台查看详情,网页地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
废话不多说,咱们先看效果图:
进入微信公众号搜索“优课GO”,点击左下角“优课GO”
点击“同意”后进入“个人中心”页,代表授权成功(也意味登陆成功),如下图所示:
接下来,我们重点看代码
我这里后端使用的SpringBoot,Maven项目,代码如下:
<!--公众号(包括订阅号和服务号) -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>2.7.0</version>
</dependency>
<!--微信支付 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>3.0.0</version>
</dependency>
在application.properties中配置相关信息
#微信公众号
wx.mp.appId=xxxxxxxxxxxxxx
wx.mp.appSecret=xxxxxxxxxxxxxxxxx
wx.mp.oauth2redirectUri=https://mgo.whhtjl.com/pages/tabbar/my
wx.mp.redirectURI=https://服务器域名/thirdPartLogin/jswx/login
创建实体类
package com.ltf.config;
import lombok.Data;
import lombok.EqualsAndHashCode;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 微信公众号商户基本信息
* @author xhz
*
*/
@Data
@EqualsAndHashCode(callSuper=true)
@Component
@ConfigurationProperties(prefix = "wx.mp")
public class YkgWxMpProperties extends WxMpDefaultConfigImpl{
private static final long serialVersionUID = 1L;
private String subscribeUri;
/**
* 静默授权回调地址
*/
private String oauth2RdmUri;
/**
* 公众号支付授权转发地址
*/
private String redirectURI;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
创建控制层
package com.ltf.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ltf.config.BaiduAppletProperties;
import com.ltf.config.SinaWebProperties;
import com.ltf.config.YkgWxAppletProperties;
import com.ltf.config.YkgWxMpProperties;
import com.ltf.dao.IWxPushKfMessage;
import com.ltf.entity.Course;
import com.ltf.entity.UserProfile;
import com.ltf.entity.WxPushKfMessage;
import com.ltf.service.CourseService;
import com.ltf.service.UserProfileService;
import com.ltf.utils.HttpClientUtil;
import com.ltf.utils.HttpRequestUtil;
import com.ltf.utils.StringUtils;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
/**
* 第三方登录控制层
* @author xhz
*
*/
@Controller
@RequestMapping("/thirdPartLogin")
public class ThirdPartLoginController extends BaseController {
private static final Logger logger = LoggerFactory
.getLogger(ThirdPartLoginController.class);
@Autowired
private WxMpService jsWxMpService;
@Autowired
private YkgWxMpProperties ykgMpProperties;
/**
* jswx 请求授权地址转发
* @param response
* @throws IOException
*/
@RequestMapping(path="/jswx/wxlogin", method=RequestMethod.GET)
@ResponseBody
public void wxRdLogin(HttpServletRequest request,HttpServletResponse response,
@RequestParam(name="state",required=false) String state,
@RequestParam(name="invitationCode",required=false) String invitationCode,
@RequestParam(name="icode",required=false) String icode)throws IOException {
String ivcode="";
if(!StringUtils.isEmpty(invitationCode)) {//兼容历史版本,后续考虑删除
ivcode=invitationCode;
}else {
ivcode=icode;
}
String redirectURI=jsWxMpService.getOAuth2Service().buildAuthorizationUrl(ykgMpProperties.getRedirectURI(),WxConsts.OAuth2Scope.SNSAPI_USERINFO,ivcode);
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect(redirectURI);
}
/**
* jswx 授权登陆回调地址
* @param request
* @param response
* @param code
* @return
*/
@RequestMapping(path="/jswx/login", method=RequestMethod.GET)
@ResponseBody
public JSONObject jsWxLogin(HttpServletRequest request,HttpServletResponse response,
@RequestParam("code") String code,
@RequestParam(name="state",required=false) String state) {
System.out.println("wxlogin state="+state);
Map<String,Object> map=new HashMap<String,Object>();
String invitationCode="";
int courseId=0;
String uid="";
if(StringUtils.isNotEmpty(state)&&state.startsWith("cid")&&state.contains(";")) {
String[] params=state.split(";");
if(params.length>1) {
String cid=params[0];
cid=cid.substring(3);
courseId=Integer.parseInt(cid);
invitationCode=params[1];
}
}else {
invitationCode=state;
}
String resRdUrl= ykgMpProperties.getOauth2redirectUri()+"?";
boolean subscribe=false;
String nickName="";
try {
WxMpOAuth2AccessToken oauth2AccessToken = jsWxMpService.getOAuth2Service().getAccessToken(code);
request.getSession().setAttribute("weixinOauth2AccessToken", oauth2AccessToken);//用于支付等安全校验
// 获取用户基本信息
String result=jsWxMpService.get("https://api.weixin.qq.com/cgi-bin/user/info?", "access_token="+oauth2AccessToken.getAccessToken()+"&openid="+oauth2AccessToken.getOpenId()+"&lang=zh_CN");
WxMpUser userInfo=JSONObject.parseObject(result, WxMpUser.class);
subscribe=userInfo.getSubscribe();
if(!subscribe) {
userInfo = jsWxMpService.getOAuth2Service().getUserInfo(oauth2AccessToken,"zh_CN");
}
UserProfile userProfile=new UserProfile();
userProfile.setNickName(StringUtils.filterEmoji(userInfo.getNickname()));
nickName=userProfile.getNickName();
userProfile.setGender(userInfo.getSex());
userProfile.setAvatar(userInfo.getHeadImgUrl());
userProfile.setOpenId(userInfo.getOpenId());
uid=userInfo.getOpenId();
userProfile.setUnionId(userInfo.getUnionId());
userProfile.setProfileType("WEIXIN_PUBLIC");
// userProfile.setSubscribe(subscribe);
map=userProfileService.queryDoUserThreeLogin(userProfile, invitationCode, request, response);
resRdUrl+=super.buildQuery(200, "登陆成功!", map);
} catch (WxErrorException e) {
e.printStackTrace();
resRdUrl+=super.buildQuery(500, "登录失败!"+e.getMessage(), map);
}catch (Exception e) {
e.printStackTrace();
resRdUrl+=super.buildQuery(500, "登录失败!"+e.getMessage(), map);
}
return null;
}
}
前端代码
window.location = getApp().globalData.BaseUrl + "/thirdPartLogin/jswx/wxlogin?icode=cid" + cid + ";" + ivcode;