项目中遇到的问题:1.前台为商品扫码数据埋点(二维码中的连接是外链,不是本身的后台),若是直接放外链的话,是统计不到数据的,因此须要先请求到本身后台,而后重定向外链。2. 二维码中连接若是太长,二维码的点会不少,手机扫码识别时间加长,须要设计短连接替换策略
引用qrcode-lite
包生成二维码html
import { toDataURL } from 'qrcode-lite' ... const longUrl = 'http://h5.m.taobao.com/app/smg/index.html?a=1&b=2&c=3...' this.shortUrl = this.getShortUrl(longUrl) // 由长连接获取短连接 const qrOption = { width: 200, margin: 1, quality: 0.3 } this.getQrcodeImgURL(this.shortUrl, qrOption).then(url => { this.qrcodeImg = url }).catch((err) => { console.log(`Create qrcode img failed, ${err}`) })
后台主要实现3个功能,生成短连接、长连接的缓存和取用、重定向前端
public function shortUrl(Request $request) { $url = $request->input('long_url'); if (!$url) { return response()->json([ 'code' => '-1', 'message' => 'The long_url is required!' ]); } $key = Carbon::now()->timestamp; // 以当前时间戳做为缓存的key $expiresAt = Carbon::now()->addDays(10); // 短连接的有效时间为10天 Cache::put($key, $url, $expiresAt); return response()->json([ 'code' => '0', 'message' => 'Success short the url', 'data' => $key ]); } public function redirect($shortCode) { $key = $shortCode; if (!$key) { return view("common.error", [ "errorTitle" => "扫码错误", "errorMessage" => "二维码错误,请跟管理员确认!"]); } $redirectUrl = Cache::get($key, 'expiration'); if ($redirectUrl == 'expiration') { return view("common.error", [ "errorTitle" => "扫码错误", "errorMessage" => "二维码过时,请从新生成二维码后再扫码!"]); } // 记录埋点数据 ... return redirect()->away($redirectUrl); }