Article Directory
Demand scenario
User A logs in to the mini program and clicks on my page to recommend a new customer. The mini program QR code needs to be generated to carry user A’s id;
user B scans the QR code above to enter the mini program. The ids of user B and user A establish a recommendation relationship.
Technical realization analysis
The key code is as follows:
Java background restTemplate generates two small program dimension codes
@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;
}
Front-end rendering
Generate QR code page 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}`
})
}
})
},
QR code page
<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×tamp=' + 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,
},
})
Key code:
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']
}
The effect is as follows:
Finish