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

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


需求场景

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

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

技术实现分析

重点代码如下:

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']
          }



相关文章
|
16天前
|
传感器 小程序 搜索推荐
(源码)java开发的一套(智慧校园系统源码、电子班牌、原生小程序开发)多端展示:web端、saas端、家长端、教师端
通过电子班牌设备和智慧校园数据平台的统一管理,在电子班牌上,班牌展示、学生上课刷卡考勤、考勤状况汇总展示,课表展示,考场管理,请假管理,成绩查询,考试优秀标兵展示、校园通知展示,班级文化各片展示等多种化展示。
40 0
(源码)java开发的一套(智慧校园系统源码、电子班牌、原生小程序开发)多端展示:web端、saas端、家长端、教师端
|
1天前
|
小程序 Java 关系型数据库
基于Java微信小程序智能招聘平台设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序智能招聘平台设计和实现(源码+LW+调试文档+讲解等)
21 11
|
1天前
|
小程序
微信小程序没有后台切换如何解决
微信小程序没有后台切换如何解决
|
1天前
|
小程序 Java 关系型数据库
基于Java微信小程序同城家政服务系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序同城家政服务系统设计和实现(源码+LW+调试文档+讲解等)
|
1天前
|
小程序 安全 Java
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序民宿短租系统设计和实现(源码+LW+调试文档+讲解等)
|
3天前
|
小程序 JavaScript Java
基于Java微信小程序火锅店点餐系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序火锅店点餐系统设计和实现(源码+LW+调试文档+讲解等)
|
14天前
|
存储 小程序 前端开发
java毕设项目|宿舍管理系统小程序设计与实现
java毕设项目|宿舍管理系统小程序设计与实现
|
18天前
|
缓存 前端开发 JavaScript
前端性能优化:从加载到渲染的全方位探索
【6月更文挑战第11天】本文探讨了前端性能优化,重点关注加载速度和渲染效率。压缩与优化资源文件、利用CDN、异步加载和懒加载可提升加载速度。减少DOM操作、合理利用CSS和JavaScript、优化JavaScript执行效率以及利用浏览器缓存能提高渲染效率。通过综合运用这些策略,可提升用户体验。
|
1天前
|
小程序 Java 关系型数据库
基于Java微信小程序自驾游拼团设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序自驾游拼团设计和实现(源码+LW+调试文档+讲解等)
|
1天前
|
小程序 JavaScript Java
基于Java微信小程序校园自助打印系统设计和实现(源码+LW+调试文档+讲解等)
基于Java微信小程序校园自助打印系统设计和实现(源码+LW+调试文档+讲解等)