您的位置:首页 > 移动开发 > 微信开发

小程序生成带二维码的分享海报(后端PHP)

2019-06-05 10:32 701 查看

小程序wxml页面

<canvas class='mycanvas' style="" canvas-id="myCanvas"></canvas>

<!-- <view class='ft'>保存图片到手机相册,分享到朋友圈</view> -->
<view class='operation' style="">
<image bindtap='savetup' class="icon" src="/pages/images/down.png"></image>
<image open-type="share" class="icon" src="/pages/images/share.png"></image>
</view>

小程序wxss页面

.mycanvas{
margin:0 auto;
margin-top:30px;
margin-bottom:30px;
width: 310px;
height: 490px;
border:1px solid #ddd;
box-shadow:0px 0px 10px 5px #D8D7DD;

}
.ft{
text-align: center;
}
.icon{
width: 110rpx;
height: 110rpx;
}
.operation{
display: flex;
justify-content: space-around;
padding:10px
}

小程序js页面

/**
* 页面的初始数据
*/
data: {
id: '',
housetitle: '',
houseaddress: '',
houseprice: '',
qrcode: '',
houseimg: '',
codesrc: ''
},

/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
var that = this;
that.setData({
id: 13608,
})
//1. 请求后端API生成小程序码
wx.request({
url: 'xxxxxxxxxx',
data: {
id: that.data.id
},
success: function(data) {
var houseinfo = data.data;
var imgurl = houseinfo.fyxx.url;
var title = houseinfo.fyxx.fytitle;
var address = houseinfo.fyxx.district + " | " + houseinfo.fyxx.rooms + " room | " + houseinfo.fyxx.site;
if (title.length > 45){
var title = houseinfo.fyxx.fytitle.substring(0,42)+"...";
}
if (address.length > 45) {
var address = address.substring(0, 42)+"...";
}
console.log(houseinfo)

that.setData({
housetitle: title,
houseaddress: address,
houseprice: houseinfo.fyxx.price,
});

var arr3 = houseinfo.url;
var imgurl2 = arr3[0];

//2. canvas绘制文字和图片
const ctx = wx.createCanvasContext('myCanvas');
var imgPath = 'xxxxxxxxxx' + imgurl2;
var bgImgPath = '../images/wifi.jpg';
// var basicprofile = '../images/房子 (3)@2x.png';

wx.downloadFile({
url: imgPath, //二维码路径
success: function(res) {
if (res.statusCode === 200) {
that.setData({
houseimg: res.tempFilePath
});
}
wx.request({
url: 'xxxxxxxxxx/index',
data: {
id: that.data.id
},
method: 'POST',
success: function(data) {
that.setData({
qrcode: data.data
});

wx.downloadFile({
url: that.data.qrcode, //二维码路径
success: function(res) {
if (res.statusCode === 200) {
that.setData({
codesrc: res.tempFilePath
});
}

//填充背景
ctx.setFillStyle('#ffffff');
ctx.fillRect(0, 0, 310, 490);

//绘制房子图片
ctx.drawImage(that.data.houseimg, 0, 0, 310, 260);

//绘制标题
ctx.setFontSize(13);
ctx.setFillStyle('#000000');
ctx.fillText(that.data.housetitle, 10, 285);

//绘制房子地址
ctx.setFontSize(13);
ctx.setFillStyle('#6F6F6F');
ctx.fillText(that.data.houseaddress, 10, 310);

//绘制房子价格
const metrics = ctx.measureText(that.data.houseprice); //测量文本信息
ctx.stroke();
ctx.rect(10, 328, metrics.width + 30, 25);
ctx.setFillStyle('rgba(20,136,204,1)');
ctx.fill();
ctx.setFillStyle('#FFFFFF');
ctx.fillText('¥'+ that.data.houseprice, 15, 345);

//房源浏览量
ctx.setFillStyle('#6F6F6F');
ctx.fillText('1000+  views', 215, 345)

//绘制一条虚线
ctx.strokeStyle = 'blue';
ctx.beginPath();
ctx.setLineWidth(1);
ctx.setLineDash([2, 4]);
ctx.moveTo(10, 365);
ctx.lineTo(300, 365);
ctx.stroke();

//绘制介绍
ctx.setFontSize(12.5);
ctx.setFillStyle('#aaaaaa');
ctx.fillText('Long click scan code for details', 10, 414);
ctx.fillText('Share SmartHousing applet', 10, 443);
ctx.drawImage(that.data.codesrc, 205, 382, 90, 90);
ctx.draw();

}
})
}
})
}
})

}
});
},

/**
* 多行文字处理,每行显示数量
* @param text 为传入的文本
* @param num  为单行显示的字节长度
*/
textByteLength(text, num) {
let strLength = 0; // text byte length
let rows = 1;
let str = 0;
let arr = [];
for (let j = 0; j < text.length; j++) {
if (text.charCodeAt(j) > 255) {
strLength += 2;
if (strLength > rows * num) {
strLength++;
arr.push(text.slice(str, j));
str = j;
rows++;
}
} else {
strLength++;
if (strLength > rows * num) {
arr.push(text.slice(str, j));
str = j;
rows++;
}
}
}
arr.push(text.slice(str, text.length));
return [strLength, arr, rows] //  [处理文字的总字节长度,每行显示内容的数组,行数]
},

// 保存到相册
savetup: function() {
var that = this;
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 310,
height: 490,
destWidth: 930,
destHeight: 1470,
canvasId: 'myCanvas',
success: function(res) {
//调取小程序当中获取图片
console.log(res.tempFilePath);
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.showModal({
title: 'Save chart success!',
content: 'The picture was successfully saved to the album, you can go to share ~',
showCancel: false,
confirmText: 'OK',
confirmColor: '#72B9C3',
success: function(res) {
if (res1.confirm) {
console.log('用户点击确定');
}
}
})
}
})
},
fail: function(res) {
console.log(res)
}
})
},

PHP后端

<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

class Wxcode extends Co
4000
ntroller
{
public function index($id = "")
{
header('content-type:text/html;charset=utf-8');
//配置APPID、APPSECRET
$APPID = "xxxxxxxxxxxxx";
$APPSECRET =  "xxxxxxxxxxxxxxx;
//获取access_token
$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

//缓存access_token
session_start();
$_SESSION['access_token'] = "";
$_SESSION['expires_in'] = 0;
if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
{
$json = $this->httpRequest( $access_token );
$json = json_decode($json,true);
$_SESSION['access_token'] = $json['access_token'];
$_SESSION['expires_in'] = time()+7200;
$ACCESS_TOKEN = $json["access_token"];
}else{
$ACCESS_TOKEN =  $_SESSION["access_token"];
}

//构建请求二维码参数
//path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
//width是二维码宽度
$qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN";
$path = "pages/houseDetail/houseDetail";
$param = json_encode(array("scene"=>"$id","page"=>"$path","width"=> 150));

//POST参数
$result = $this->httpRequest( $qcode, $param,"POST");
//生成二维码
file_put_contents("qrcode.jpg", $result);
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
$img_url = "https://www.move2china.com/qrcode.jpg";
return $img_url;
}

//把请求发送到微信服务器换取二维码
public function httpRequest($url, $data='', $method='GET'){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
if($method=='POST')
{
curl_setopt($curl, CURLOPT_POST, 1);
if ($data != '')
{
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
}

curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: