微信公众号登录授权

海豚精灵https://www.whhtjl.com优课GOhttps://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;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信公众号网页授权登录是指在微信公众号中,用户点击菜单或链接后,通过授权登录获取用户信息的过程。根据微信公众号官方文档,在开发微信公众号的网页时,需要仔细观看文档中关于网页授权回调域名的说明、网页授权的两种scope的区别说明以及关于网页授权access_token和普通access_token的区别等内容。 微信公众号的网页授权登录主要分为以下几个步骤: 1. 用户点击菜单或链接后,进入微信公众号网页授权登录页面。 2. 用户在该页面中进行授权操作,微信公众号会跳转到授权回调域名中的指定页面,并携带授权的code参数。 3. 开发者可以根据获取的code参数,调用微信接口获取用户的access_token和openid等信息。 4. 开发者可以使用获取的用户信息进行业务逻辑的操作,例如展示个人中心、发送消息等。 需要注意的是,在开发过程中,需要配置微信公众号后台的路径和授权回调域名等信息,以确保页面的正确展示和接口的正常调用。 与小程序相比,微信公众号更加侧重于营销,而小程序则更像是一个微型的APP程序,用于和用户进行交互。 总结起来,微信公众号网页授权登录是通过微信公众号中的授权机制,获取用户信息并进行业务操作的过程。开发者需要仔细阅读微信公众号官方文档,了解网页授权的相关操作和配置要求,以确保功能的正常运行。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [微信公众号网页授权登录](https://blog.csdn.net/qq_41971087/article/details/82593830)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [uni-app微信公众号(1)——网页授权登录](https://blog.csdn.net/qq_40601005/article/details/121028141)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值