微信小程序中获取微信公众号授权获得公众号的openId(此方式仅适用于短时间的活动,长期项目还是需要维护基础表)

准备工作:小程序和公众号需要绑定在同一开放平台下(这样会有unionid,用来验证是否为同一用户);公众号设置好白名单,网页授权域名(这个要和小程序的api访问域名一致)

步骤:1.准备一个跳转的html页面,放在用网页授权域名可以访问到的地址




    
    公众号信息网页授权
    
    
    





           2.写一个接收code获取openid的接口

/**
	* 公众号授权回调,获取用户信息
	* @param code
	* @param state
	* @param req
	* @throws
	* @return void
	*/
	@GetMapping("/savewxopenid")
	public void savewxopenid(String code, String state, HttpServletRequest req) throws Exception {
		String errMsg = "";
		//根据code获取token和openId
		System.out.println("code:"+code+",state:"+state);
		String url = WechatUtilsMP.getAccessTokenRequest(code);
		String result = HttpClientUtil.doGet(url);
		System.out.println("获取网页授权token:"+result);
		logger.info("获取网页授权token:"+result);
		if(StringUtil.isStringEmpty(result)){
			logger.error("获取网页授权token出错:"+result);
			return;
		}
		JSONObject resultJson = JSONObject.fromObject(result);
		String openId = "";
		String unionid = "";
		int subscribe = 0;
		if(resultJson.containsKey("openid")){
			openId = resultJson.getString("openid");
		}
		if(StringUtil.isStringEmpty(openId)){
			logger.error("获取openid出错:"+result);
			return;
		}
		//根据openid获取unionid
		String token = WechatUtilsMP.getAccessTokenRequest();
		String unionUrl = WechatUtilsMP.getUnionIdRequest(openId,token);
		String unionResult = HttpClientUtil.doGet(unionUrl);
		System.out.println("unionResult:"+unionResult);
		JSONObject unionResultJson = JSONObject.fromObject(unionResult);
		if(unionResultJson.containsKey("unionid")){
			unionid = unionResultJson.getString("unionid");
		}
		if(unionResultJson.containsKey("subscribe")){
			subscribe = unionResultJson.getInt("subscribe");
		}
		if(!StringUtil.isStringEmpty(unionid)){
			Member member = memberService.getMemberByUnionid(unionid);
			if(member != null){
				member.setWxOpenId(openId);
				member.setIsFocus((short)subscribe);
				memberService.modifyMember(member);
			}
		}
	}

           3.小程序中新增一个web-view页面,url放html的地址

            



你可能感兴趣的:(微信小程序,微信,小程序)