【微信授权】极其简单的实现方法

强烈推荐使用一个工具包,在maven的中心仓库中搜索"weixin-java"就可以搜索到,感谢这位大佬的作品,大大简化了微信端开发的难度。

接下来是一个简单例子,是我在我的实际项目中抽取出来的一部分,项目使用的是springboot框架,但是无论使用什么框架微信授权的步骤和原理是一样的。

这个例子是微信公众号授权的例子。

代码如下:

package cn.smileyan.boot.main.controler;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smileyan.boot.main.entity.User;
import cn.smileyan.boot.main.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Controller
@Slf4j
@RequestMapping("/login")
@CrossOrigin
public class LoginControler {
	@Autowired
	private UserService userService;
	
	@Value("${wechat.appid}")
	private String appid;
	@Value("${wechat.appsecret}")
	private String appsecret;
	
	@Value("${wechat.login_url}")
	private String login_url;				// 授权网址
   
	@Value("${wechat.success_login_url}")
	private String success_login_url;		// 登录成功后返回的网页
	
	private WxMpService wxMpService;
	/**
	 * 提示用户点击同意,授权登录
	 * @return
	 */
	@GetMapping("/welcome")
	public String  welcome() {
		// 1.根据appid和appsecret和回调地址配置微信授权
            WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
            wxMpConfigStorage.setAppId(appid);
            wxMpConfigStorage.setSecret(appsecret);
            wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
            // 完成配置后进行跳转
	    String oauth2buildAuthorizationUrl = wxMpService.oauth2buildAuthorizationUrl(login_url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,  null);
	    System.out.println(oauth2buildAuthorizationUrl);
	    return "redirect:" + oauth2buildAuthorizationUrl;
	}
	/**
	 * 通过code拿到数据openid
	 * @param code
	 * @param returnUrl
	 * @return 进行网站跳转
	 */
	@GetMapping("/login")
	public String login(@RequestParam("code") String code,
            @RequestParam("state") String returnUrl,HttpServletRequest request,HttpServletResponse response) {
		System.out.println("code=="+code);
		// 2.根据code换取AccessToken
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
            try {
                wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            } catch (WxErrorException e) {
        	e.printStackTrace();
            }
        
            // 3.进一步获取用户信息
            String openId = wxMpOAuth2AccessToken.getOpenId();
            System.out.println("openid="+openId);
            // 拿到用户的基本信息
            WxMpUser wxMpUser=null; 
            try {
        	wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		} catch (WxErrorException e) {
	        	e.printStackTrace();
	    }
       
            // 后面的内容根据需要编写,微信授权到此已经结束了。
            // 判断这个用户是否已经注册
            User user=newFromWechat(wxMpUser);
            User loginedUser = userService.registerOrLogin(user);
    
            String url_add = "user_id="+loginedUser.getUser_id()+"&portrait_url="+loginedUser.getPortrait_url();

            return "redirect:" + success_login_url+"?"+url_add;
	}
	

}

基本步骤也是非常简单的,核心配置类WxMpInMemoryConfigStorage,在这个类的对象中设置appid和appsecret,然后设置一下回调地址,然后就是微信授权了。

注意需要在公众号中配置回调地址的域名。

注意如果已经引入httpclient,需要删除httpclient,解决与weixin-java-mp的冲突问题。


    org.apache.httpcomponents
    httpclient
    4.1.1

另外如果微信授权过程中牵扯到 跨域问题。可以参考我的另外一个博客,地址如下:https://blog.csdn.net/smileyan9/article/details/82467910

你可能感兴趣的:(我的大后端,我的微信开发)