开发代码 package com.wlpt.swpt.portal.common.wx;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pigx.common.core.util.R;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
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.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @program: swpt
* @description:
* @author: fq
* @create: 2020-03-25 11:55
**/
@RestController
@AllArgsConstructor
@RequestMapping("/wxauth" )
@Api(value = "wxauth", tags = "微信授权相关")
public class WXAuthorizationController {
/**
* 以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
*/
private static String SCOPE_TYPE_SNSAPI_BASE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";
/**
* 以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
*/
private static String SCOPE_TYPE_SNSAPI_USERINFO = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect";
/**
* appID
*/
private static final String APPID = "wx1f5a62dc0097bbcb";
/**
* appsecret
*/
private static final String APPSECRET = "bdbef8310434c70f2ff9e5b4f2ac7285";
/**
* redirect_uri
*/
private static String REDIRECT_URI = "http://iwjez2.natappfree.cc/ptportal/wxauth/wxGetCode";
/**
* state
*/
private static final String STATE = "123";
/**
* access_token
*/
private static String ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
/**
* 返回给前端获取微信code的Url
*/
@GetMapping("/wxGetCode")
public R wxGetCode(){
String encodeUrl = URLUtil.encode(REDIRECT_URI);
String codeUrl = String.format(SCOPE_TYPE_SNSAPI_BASE, APPID,encodeUrl,STATE);
return R.ok(codeUrl);
}
@GetMapping("/wxRedirectUri")
public void wxGetAccessTokenOrOpenId(@RequestParam String code,@RequestParam String state){
//String codeNew = "071tYiJd0nEmAv1h9YId0og3Jd0tYiJp";
String accessTokenUrl = String.format(ACCESS_TOKEN,APPID,APPSECRET,code);
RestTemplate restTemplate = new RestTemplate();
JSONObject jsonObject = restTemplate.getForObject(accessTokenUrl,String.class);
System.out.println(jsonObject);
}
public static void main(String[] args) {
new WXAuthorizationController().wxGetAccessTokenOrOpenId("xxx","ssss");
}
}
重点,授权回调页面域名 与 redirect_uri 的关系是,redirect_uri重定向的这个地址,只要在你填写的授权回调页面域名之下就行。
好了,测试代码调通了,后面就是优化代码了,调用微信授权其实不难,主要是要理清楚,对应的过程,相关的步骤,这样,开发起来,得心应手。