PHP微信小程序相关开发

热度:7762020-05-04 06:53 收藏 0 点赞 0

最近接了个项目,关于微信小程序的,我这里记录一下开发笔记。


小程序app.js里面的配置在其他页面读取方法

const app = getApp()
//调用data信息
app.data.xx (xx为对应参数)
//调用相关函数
app.function_name() (function_name换成对应的函数)

页面内js调用data里面的参数

this.data.xx (xx为对应参数)
//需要注意,如果是api接口内部调用,则需要先定义全局,再调用
var that = this;
wx.request({
	  url: 'xxx', //仅为示例,并非真实的接口地址
	  data: {
	
	  },
	  header: {
		'content-type': 'application/x-www-form-urlencoded' 
	  },
	  success (res) {
		//调用时
		var abc = that.data.xx

	  }
	})

设置当前页面的data数据

this.setData({
	
	userinfo:info,
	maskshow:0
	
})
//同理,api请求内部需要先在请求前面定义全局
var that = this;
wx.request({
	  url: 'xxx', //仅为示例,并非真实的接口地址
	  data: {
	
	  },
	  header: {
		'content-type': 'application/x-www-form-urlencoded 
	  },
	  success (res) {
		
		if(res.data.code==0){
			that.setData({
				userinfo:userinfo
			})
		}
	  }
	})

设置缓存和读取缓存

//检查并读取缓存
if(wx.getStorageSync('userinfo')){
		console.log(wx.getStorageSync('userinfo'));
		this.setData({
			userinfo:wx.getStorageSync('userinfo'),
			maskshow:0
			
		})
		
		
}else{
    //无缓存
}

//设置缓存
var userinfo = { };
userinfo['openid'] = 'xxxx';
wx.setStorageSync('userinfo', userinfo);

简单发起http请求

wx.request({
	  url: 'xxx', //仅为示例,并非真实的接口地址
	  data: {
	
	  },
	  header: {
		'content-type': 'application/x-www-form-urlencoded' 
	  },
	  success (res) {
		//返回数据必须为json才能被接收
		//返回的res.data才是后端的数据
		if(res.data.code==0){
			
		}
	  }
	})

上传文件接口使用

   //前台wxml
   <view class="photo">
            <view class="uploading fl">
              <image src="../../images/case2.jpg" wx:if="{{showimages==0}}"></image>
               <block wx:for="{{showimages}}" wx:key="*this">
                        <image  src="{{item}}" mode="aspectFill" data-idx="{{index}}" ></image>
                </block>
              <!--上传图片后显示-->
            </view>
            <view class="scinput fr" bindtap="upImage"></view>
         </view>
   
   //JS部分
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
		 var tempFilePaths = res.tempFilePaths;
		 console.log(tempFilePaths);
		wx.uploadFile({
		  url: 'https://xxxx/common/uploads', //仅为示例,非真实的接口地址
		  filePath: tempFilePaths[0],
		  name: 'file',
		  formData:{
			'molds':'message'
		  },
		   header: {
            "Content-Type": "multipart/form-data"//记得设置
          },
		  success: function(res){
		        //返回信息需要转JSON
			var data = JSON.parse(res.data);
			console.log(data);
			that.setData({
			  showimages: [data.url]
			})
		  }
		})
	
      }
    })

后端接收上传文件的函数

function uploads(){
	$file = $_POST['filename'];
	if(!$file){
		$file = 'file';
	}
	if ($_FILES[$file]["error"] > 0){
	  $data['error'] =  "Error: 上传错误!";
	  $data['code'] = 1000;
	}else{
	  // echo "Upload: " . $_FILES["file"]["name"] . "<br />";
	  // echo "Type: " . $_FILES["file"]["type"] . "<br />";
	  // echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
	  // echo "Stored in: " . $_FILES["file"]["tmp_name"];
	  $pix = explode('.',$_FILES[$file]['name']);
	  $pix = end($pix);

		$fileType = ['jpg','png','gif','jpeg'];//后台配置--可删除
		if(strpos($fileType,strtolower($pix))===false){
			$data['error'] =  "Error: 文件类型不允许上传!";
			$data['code'] = 1002;
			JsonReturn($data);
		}
		$fileSize = 20000;//单位kb,后台配置--可删除
		if($fileSize!=0 && ($_FILES[$file]["size"]/1024)>$fileSize){
			$data['error'] =  "Error: 文件大小超过网站内部限制!";
			$data['code'] = 1003;
			JsonReturn($data);
		}
		
	  
		$filename =  'Public/Home/'.date('Ymd').rand(1000,9999).'.'.$pix;
	  
		if(move_uploaded_file($_FILES[$file]['tmp_name'],$filename)){
			$data['url'] = '/'.$filename;
			$data['code'] = 0;
			
			
			
		}else{
			$data['error'] =  "Error: 请检查目录[Public/Home]写入权限";
			$data['code'] = 1001;
			  
		} 

		  
	  
	  }
	  
	  
	  JsonReturn($data,true);
	  exit;
	  
	
	
}


微信用户登录

//前台
 <view class="mask" wx:if="{{maskshow==1}}" >
  <view class="login_info">
    <view class="tit">授权登录</view>
    <view class="des">
      为了更快速的审核,我们需要授权您授权。
    </view>
   
    <view class="obtain">
      <button class="fl btn" bindtap="noShowLogin">暂不授权</button>
      <button class="fr btn blue" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">立即授权</button>
    </view>
    
  </view>
</view>
//js部分
    bindGetUserInfo(res) {
		console.log(res);
		if (res.detail.userInfo) {
		  console.log("点击了同意授权");
		   var that = this;
		  wx.getUserInfo({
			  success: function(res) {
				var userInfo = res.userInfo
				var nickName = userInfo.nickName
				var avatarUrl = userInfo.avatarUrl
				var gender = userInfo.gender //性别 0:未知、1:男、2:女
				var province = userInfo.province
				var city = userInfo.city
				var country = userInfo.country
				 wx.login({
				success: function (res) {
				  if (res.code) {
					wx.request({
					  url: 'xxx.php',//发送给后端获取openid
					  data: {
						code: res.code,
						nickName:nickName,
						avatarUrl:avatarUrl,
						gender:gender,
						province:province,
						city:city,
						country:country
						
					  },
					  header: {
						'content-type': 'application/json' // 默认值
					  },
					  success: function (res) {
						  var userinfo = {};
						 console.log(res);
						  userinfo['nickName'] = nickName;
						  userinfo['avatarUrl'] = avatarUrl;
						  userinfo['gender'] = gender;
						  userinfo['province'] = province;
						  userinfo['openid'] = res.data.info.openid;
						    //写入缓存
						  wx.setStorageSync('userinfo', userinfo);
						  that.setData({
							  openid:res.data.info.openid,
							  userinfo:userinfo,
							  maskshow:0
							  
						  })
						
					  }
					})
				  } else {
					console.log("授权失败");
				  }
				},
			  })
				
				
			  }
			})
		 
		  
 
		} else {
		  console.log("点击了拒绝授权");
		  wx.showToast({
			  title: '您拒绝授权不能申请!',
			  icon: 'error',
			  duration: 2500
			})
		 this.setData({
			 maskshow:1
			 
		 })
		  
		}
	},
	  noShowLogin:function(){
	   wx.showToast({
			  title: '您拒绝授权不能使用!',
			  icon: 'error',
			  duration: 2500
			})
	  this.setData({
			 maskshow:1
			 
		 })
		   
  },

PHP处理登录

 function checklogin(){
		
    	$params=$this->frparam();
    	$appid = $this->webconf['wxappid'];
    	$secret = $this->webconf['wxsecret'];
	    $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$params['code']."&grant_type=authorization_code";
	    $data=$this->doCurl($url);
		$info['data'] = $data;
		$data = json_decode($data,1);
		//注册用户信息
		if($data['openid']){
			if(!M('member')->find(['openid'=>$data['openid']])){
				$w['openid'] = $data['openid'];
				$w['litpic'] = $params['avatarUrl'];
				$w['city'] = $params['city'];
				$w['username'] = $params['nickName'];
				$w['province'] = $params['province'];
				M('member')->add($w);
			}
			
			
		}
		
	    $info['openid']=$data['openid'];
	    $info['avatar']=$params['avatarUrl'];
	    $info['province']=$params['province'];
	    $info['city']=$params['city'];
	    $info['nickName']=$params['nickName'];
	    JsonReturn(['status'=>1,'info'=>$info]);
    	
    	
    }
    public function doCurl($url)
	{
	    $curl = curl_init();
	    // 使用curl_setopt()设置要获取的URL地址
	    curl_setopt($curl, CURLOPT_URL, $url);
	    // 设置是否输出header
	    curl_setopt($curl, CURLOPT_HEADER, false);
	    // 设置是否输出结果
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    // 设置是否检查服务器端的证书
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
	    $data = curl_exec($curl);
	    // 使用 curl_close() 关闭CURL会话
	    curl_close($curl);
		
	    return $data;
	}

路由跳转相关

常用第一种:
wx.navigateTo(Object object)
保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。小程序中页面栈最多十层。
wx.navigateTo({
  url: 'test?id=1',
  events: {
    // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
    ...
  },
  success: function(res) {
    // 通过eventChannel向被打开页面传送数据
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
  }})
  
 //简单使用
 wx.navigateTo({
  url: 'test?id=1'
  })
 返回上一页
 wx.navigateBack({
  delta: 1,
  success: function() {
	  console.log('成功!')
  }

}) 
  
 常用第二种:
 wx.redirectTo(Object object)
关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 

wx.redirectTo({
  url: 'test?id=1'
  })

数据循环

<view wx:for="{{array}}"  wx:key="key">
  {{index}}: {{item.message}}
  {{array[index].message}}
</view>
使用 wx:for-item 可以指定数组当前元素的变量名,
使用 wx:for-index 可以指定数组当前下标的变量名:
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>

条件判断

<view wx:if="{{condition}}"> True </view>

条件输出

{{data?'真':'假'}}  //根据data的真假,使用三元运算符输出

小程序模板

#独立页面存储
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>
#其他页面调用
<template is="msgItem" data="{{data}}"/>
//is决定调用哪个部分,data表示传值

小程序页面Page

Page({
  data: {
    text: "This is page data."
  },
  onLoad: function(options) {
    // Do some initialize when page load.
  },
  onShow: function() {
    // Do something when page show.
  },
  onReady: function() {
    // Do something when page ready.
  },
  onHide: function() {
    // Do something when page hide.
  },
  onUnload: function() {
    // Do something when page close.
  },
  onPullDownRefresh: function() {
    // Do something when pull down.
  },
  onReachBottom: function() {
    // Do something when page reach bottom.
  },
  onShareAppMessage: function () {
    // return custom share data when user share.
  },
  onPageScroll: function() {
    // Do something when page scroll
  },
  onResize: function() {
    // Do something when page resize
  },
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  // Event handler.
  viewTap: function() {
    this.setData({
      text: 'Set some data for updating view.'
    }, function() {
      // this is setData callback
    })
  },
  customData: {
    hi: 'MINA'
  }})
data


暂无评论
登录后才可以评论~立即登录

如何获取资源?

您可以关注底部公众号,回复文章提示的 “ 关键词 ” 获取对应资源。

每日分享

每日分享收集的网络资源,其中包含开源项目、小工具、常用软件,以及音频视频、电子书籍等。

外卖天天领红包,饿了么,美团红包天天都有!

外卖天天领红包,饿了么,美团红...

最低每顿可省2元

分享两个远程工具-ToDesk和向日葵

分享两个远程工具-ToDesk和向日葵...

在工作生活中经常用到远程,QQ远程很卡,第三方远程工具就比较方便了。

爱奇艺万能播放器2018年完整版

爱奇艺万能播放器2018年完整版

2018年的爱奇艺万能播放器,功能齐全,没有广告!

分享500套个人求职简历模板

分享500套个人求职简历模板

500套免费求职简历下载!

一款最近很火的自动跳过广告APP,无root直装版

一款最近很火的自动跳过广告APP,...

自动跳过广告,无需root

WPS免费去广告电脑软件

WPS免费去广告电脑软件

wps广告实在太多了,下载一个去广告版本