java后台restTemplate生成二小程序维码,前端渲染

简介: java后台restTemplate生成二小程序维码,前端渲染

需求场景


用户A登录小程序,在我的页面,点击推荐新客户,需要生成小程序二维码携带用户A的id;


用户B扫描上面的二维码,即可进入小程序,根据是否注册过,将用户B和用户A的id建立推荐关系。


技术实现分析


1dc618a0ed9580ce8bfa6facb208c08f.png


重点代码如下:


java后台restTemplate生成二小程序维码


@RequestMapping("/getQrCode")
    @ResponseBody
    public String getAppQrCode(@RequestParam(name="recomReferorId") String recomReferorId, HttpServletResponse response) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 设置代理,因为我们公司访问外网需要代理,所以设置代理,如果没有这个要求,就不用设置
        restTemplate.setRequestFactory(requestFactory);
        // 获取token
        String token = businessWxService.getAccessToken();
        // 配置参数
        Map<String, Object> param = new HashMap<>(5);
        param.put("scene", "clientId="+recomReferorId);
        param.put("page", "pages/index/index");
        param.put("width", 247);
        param.put("is_hyaline", true);
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, JSON.toJSONString(param), byte[].class);
        byte[] result = responseEntity.getBody();
        String s = Base64.getEncoder().encodeToString(result);
        return s;
    }


前端渲染


生成二维码页js


// 获取小程序码(接口)
  getQrCode() {
    app.func.reqGet('/static/wx/getQrCode', {
      recomReferorId: wx.getStorageSync('userInfo').wechatId
    }, res => {
      if (res.result === 'SUCCEED') {
        this.setData({
          qrcode: `data:image/PNG;base64,${res.data}`
        })
      }
    })
  },


二维码页面


<view class="share-container">
  <view class="qrcode">
    <image src="{{qrcode}}" mode="widthFix"></image>
  </view>
  <button class="btn" type="primary" open-type="share">立即分享</button>
</view>


app.js


//app.js
import { TOKENISSURE } from "./config/config";
var http = require('http.js')
App({
  globalData: {
    token: null,
    userInfo: null,
    hasUserInfo: false,
    userInfo1: null,
    lotteryTitle: null,
    recomReferorId: '',
    firstLoginPage: ''
  },
  onLaunch(options) {
    console.log(options, 'options-----------------')
    this.globalData.firstLoginPage = options.path
    try {
      this.globalData.token = wx.getStorageSync('token')
      this.globalData.userInfo = wx.getStorageSync('userInfo')
      if (this.globalData.token) {
        this.globalData.hasUserInfo = true
        // 每次进入小程序需要调一下,后台记录使用
        this.getCurrentPageUrl()
      } else {
        if(options.scene === 1047) {
          // 扫小程序码进入
          let queryStr = options.query.scene
          if (queryStr) {
            let query = {}
            decodeURIComponent(queryStr).split('&').forEach(item => {
              let arr = item.split('=')
              query[arr[0]] = arr[1]
            })
            this.globalData.recomReferorId = query['clientId']
          }
        } else {
          // 没登陆跳转登陆页面
          if (options.query.clientId) {
            // 存在邀请 clientId
            this.globalData.recomReferorId = options.query.clientId
          }
        }
        wx.navigateTo({ url: '/pages/login/index' })
      }
    } catch (e) {
      console.log(e)
    }
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  // 获取当页面url地址
  getCurrentPageUrl: function () {
    wx.showLoading({
      title: '数据加载...',
      mask: true,
    })
    let data = {
      clientId: wx.getStorageSync('userInfo').wechatId,
      enterPageUrl: `/${this.globalData.firstLoginPage}`,
      enterPageDecri: '飞碟汽车天文馆',
      providerType: 1,
    }
    wx.request({
      url: http.rootUrl + '/business_enter_record/add?sign=1&timestamp=' + Date.parse(new Date()),
      data: data,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'X-Request-Id': new Date().getTime(),
        'X-Token-Issuer': TOKENISSURE,
        Authorization: wx.getStorageSync('token'),
      },
      success: function (res) {
        if (res.data.result == 'SUCCEED') {
          wx.hideLoading()
          return typeof cb == 'function' && cb(res.data)
        } else {
          wx.hideLoading()
          return typeof cb == 'function' && cb(false)
        }
      },
      fail: function () {
        wx.hideLoading()
        return typeof cb == 'function' && cb(false)
      },
    })
  },
  GetUserToken: function () {
    return new Promise((resolve) => {
      //console.log("this.globalData.userInfo.userId", this.globalData.userInfo.userId)
      wx.request({
        url: 'https://nms.wuzheng.com.cn/common/xcx/getToken',
        method: 'GET',
        data: {
          userId:wx.getStorageSync('userInfo').wechatId,
        },
        success: (res) => {
          //console.log("2", res);
          this.globalData.token = res.data.data
          return resolve(res.data.data)
        },
        fail: function (res) {
          return res
        },
      })
    })
  },
  GetSystemInfo: function () {
    return new Promise((resolve) => {
      wx.request({
        url: 'https://nms.wuzheng.com.cn/common/xcx/systemInfo',
        method: 'GET',
        success: (res) => {
          this.globalData.lotteryTitle = res.data.data.lotteryTitle
          wx.setStorage({
            key: 'programNotice',
            data: res.data.data.programNotice,
            success: function () {
              return resolve(res.data.data)
            },
          })
        },
      })
    })
  },
  // 这里配置我们需要的方法
  func: {
    reqGet: http.reqGet,
    reqPost: http.reqPost,
    postQuery: http.postQuery,
    formatRichText: http.formatRichText,
  },
})

关键代码:


if(options.scene === 1047) {
          // 扫小程序码进入
          let queryStr = options.query.scene
          if (queryStr) {
            let query = {}
            decodeURIComponent(queryStr).split('&').forEach(item => {
              let arr = item.split('=')
              query[arr[0]] = arr[1]
            })
            this.globalData.recomReferorId = query['clientId']
          }


效果如下:


66ba272a0bfc97be54a5fa679e3d5482.png



相关文章
|
11天前
|
小程序 Java 关系型数据库
基于Java微信小程序智能招聘平台设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序智能招聘平台设计和实现(源码+LW+调试文档+讲解等)
27 11
|
11天前
|
小程序 Java 关系型数据库
基于Java微信小程序同城家政服务系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序同城家政服务系统设计和实现(源码+LW+调试文档+讲解等)
|
11天前
|
小程序 Java 关系型数据库
基于Java微信小程序小说阅读系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序小说阅读系统设计和实现(源码+LW+调试文档+讲解等)
|
24天前
|
前端开发 JavaScript Java
计算机Java项目|基于Web的足球青训俱乐部管理后台系统的设计与开发
计算机Java项目|基于Web的足球青训俱乐部管理后台系统的设计与开发
|
7天前
|
SQL XML JavaScript
【若依Java】15分钟玩转若依二次开发,新手小白半小时实现前后端分离项目,springboot+vue3+Element Plus+vite实现Java项目和管理后台网站功能
摘要: 本文档详细介绍了如何使用若依框架快速搭建一个基于SpringBoot和Vue3的前后端分离的Java管理后台。教程涵盖了技术点、准备工作、启动项目、自动生成代码、数据库配置、菜单管理、代码下载和导入、自定义主题样式、代码生成、启动Vue3项目、修改代码、以及对代码进行自定义和扩展,例如单表和主子表的代码生成、树形表的实现、商品列表和分类列表的改造等。整个过程详细地指导了如何从下载项目到配置数据库,再到生成Java和Vue3代码,最后实现前后端的运行和功能定制。此外,还提供了关于软件安装、环境变量配置和代码自动生成的注意事项。
|
11天前
|
小程序 安全 Java
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
|
13天前
|
小程序 JavaScript Java
基于Java微信小程序火锅店点餐系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序火锅店点餐系统设计和实现(源码+LW+调试文档+讲解等)
|
24天前
|
存储 小程序 前端开发
java毕设项目|宿舍管理系统小程序设计与实现
java毕设项目|宿舍管理系统小程序设计与实现
|
4天前
|
小程序 前端开发
【微信小程序-原生开发】实用教程22 - 绘制图表(引入 echarts,含图表的懒加载-获取到数据后再渲染图表,多图表加载等技巧)
【微信小程序-原生开发】实用教程22 - 绘制图表(引入 echarts,含图表的懒加载-获取到数据后再渲染图表,多图表加载等技巧)
17 0
|
8天前
|
XML 小程序 Java
java小程序代码详细展示
java小程序代码详细展示