微信生成二维码认证网页

一.引入相关jar

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>2.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>2.1</version>
</dependency>

二.编写相关接口

	/**
	   * 生成二维码
	   * @param request
	   * @param content 二维码的内容
	   * @return
	  * @throws UnsupportedEncodingException 
	   */
	  @RequestMapping("/barCodeUrl")
	  public void barCodeUrl(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		 String preSupId = request.getParameter("preSupId");
		 String userCode = request.getParameter("userCode"); 
		 int width = 300;
	     int height = 300;
	     Hashtable<EncodeHintType, Object> hints= new Hashtable<EncodeHintType, Object>();
	     hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	     BitMatrix bitMatrix;
	    
	     String wxUrl=smpGroupConfig.getWxUrl();//业务域名
	     String url = URLEncoder.encode(wxUrl+"/smpGroup/supplier/focusOnWeixin.to?preSupId="+preSupId+"&userCode="+userCode,"utf-8");//访问URL
	     String appid=smpGroupConfig.getCorpId();//服务号appid
	     String content ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";  
	     InputStream in = null;
	     OutputStream os = null;
	     try {
    	 	 bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
	    	 BufferedImage barcodeImg = MatrixToImageWriter.toBufferedImage(bitMatrix);
	         try {
	        	  in = this.getImageStream(barcodeImg);
	        	  byte[] data = new byte[2048];
	        	  int count = -1;
	        	  os = response.getOutputStream();
	        	  while((count = in.read(data,0,2048)) != -1)
	        		  os.write(data, 0, count);
	        	  os.flush();
	         } catch (Exception e) {
	        	 e.printStackTrace();
	         }
	     } catch (Exception e) {
	    	 e.printStackTrace();
	     }finally {
	    	 if(in!=null) try {in.close();} catch (Exception e) {}
	    	 if(os!=null) try {os.close();} catch (Exception e) {}
	     }
	  }
	  /**
	   * 从BufferedImage对象中获取InputStream对象
	   */
	  public InputStream getImageStream(BufferedImage bi) {
	   InputStream is = null;
	   ByteArrayOutputStream bs = new ByteArrayOutputStream(); 
	         ImageOutputStream imOut;  
	         try {
	             imOut = ImageIO.createImageOutputStream(bs);  
	             ImageIO.write(bi, "png",imOut);
	             is= new ByteArrayInputStream(bs.toByteArray());
	         } catch (Exception e) {
	             e.printStackTrace();  
	         }   
	         return is;
	  }
	  
	  /**
	   * 关注微信号
	   * @param request
	   * @return
	   */
	  @RequestMapping("focusOnWeixin")
	  public ModelAndView focusOnWeixin(HttpServletRequest request,HttpServletResponse response) throws Exception{
		  ModelAndView mav = new ModelAndView("/wechat/smpGroup/focusOnWeixin");
		  String preSupId = request.getParameter("preSupId");
		  String userCode = request.getParameter("userCode");
		  String openId = super.getOpenidByHttp(request, response);
		  System.out.println("---------->>preSupId:"+preSupId);
		  System.out.println("---------->>openId:"+openId);
		  if(StringUtils.isEmpty(openId)){
			  System.out.println("获取用户信息失败!");
			  mav = new  ModelAndView("/weixin/err");
			  mav.addObject("err", "获取用户信息失败!");
			  return mav;
		  }
		  String url = smpGroupConfig.getSmpGroupUrl() + "/wechat/Wechat!saveOpenIdToSupplier.action?openId="+openId+"&preSupId="+preSupId+"&userCode="+userCode;
		  String result = super.getAppData(request, url);
		  JSONObject json = JSONObject.fromString(result);
		  mav.addObject("rtn", json.getString("rtn"));
		  return mav;
	  }
	

三.结果

1)扫码

2)扫描结果

在.NET中调用微信小程序生成二维码并返回buffer,通常涉及到几个步骤:首先需要调用微信小程序提供的API来生成二维码,然后将返回的数据转换为buffer。以下是一个大致的流程介绍: 1. 首先,你需要有一个微信小程序,它提供了生成二维码的后端接口。 2. 在.NET应用程序中,通过HTTP客户端(如HttpClient)调用这个接口。通常,这涉及到构建一个HTTP请求,其中可能包含必要的参数,比如要生成二维码的唯一标识。 3. 发送请求后,微信小程序会根据请求处理并生成二维码图片,然后以二进制流(byte array)的形式返回。 4. 在.NET中接收到这个二进制流后,可以将其存储在一个buffer中,例如使用byte[]类型的变量来存储。 这里是一个简化的代码示例,展示如何在.NET中发送HTTP请求并接收返回的数据流: ```csharp using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public class WeChatMiniAppQRCodeGenerator { private readonly string _weChatMiniAppApiUrl; private readonly HttpClient _httpClient; public WeChatMiniAppQRCodeGenerator(string weChatMiniAppApiUrl) { _weChatMiniAppApiUrl = weChatMiniAppApiUrl; _httpClient = new HttpClient(); } public async Task<byte[]> GenerateQRCodeAsync(string uniqueId) { // 构建请求的URL,通常需要拼接API地址与必要的参数 string url = $"{_weChatMiniAppApiUrl}?id={uniqueId}"; try { // 发送HTTP GET请求 HttpResponseMessage response = await _httpClient.GetAsync(url); // 确保请求成功 if (response.IsSuccessStatusCode) { // 读取响应内容作为流 using (Stream contentStream = await response.Content.ReadAsStreamAsync(), memoryStream = new MemoryStream()) { // 将流的内容复制到内存中,即buffer await contentStream.CopyToAsync(memoryStream); return memoryStream.ToArray(); } } else { // 处理错误情况 throw new Exception($"Request failed with status code: {response.StatusCode}"); } } catch (HttpRequestException e) { // 异常处理 throw new Exception("Request exception occurred.", e); } } } ``` 使用时,你需要提供正确的微信小程序API URL,并且可能需要添加额外的请求头(如认证信息)等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值