Java 微信公众号网页授权

写这篇文章之前简单说下,本人之前也没做过微信这方面的开发,也是属于第一次接触微信公众号开发,写下这篇博客也是为了记录自己的开发内容,也算是给微信公共号开发小白一些借鉴,不喜勿喷。好了 废话不多说 

首先登录微信公众号----点击左侧列表接口权限----网页服务----网页授权(网页授权获取用户基本信息)-----网页授权域名(这个域名一定是备案过的)

上面的操作完成之后


看一下微信网页授权的API 地址为https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN

仔细看下上面图片中的参数说明

https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=回调地址&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
这个回调的地址就是你的域名/项目名称/你的服务/方法
例如楼主的redirect_uri为http://域名/MountainTourism/wechat/getOpenid (切记这个上面一定要加http://  不能单独写域名 楼主在这吃亏了)
好了以上就是需要设置的地方,因为楼主的业务是需要网页授权之后返回openid,接下来直接上代码
WeChatController.java
/**
 * 
 */
package com.htht.tourism.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.htht.tourism.domain.Response;
import com.htht.tourism.domain.User;
import com.htht.tourism.domain.link.UserParam;
import com.htht.tourism.intf.TUserService;
import com.htht.tourism.utils.ValidatorResultHandler;
import com.htht.tourism.utils.WeixinHelper;

/**
 * @author wuqiwei
 *
 */
@Controller
@ResponseBody
@RequestMapping("/wechat")
public class WeChatController {
	@Resource
	private TUserService tUserService;
	/**
	 * 获取openid
	 * @author:wuqiwei
	 * @param @param param
	 * @param @param result
	 * @param @return
	 * @throws IOException 
	 * @throws ServletException 
	 * @date:2017年3月27日下午2:35:13
	 */
	@RequestMapping(value = "/getOpenid", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView model,final HttpServletRequest request,final HttpServletResponse response) throws ServletException, IOException {
		WxMpUser wxMpUser =  null;
		try {
			System.out.println(request.getParameter("code"));
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = WeixinHelper.getWxMpService().oauth2getAccessToken(request.getParameter("code"));
			wxMpUser =  WeixinHelper.getWxMpService().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//先判断wxMpUser是否为null
//		if (wxMpUser != null) {
////			request.getRequestDispatcher("index.jsp").forward(request,response); //请求转发
////			return Response.getInstance().success("1");
//		}
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("openid", wxMpUser.getOpenId());
		return mav;
	}
}
WeixinHelper.java
package com.htht.tourism.utils;

import java.util.HashMap;
import java.util.Map;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
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;

/**
 * WeixinHelper
 */
public final class WeixinHelper {
    private WeixinHelper() {
        throw new Error("工具类不能实例化!");
    }

//    private static final String CONFIG_URL = "application.properties";
    public static final String APPID = ConfigUtil.getProperty("WeChat","appid"); // appid
    public static final String APPSECRET =  ConfigUtil.getProperty("WeChat","appsecret"); // appsecret
    public static final String PATERNER_KEY =ConfigUtil.getProperty("WeChat","paternerKey"); // 商户支付密钥
    public static final String MCHI_ID = ConfigUtil.getProperty("WeChat","mch_id"); // 商户号
    public static final String NOTIFY_URL = ConfigUtil.getProperty("WeChat","notify_url");; // 回调地址
    public static final String TRADE_TYPE_JS = ConfigUtil.getProperty("WeChat","trade_type_js"); // 交易类型
    public static final String WEIXIN_OAUTH2 = ConfigUtil.getProperty("WeChat","WEIXIN_OAUTH2"); // 回调地址
    private static WxMpService wxMpService = null;

    /**
     * 获取WxMpService
     */
    public static WxMpService getWxMpService() {
        if (wxMpService == null) {
            WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
            config.setAppId(APPID); // 设置微信公众号的appid
            config.setSecret(APPSECRET); // 设置微信公众号的app corpSecret
            // config.setToken("..."); // 设置微信公众号的token
            // config.setAesKey("..."); // 设置微信公众号的EncodingAESKey
            config.setOauth2redirectUri(WEIXIN_OAUTH2);
            wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(config);
        }
        return wxMpService;
    }

    /**
     * getShortUrl
     */
    public static String getShortUrl(final String url) {
        String shortUrl = url;
        try {
            shortUrl = getWxMpService().shortUrl(url);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return shortUrl;
    }

    /**
     * getJsapiTicket
     */
    public static String getJsapiTicket() throws WxErrorException {
        return getWxMpService().getJsapiTicket();
    }

    /**
     * createJsapiSignature
     */
    public static WxJsapiSignature createJsapiSignature(final String url) throws WxErrorException {
        return getWxMpService().createJsapiSignature(url);
    }

    /**
     * getJSSDKPayInfo
     */
//    public Map<String, String> getJSSDKPayInfo(final String body, final String totalFee) throws Exception {
//        String outTradeNum = System.currentTimeMillis() + ""; // 商户订单号
//        Map<String, String> paramMap = new HashMap<String, String>();
//        paramMap.put("paternerKey", PATERNER_KEY); //
//        paramMap.put("mch_id", MCHI_ID); //
//        paramMap.put("body", body); // 商品描述
//        paramMap.put("out_trade_no", outTradeNum); // 商户端对应订单号
//        paramMap.put("total_fee", totalFee + "");
//        paramMap.put("spbill_create_ip", SystemHelper.getCurrentUserIp());
//        paramMap.put("notify_url", NOTIFY_URL);
//        paramMap.put("trade_type", TRADE_TYPE_JS);
//        Map<String, String> payInfo = WeixinHelper.getWxMpService().getJSSDKPayInfo(paramMap);
//        return payInfo;
//    }
}

这样就可以获取到openid了 返回到前台
以上就是网页授权获取openid的方法 由于是第一次写这种博客 写的不是很好 请见谅


### 实现Java环境中微信公众号OAuth2授权登录 #### 构造OAuth2授权URL 为了启动OAuth2授权过程,需先构建授权链接。这可以通过`WxMpOAuth2Service`对象来完成。 ```java // 获取服务实例并创建授权URL WxMpOAuth2Service wxMpOAuth2Service = wxService.getOAuth2Service(); String authorizationUrl = wxMpOAuth2Service.buildAuthorizationUrl( "https://example.com/callback", // 替换为实际回调地址 WxConsts.OAUTH2_SCOPE_BASE, // 或者使用 snsapi_userinfo 请求更多信息 "STATE"); // 可选状态参数用于保持请求前后状态一致[^1] ``` 此代码片段展示了如何利用`buildAuthorizationUrl()`函数生成带有必要查询参数的URL字符串,这些参数包括应用ID (`appid`)、重定向URI(`redirect_uri`)以及权限范围(`scope`)等。 #### 处理用户同意后的回调 当用户点击上述构造好的链接,并授予应用程序所需权限后,会跳转到指定的回调页面带上临时凭证`code`作为GET参数传递过来。此时服务器端应准备接收该请求并对之作出响应处理。 ```java @RequestMapping("/callback") public ResponseEntity<?> handleCallback(@RequestParam(value = "code") String code, @RequestParam(value = "state", required = false) String state){ if (code == null || code.isEmpty()) { return new ResponseEntity<>("Missing or invalid 'code' parameter.", HttpStatus.BAD_REQUEST); } try{ // 使用获得的code换取access_token String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=YOUR_APP_ID&secret=YOUR_SECRET_KEY&code=" + code + "&grant_type=authorization_code"; RestTemplate restTemplate = new RestTemplate(); Map<String, Object> result = restTemplate.getForObject(accessTokenUrl, Map.class); // 提取必要的信息如openid 和 access_token String openid = (String)result.get("openid"); String accessToken = (String)result.get("access_token"); // 进一步操作... System.out.println("User OpenId: "+openid+", Access Token:"+accessToken); return new ResponseEntity<>(result, HttpStatus.OK); }catch(Exception e){ return new ResponseEntity<>("Error processing callback request.", HttpStatus.INTERNAL_SERVER_ERROR); } } ``` 这段示例说明了怎样解析来自前端浏览器携带的`code`值,并向微信API发起HTTP GET请求以交换成永久性的`access_token`和用户的唯一标识符`openid`[^4]。 #### 存储与验证用户数据 一旦获得了有效的`access_token`及关联的`openid`,就可以将其保存至数据库或其他持久化存储机制中以便日后识别已认证过的访客身份。此外,在每次接收到新的访问时都应该重新校验令牌的有效性和合法性,从而保障系统的安全性[^5]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值