微信公众号带参二维码的生成以及后台Java的处理

1.生成带参二维码

有两种方式,一是通过微信公众平台来生成,二是通过java代码生成

一:微信平台生成

首先进入公众平台,找到接口权限进入

进入后找到获取access_tocken接口,获取access_tocken,因为获取ticket要有tocken才行

拿到token后根据官方文档选择所需要的二维码,是否是永久,来传入需要的参数

获取到ticket后直接在任意浏览器请求 

https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
提醒:TICKET记得进行UrlEncode

会得到一个二维码图片,保存后会得到一个showqrcode文件 用图片编辑器打开是一张二维码图

也可以选择直接保存二维码图片

2.Java后台生成

以下是Java生成代码

controller:

package com.szhz.controller;

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

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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.szhz.entity.WeiXinTicketEntity;
import com.szhz.framework.base.controller.BaseController;
import com.szhz.framework.util.HttpUtil;
import com.szhz.service.IWeiXinService;
/**
 * 生成带参二维码的ticket值
 * @author wyx
 *
 */
@SuppressWarnings("rawtypes")
@Controller
@RequestMapping("weixin/ticket")
public class WeiXinTicketController extends BaseController {
	
	@Autowired
	private IWeiXinService service;
	
	@Value("${weixin.ticket.action_name.QR_SCENE}")
    private String 	QRSCENE;
	@Value("${weixin.ticket.action_name.QR_STR_SCENE}")
    private String 	QR_STR_SCENE;
	
	@RequestMapping(value = "sendInterviewInvitation",method=RequestMethod.POST)
	public String sendInterviewInvitation(@RequestBody WeiXinTicketEntity reqDto) throws Exception{
		try {
			String accessToken = service.getAccessToken();
			int sceneId = reqDto.getSceneId();
			String result = new WeiXinTicketController().createForeverTicket(accessToken, sceneId);
			JSONObject jsonObject = JSONObject.parseObject(result);
			String ticket = null ;
			if(null!=jsonObject){
				ticket = jsonObject.getString("ticket");  
                System.out.println("创建永久带参二维码成功,ticket="+ticket);  
	        }    
			return success(ticket);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
	
	/**
	 * 创建临时带参数二维码 
	 * 获取灵石带参二维码ticket
	 * 
	 * @param accessToken
	 * @expireSeconds 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒。
	 * @param sceneId 场景Id
	 * @return
	 */
	public String createTempTicket(String accessToken, String expireSeconds, int sceneId) {
		Map<String, Integer> intMap = new HashMap<>();
		intMap.put("scene_id", sceneId);
		Map<String, Map<String, Integer>> mapMap = new HashMap<>();
		mapMap.put("scene", intMap);
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("expire_seconds", expireSeconds);
		paramsMap.put("action_name", QRSCENE);
		paramsMap.put("action_info", mapMap);
		String  jsonObject = JSONObject.toJSONString(paramsMap);
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
		String result = HttpUtil.sendPost(requestUrl, jsonObject);
		return result;
	 
	}
	 
	/**
	 * 创建永久二维码(数字)
	 * 
	 * @param accessToken
	 * @param sceneId
	 *            场景Id
	 * @return
	 */
	public String createForeverTicket(String accessToken, int sceneId) {
		Map<String, Integer> intMap = new HashMap<>();
		intMap.put("scene_id", sceneId);
		Map<String, Map<String, Integer>> mapMap = new HashMap<>();
		mapMap.put("scene", intMap);
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("action_name", QR_STR_SCENE);
		paramsMap.put("action_info", mapMap);
		String  jsonObject = JSONObject.toJSONString(paramsMap);
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
		String result = HttpUtil.sendPost(requestUrl, jsonObject);
		return result;
	}
	 
	/**
	 * 创建永久二维码(字符串)
	 * 
	 * @param accessToken
	 * @param sceneStr
	 *            场景str
	 * @return
	 */
	public String createForeverStrTicket(String accessToken, String sceneStr) {
		Map<String, String> intMap = new HashMap<>();
		intMap.put("scene_str", sceneStr);
		Map<String, Map<String, String>> mapMap = new HashMap<>();
		mapMap.put("scene", intMap);
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("action_name", QR_STR_SCENE);
		paramsMap.put("action_info", mapMap);
		String  jsonObject = JSONObject.toJSONString(paramsMap);
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
		String result = HttpUtil.sendPost(requestUrl, jsonObject);
		return result;
	}


}

entity:

package com.szhz.entity;

import lombok.Data;

/**
 * 
 * @author 
 *
 */
@Data
public class WeiXinTicketEntity {
	/*场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000)*/
	private int sceneId;
	/*该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒*/
	private String expireSeconds;
	/*场景值ID(字符串形式的ID),字符串类型,长度限制为1到64*/
	private String sceneStr;
}

yml:

#临时的整型参数值
weixin.ticket.action_name.QR_SCENE=QR_SCENE
#临时的字符串参数值
weixin.ticket.action_name.QR_STR_SCENE=QR_STR_SCENE
#永久的整型参数值
weixin.ticket.action_name.QR_LIMIT_SCENE=QR_LIMIT_SCENE
#永久的字符串参数值
weixin.ticket.action_name.QR_LIMIT_STR_SCENE=QR_LIMIT_STR_SCENE

然后前端调用接口传入参数{ 过期时间,场景值id或者字符串}获取到ticket值,

然后直接请求 window.location.href =" "

https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
提醒:TICKET记得进行UrlEncode

同样获取一张二维码图片

2.获取到二维码图片后处理用户关注公众号

一:在用户扫码关注后进入园区时,获取到关注者的个人信息,包括进入公众号的方式,以及扫码时场景值id或者字符串,

package com.szhz.controller;

import java.io.IOException;

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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.szhz.entity.BaseUrl;
import com.szhz.entity.WeiXinNoticerEntity;
import com.szhz.framework.base.controller.BaseController;
import com.szhz.service.IWeiXinNoticerService;
import com.szhz.service.IWeiXinService;
import com.szhz.service.impl.WeiXinServiceImpl;

/**
 * Titile 微信公众号-Controller层
 * 
 */
@SuppressWarnings("rawtypes")
@Controller
@RequestMapping("/wechat")
public class WeiXinController extends BaseController {
	
	// 第三方用户唯一凭证(从配置中心读取)
    @Value("${weixin.appid}")
    private String appid;

	// 注入主业务service
	@Autowired
	private IWeiXinService service;

	// 注入唯一身份service
	//@Autowired
	//private IIdentityService iIdentityService;

	// 注入关注者service
	@Autowired
	private IWeiXinNoticerService iWeiXinNoticerService;

	private String openId = "";

	// 第三方用户唯一凭证密钥,即appsecret(从配置中心读取)
	// private static String secret = "";

	/**
	 * 第一步:微信认证(让微信服务器调用,告诉微信服务器调用我们的服务器是合法的,放心回调)
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "auth", method = RequestMethod.GET)
	public String auth(HttpServletRequest request) {
		try {
			// 与接口配置信息中的Token要一致
			String token = "123";
			// 获取微信服务器传递的微信加密签名
			String signature = request.getParameter("signature");
			// 获取微信服务器传递的时间戳
			String timestamp = request.getParameter("timestamp");
			// 获取微信服务器传递的随机数
			String nonce = request.getParameter("nonce");
			// 获取微信服务器传递的随机字符串
			String echostr = request.getParameter("echostr");
			// 通过验证,原样返回echostr(微信服务器收到echostr后再次比对,比对一致后建立合作关系)
			if (signature != null && service.checkSignature(token, signature, timestamp, nonce)) {
				return echostr;
			}
		} catch (Exception e) {
			// 验证失败,返回空
			return "";
		}
		// 验证失败,返回空
		return "";
	}

	/**
	 * 微信菜单按钮点击时触发身份认证接口 重定向到 wechat/userInfo
	 * 
	 * @param returnUrl:认证完成后需要跳转到的前台页面
	 * @return
	 */
	@GetMapping("/authorize")
	public String authorize(@RequestParam("returnUrl") String returnUrl,
			@RequestParam("returnUrlPage") String returnUrlPage) {
		String getAuthUrl = "http://www.szhzsoft.com/" + "wechat/userInfo?returnUrlPage=" + returnUrlPage;

		// 需要跳转到认证的地址
		String redirectGetUserInfoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
				+ "&redirect_uri=" + getAuthUrl + "&response_type=code&scope=snsapi_base&state=" + returnUrl
				+ "#wechat_redirect";
		// System.out.println("我是returnUrl:[{}]" + redirectGetUserInfoUrl);
		return "redirect:" + redirectGetUserInfoUrl;
	}

	/**
	 * 微信认证接口回调时调用的接口
	 * 
	 * @param code
	 * @param returnUrl
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/userInfo")
	// @Transactional
	public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl,
			@RequestParam("returnUrlPage") String returnUrlPage) throws Exception {

		String baseReturnUrl = returnUrl + "/#/" + returnUrlPage;

		System.out.println("我是baseReturnURL:____" + baseReturnUrl);
		// 获取openid
		String openId = service.getOpenId(code);
		// 门户id
		String identityId = "";
		// 
		WeiXinNoticerEntity weiXinNoticerSearchEntity = new WeiXinNoticerEntity();
		weiXinNoticerSearchEntity.setOpenId(openId);
		
		WeiXinNoticerEntity weiXinNoticerEntity = (WeiXinNoticerEntity) iWeiXinNoticerService.getNoticerByOpenId(weiXinNoticerSearchEntity);// 通过openid查询用户是否已经关注过公众号,
		
		// 如果未关注写入到微信关注者表
		int qrScene =0;
		if (null==weiXinNoticerEntity) {
			String accessToken = service.getAccessToken();
			String noticerInfo = service.getNoticerInfo(accessToken, openId);// 获取个人信息
			JSONObject jsonObject = JSON.parseObject(noticerInfo);// 转为json对象
			String subscribeScene = jsonObject.getString("subscribe_scene");// 获取关注方式
			if(subscribeScene.equals("ADD_SCENE_QR_CODE")){ //如果用户是扫描二维码关注的拿到二维码场景值
				qrScene = jsonObject.getInteger("qr_scene");
			}else{
				
				qrScene = 1;
			}
			iWeiXinNoticerService.addNoticer(noticerInfo);
			//identityId = iIdentityService.addOpenId(openId);
		} else {
			qrScene=weiXinNoticerEntity.getQrScene();
		
		}

		System.out.println("最终回调rui:" + "redirect:" + baseReturnUrl + "?openid=" + identityId+"&qrScene="+qrScene);
		return "redirect:" + baseReturnUrl + "?openid=" + identityId+"&qrScene="+qrScene;
	}

	/**
	 * 点击页面菜单时,调用前台,前台回来调用此接口
	 *
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("getBaseOpenid")
	public BaseUrl getBaseOpenId(HttpServletResponse response) throws IOException {
		String url = service.getOpenIdUrl();
		BaseUrl baseUrl = new BaseUrl();
		baseUrl.setUrl(url);
		response.sendRedirect(url);
		baseUrl.setOpenId(openId);
		System.out.println("返回时的openId" + openId);
		return baseUrl;
	}

	
	
	
	/****************************************测试***************************************************/
	/**
	 * 测试获取TOKEN
	 * 
	 * @param reqDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getToken", method = RequestMethod.GET)
	public String getToken() throws Exception {
		try {
			return success(service.getAccessToken());
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 测试获取关注者信息
	 * 
	 * @param reqDto
	 * @param pageReqDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getNoticerInfo", method = RequestMethod.GET)
	public String getNoticerInfo() throws Exception {
		try {
			String accessToken = service.getAccessToken();
			String openId = "111";
			return success(service.getNoticerInfo(accessToken, openId));
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	public static void main(String args[]) {
		try {
			String str = new WeiXinServiceImpl().getNoticerInfo(
					"-222",
					"111");
			System.out.println(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

然后前端请求时再进行拦截,根据qrsence去请求不同的接口,获取不同的数据

本文主要就是实现一个公众号给多个企业使用,每个企业通过扫描不同的但是永久的二维码,进入不同的界面,获取到不同信息

 

 

 

 

 

 

 

 

 

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值