微信公众号推广分享二维码,关联扫码关注的客户

发布时间:2023-07-30 12:30

最近公司做活动推广公众号,公司下面有代理人,每个代理人都要有个独立的公众号推广码,让每个代理都去推广,用户扫描代理推广的二维码,关注公众号的同时,也清楚这个用户是扫描了哪个代理的推广二维码,

 

自己查了查,微信生成公众号推广码,可以携带一个场景值,我用 用户的id作为了一个场景值,

我是用了用户的id做了场景值

 

废话不多说,上代码

 

生成带场景值得公众号推广码

 

sprinboot 导入依赖 

我也搞忘了是哪个包下的,都导入吧

 
            com.github.binarywang
            weixin-java-mp
            2.9.0
        


  
            com.google.zxing
            core
            3.3.3
        
        
            com.google.zxing
            javase
            3.3.3
        

 

首先

application.properties文件里面 写入你的公众号配置

wechat.mpAppId=#
wechat.mpAppSecret=#
wechat.Token=# 

 

创建WechatAccountConfig  获取配置里面的值

package com.example.qidianchaoren.config;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix =\"wechat\")
public class WechatAccountConfig {
    private String mpAppId;

    private String mpAppSecret;

    private String Token;

    public String getMpAppId() {
        return mpAppId;
    }

    public void setMpAppId(String mpAppId) {
        this.mpAppId = mpAppId;
    }

    public String getMpAppSecret() {
        return mpAppSecret;
    }

    public void setMpAppSecret(String mpAppSecret) {
        this.mpAppSecret = mpAppSecret;
    }

    public String getToken() {
        return Token;
    }

    public void setToken(String token) {
        Token = token;
    }
}

 

创建WeChatMpConfig类 

 

package com.example.qidianchaoren.config;


import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class WeChatMpConfig {
    @Autowired
    WechatAccountConfig wechatAccountConfig;

    @Bean
    public WxMpService wxMpService(){
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage(){
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
        wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
        wxMpConfigStorage.setToken(wechatAccountConfig.getToken());

        return wxMpConfigStorage;
    }
}

上面 准备好了之后,准备开始操作了

 

代码生成二维码

    @GetMapping(\"/createTicket\")
    //1、生成带参数的二维码
    public String createTitcket(Model model) throws WxErrorException {
         //从sesssion当中获取当前登录的User用户
       User user= (User) request.getSession().getAttribute(\"sucessUser\");
        if(user!=null){
              //看看这个用户有没有推广二维码,没有就创建一个
            if(user.getWXcode()==null){
                //还没自己的专属二维码,生成一个
               //在这里我是用户的id生成的一个二维码
                String idReferrer=String.valueOf(user.getId());
      
                WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateLastTicket(idReferrer);//携带了场景值就是用户id
            
                String pictueUrl = wxMpService.getQrcodeService().qrCodePictureUrl(ticket.getTicket());
              
                String ppAdress= text(pictueUrl,idReferrer); //解析微信二维码,并生成新的带图片的二维码,并保存在本地

                model.addAttribute(\"pp\",ppAdress);
                user.setWXcode(ppAdress);  //保存用户生成的推广维码图片路径
                userService.updateUserName(user); //修改保存
             
                request.getSession().setAttribute(\"sucessUser\",user); //跟新session里面的数据
                return \"/Mypersonal/WxCode.html\";

            }else{
                //已经有了,就不需要生成,直接给图片路径
                model.addAttribute(\"pp\",user.getWXcode());
                return \"/Mypersonal/WxCode.html\";
            }

        }else{
            System.out.println(\"时间过期,或没有登录\");
            return null;
        }


    }

text里面的方法,解析图片  ,因为公众号原生二维码没有中间logo图片,我加了一个图片上去

后面会整理下代码,专门写个生成带图片的二维码

    public String text(String url,String id) throws WxErrorException {
        // 解析原先的二维码
    String u=null;
        try {
             u = QRCodeUtil.decodes(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //图片解析的------
        System.out.println(\"图片解析的------\");

        // 存放在二维码中的内容
        String text = u;
        // 嵌入二维码的图片路径
        String imgPath = \"C:/temp-rainy/奇点.jpg\";
        // 生成的二维码的路径及名称
        String destPath = \"C:/wxCode/\"+id+\".jpg\";
        //生成二维码
        try {
            QRCodeUtil.encode(text, imgPath, destPath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 解析二维码
//        String str = null;
//        try {
//            str = QRCodeUtil.decode(destPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 打印出解析出的内容
//        System.out.println(\"yijing图片解析的------\");
//        System.out.println(str);

        return \"/wxCode/\"+id+\".jpg\";
    }

 

 

创建QRCodeUtil 生成图片的工具类

package com.example.qidianchaoren.config;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.net.URL;
import java.util.Hashtable;



public class QRCodeUtil {


    private static final String CHARSET = \"utf-8\";
    private static final String FORMAT_NAME = \"JPG\";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;

    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || \"\".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println(\"\" + imgPath + \"   该文件不存在!\");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        // String file = new Random().nextInt(99999999)+\".jpg\";
        // ImageIO.write(image, FORMAT_NAME, new File(destPath+\"/\"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void encode(String content, String imgPath, String destPath) throws Exception {
        QRCodeUtil.encode(content, imgPath, destPath, false);
    }
    // 被注释的方法
    /*
     * public static void encode(String content, String destPath, boolean
     * needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,
     * needCompress); }
     */

    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false);
    }

    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }

    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }


    //调用了此方法解析
    public static String decodes(String imgUrl)  {
        String resultStr=\"\";
        try {
            URL url = new URL(imgUrl);
            BufferedImage image = ImageIO.read(url);
            if (image == null) {
                return null;
            }
            BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result;
            Hashtable hints = new Hashtable();
            hints.put(DecodeHintType.CHARACTER_SET, \"UTF-8\");
            result = new MultiFormatReader().decode(bitmap, hints);
            resultStr = result.getText();
        }catch (Exception e){
            e.printStackTrace();
        }

        return resultStr;
    }



    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }



}

 

带参数的二维码就生成了

 

后面就是,用户扫了码,微信会给你发回馈信息,接收就ok了

 

互相学习

 

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号