第一步:获取小程序二维码
代码如下(采用tp5框架):
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Config;
use app\api\controller\Common;class Code extends Common{/*** [getXcxCode 获取微信小程序二维码]* @return [type] [小程序二维码图片]*/public function getXcxCode(){//获取参数值$moduleid=$this->request->get('moduleid');$itemid=$this->request->get('itemid');$url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$this->_getAccessToken();$data=['scene'=>'1001', 'width'=>430,'auto_color'=>false,];$data=json_encode($data);$result = $this->_requestPost($url,$data);if (!$result) {return false;} $fileName=$moduleid."-".$itemid; if ($fileName) {//判断file文件中是否存在数据库当中$isfile=Db::name('xcxcode')->where('fileName=:fileName',['fileName'=>$fileName])->select();if(!$isfile){file_put_contents("static/xcxcode/".$fileName.".jpeg", $result);$datafile=['fileName'=>$fileName];Db::name('xcxcode')->insert($datafile);}return "static/xcxcode/".$fileName.".jpeg"; }}/*** 获取 access_tonken* @param string $token_file 用来存储token的临时文件*/private function _getAccessToken($token_file='./access_token') {// 考虑过期问题,将获取的access_token存储到某个文件中$life_time = 7200;if (file_exists($token_file) && time()-filemtime($token_file)<$life_time) {// 存在有效的access_tokenreturn file_get_contents($token_file);}// 目标URL: $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".Config::get('appid')."&secret=".Config::get('appsecret');//向该URL,发送GET请求$result = $this->_requestGet($url);if (!$result) {return false;}// 存在返回响应结果$result_obj = json_decode($result);// 写入file_put_contents($token_file, $result_obj->access_token);return $result_obj->access_token;}}
Common含有GET,POST请求函数,其代码如下:
/*** 发送GET请求的方法* @param string $url URL* @param bool $ssl 是否为https协议* @return string 响应主体Content*/protected function _requestGet($url, $ssl=true) {// curl完成$curl = curl_init();//设置curl选项curl_setopt($curl, CURLOPT_URL, $url);//URL$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);//user_agent,请求代理信息curl_setopt($curl, CURLOPT_AUTOREFERER, true);//referer头,请求来源curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间//SSL相关if ($ssl) {curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//禁用后cURL将终止从服务端进行验证curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//检查服务器SSL证书中是否存在一个公用名(common name)。}curl_setopt($curl, CURLOPT_HEADER, false);//是否处理响应头curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//curl_exec()是否返回响应结果// 发出请求$response = curl_exec($curl);if (false === $response) {echo '<br>', curl_error($curl), '<br>';return false;}curl_close($curl);return $response;}/*** 发送GET请求的方法* @param string $url URL* @param bool $ssl 是否为https协议* @return string 响应主体Content*/protected function _requestPost($url, $data, $ssl=true) {//curl完成$curl = curl_init();//设置curl选项curl_setopt($curl, CURLOPT_URL, $url);//URL$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);//user_agent,请求代理信息curl_setopt($curl, CURLOPT_AUTOREFERER, true);//referer头,请求来源curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间//SSL相关if ($ssl) {curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//禁用后cURL将终止从服务端进行验证curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//检查服务器SSL证书中是否存在一个公用名(common name)。}// 处理post相关选项curl_setopt($curl, CURLOPT_POST, true);// 是否为POST请求curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// 处理请求数据// 处理响应结果curl_setopt($curl, CURLOPT_HEADER, false);//是否处理响应头curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//curl_exec()是否返回响应结果// 发出请求$response = curl_exec($curl);if (false === $response) {echo '<br>', curl_error($curl), '<br>';return false;}curl_close($curl);return $response;}
第二步:前台小程序
使用小程序画布js代码如下:
onLoad: function (options) {var that = this;//1. 请求后端API生成小程序码//that.getQr();//2. canvas绘制文字和图片const ctx = wx.createCanvasContext('myCanvas');var imgPath = '../../../image/intro.jpg';var bgImgPath = '../../../image/bgImgPath.jpg';var basicprofile ='../../../image/basicprofile.png';var xcxcode ="http://localhost/mining120/public/static/xcxcode/29-5.jpeg";//填充背景ctx.setFillStyle('#cccccc');ctx.fillRect(0, 0, 240, 360);ctx.setFillStyle('#ffffff');ctx.fillRect(1, 1, 238, 358);//绘制产品图ctx.drawImage(imgPath, 2, 2, 236, 200);//绘制标题ctx.setFontSize(16);ctx.setFillStyle('#000000');ctx.fillText('圆通删掉贷方金额', 10, 225);//绘制介绍产品ctx.setFontSize(12);ctx.setFillStyle('#6F6F6F');ctx.fillText('宠友们快来围观萌宠靓照我在萌爪幼稚园', 10, 250);ctx.fillText('我在萌爪幼稚园', 10, 270);//绘制一条虚线ctx.strokeStyle = 'blue';ctx.beginPath();ctx.setLineWidth(1);ctx.setLineDash([2, 4]);ctx.moveTo(10, 287);ctx.lineTo(230, 287);ctx.stroke();//绘制矿业人图标ctx.drawImage(basicprofile, 10, 310, 30, 30);//绘制介绍ctx.setFontSize(11);ctx.setFillStyle('#aaaaaa');ctx.fillText('长按扫码查看详情', 47, 318);ctx.fillText('分享自矿业人小程序', 47, 338); ctx.drawImage(xcxcode, 165, 295, 60, 60);ctx.draw();},
wxml代码如下:
<canvas style="margin:0 auto;margin-bottom:30px;width: 240px; height: 360px;box-shadow:1px 2px 2px #ccc;border-raidus:1px;" canvas-id="myCanvas"></canvas><view class='ft'>保存图片到手机相册,分享到朋友圈</view>
<view style="text-align:center;padding-bottom:20px"><button bindtap='savetup' type="primary" size='mini'>保存到相册</button></view>
</view>
保存图片代码:
savetup:function(){var that = this;wx.canvasToTempFilePath({x: 0,y: 0,width: 240,height: 360,destWidth: 240,destHeight: 360,canvasId: 'myCanvas',success: function (res) {//调取小程序当中获取图片console.log(res.tempFilePath);wx.saveImageToPhotosAlbum({filePath: res.tempFilePath,success(res) {wx.showModal({title: '存图成功',content: '图片成功保存到相册了,去发圈噻~',showCancel: false,confirmText: '好哒',confirmColor: '#72B9C3',success: function (res) {if (res1.confirm) {console.log('用户点击确定');}}})}}) },fail: function (res) {console.log(res)}})
第三步:获取图片结果
如果有问题可以加我微信:jskwjg99999