来自原文地址
目录结构:
es6-promise文件自行到官网下载
index.js文件引入es6-promise并在onLoad中写下函数:
var Promise = require('../../es6-promise.min.js');//引入ES6
onLoad: function () {
var that = this;
//第一步:更新用户信息
var getUserInfo = function(){
return new Promise(function(resolve,reject){
app.getUserInfo();
resolve();
});
};
getUserInfo().then(function(){
//第二步:其它操作
});
},
并在app.js文件写入下面代码
//app.js
var Promise = require('es6-promise.min.js');//引入ES6
App({
onError:function(res){
console.log(res);
},
//获取session
getSession:function(){
var info=wx.getStorageSync('session');
return info.session;
},
//获取用户信息
getUserInfo:function(){
var timestamp=getTimestamp();//获取当前时间戳
//检查微信登录态是否过期
var checkSession = function(){
return new Promise(function(resolve,reject){
wx.checkSession({
fail: function(){
console.log('SESSION登录态过期!');
reject();
},
success:function(){
resolve();
}
});
});
};
//检查SESSION缓存是否过期
var checkStorage = function () {
return new Promise(function(resolve,reject){
wx.getStorage({
key: 'session',
success: function(res) {
if(res.data.expires){
if(timestamp>res.data.expires){//超时
resolve();
}else{
reject();
}
}else{
resolve();
}
},
fail:function(){
resolve();
}
});
});
};
//刷新用户信息
var updateUserInfo=function(){
return new Promise(function(resolve,reject){
wx.showToast({
title: '加载中',
icon: 'loading',
duration: 10000,
mask:true
});
resolve();
});
}
//用户授权登录
var login= function(){
return new Promise(function(resolve,reject){
wx.login({
success: function(loginRes) {
resolve(loginRes);
},
fail:function(res){
reject(res);
}
});
});
}
//获取用户信息
var getUserInfo = function (loginRes) {
return new Promise(function(resolve,reject){
var that=this;
wx.getUserInfo({
success: function (userinfoRes) {
var data={
loginRes:loginRes,
userinfoRes:userinfoRes
}
resolve(data);
},
fail:function(res){
reject(res);
}
});
});
};
//用户信息入库
var request = function (data) {
return new Promise(function(resolve,reject){
var userInfoStr=JSON.stringify(data.userinfoRes);
wx.request({
url: ',
data: {
code: data.loginRes.code,
userInfo:userInfoStr
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method:'POST',
success: function(res) {
//缓存session及userInfo
if(res.data.error==0){
var return_obj={
res:res.data,
userinfoRes:data.userinfoRes
};
resolve(return_obj);
}else{
reject(res);
}
},
fail:function(res){
reject(res);
}
});
});
};
//异步写入缓存
var setStorage = function (data) {
return new Promise(function(resolve,reject){
wx.setStorage({
key:"session",
data:{
session:data.res.session,
userInfo:data.userinfoRes.userInfo,
expires:data.res.expires //超时时间戳
},
success:function(){
resolve();
},
fail:function(res){
reject(res);
}
})
})
};
checkSession().then(function(value){
console.log('SESSION登录态未过期!');
checkStorage().then(function(value) {
console.log('SESSION缓存已过期');
updateUserInfo().then(function(){
login().then(function(value){
console.log('授权登录成功');
getUserInfo(value).then(function(value){
console.log('获取用户信息成功');
request(value).then(function(value) {
console.log('用户信息入库成功');
setStorage(value).then(function(value) {
console.log('写入缓存成功');
wx.hideToast();
},function(value) {
wx.showModal({
title: '写入缓存失败',
showCancel:false,
content: value
})
}).catch(console.log(console));
}, function(value) {
wx.showModal({
title: '用户信息入库失败',
showCancel:false,
content: value
})
});
}, function(value) {
wx.showModal({
title: '获取用户信息失败!',
showCancel:false,
content: value
})
});
}, function(value){
wx.showModal({
title: '授权登录失败!',
showCancel:false,
content: value
})
});
});
},function(){
console.log('SESSION缓存未过期');
});
},function(){
console.log('SESSION登录态已过期!');
updateUserInfo().then(function(){
login().then(function(value){
console.log('授权登录成功');
getUserInfo(value).then(function(value){
console.log('获取用户信息成功');
request(value).then(function(value) {
console.log('用户信息入库成功');
setStorage(value).then(function(value) {
console.log('写入缓存成功');
wx.hideToast();
},function(value) {
wx.showModal({
title: '写入缓存失败',
showCancel:false,
content: value
})
}).catch(console.log(console));
}, function(value) {
wx.showModal({
title: '用户信息入库失败',
showCancel:false,
content: value
})
});
}, function(value) {
wx.showModal({
title: '获取用户信息失败!',
showCancel:false,
content: value
})
});
}, function(value){
wx.showModal({
title: '授权登录失败!',
showCancel:false,
content: value
})
});
});
});
}
});
function getTimestamp(){
var tmp = Date.parse( new Date() ).toString();
tmp = tmp.substr(0,10);
return tmp;
}
后端PHP代码:(thinkphp框架)
<?php
/*
* 小程序公共类
*/
namespace Weixin\Controller;
use Think\Controller\RestController;
class CommonController extends RestController{
//发送模板消息
public function sendmessage(){
$data=$_POST=json_decode(file_get_contents('php://input'), TRUE);
$access_token=$this->getAccessToken();
$request_url='.$access_token;
$request_data=array(
'touser'=>$data['touser'],//接收者(用户)的 openid
'template_id'=>$data['template_id'],//所需下发的模板消息的id
'page'=>$data['page'],//点击模板卡片后的跳转页面
'form_id'=>$data['form_id'],//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
'data'=>$data['data'],//"keyword1": {"value": "339208499", "color": "#173177"}
'emphasis_keyword'=>$data['emphasis_keyword']//模板需要放大的关键词,不填则默认无放大
);
$return=json_decode(https_request($request_url,$request_data,'json'),true);
$this->response($return,'json');
}
public function getSession(){
$code=$_POST['code'];
if(!$code){
$data['errmsg']='code为空';
$data['error']=1;
$this->response($data,'json');
exit;
}
if(!$_POST['userInfo']){
$data['errmsg']='userInfo为空';
$data['error']=1;
$this->response($data,'json');
exit;
}
$userInfo=json_decode($_POST['userInfo'],true);
$return=$this->updateSession($code,$userInfo);
$this->response($return,'json');
}
//获取AccessToken
private function getAccessToken(){
$common_config_Model=M('common_config','wei_');
$common_config_Data=$common_config_Model->where(array('appid'=>'YOURAPPID'))->find();
if($common_config_Data['access_token']&&time()<$common_config_Data['access_token_update_time']+$common_config_Data['access_token_expires_in']){
$return=array('access_token'=>$common_config_Data['access_token'],'expires_in'=>$common_config_Data['access_token_expires_in']);
}else{
$url='.$common_config_Data['appid'].'&secret='.$common_config_Data['secret'];
$return=json_decode(https_request($url),true);
if($return['access_token']){
$save=array(
'access_token'=>$return['access_token'],
'access_token_expires_in'=>$return['expires_in'],
'access_token_update_time'=>time()
);
$common_config_Model->where(array('appid'=>'YOURAPPID'))->data($save)->save();
}
}
return $return['access_token'];
}
//刷新session
private function updateSession($code,$userInfo){
$return=$this->getOAuth($code);
if(!$return['session_key']){
$data['errmsg']='getOAuth函数报错:'.json_encode($return);
$data['error']=1;
return $data;
exit;
}
$unionid_Data=json_decode($this->getUnionID($return['session_key'],$userInfo),true);
if(!$unionid_Data['unionId']){
$data['errmsg']='getUnionID函数报错:'.json_encode($unionid_Data);
$data['error']=1;
return $data;
exit;
}
$wei_user_Model=M('user','wei_');
$exist=$wei_user_Model->where(array('openid'=>$return['openid']))->find();
if($exist){
$save=array(
'unionid'=>$unionid_Data['unionId'],
'session_key'=>$return['session_key'],
'nickname'=>$userInfo['userInfo']['nickName'],
'gender'=>$userInfo['userInfo']['gender'],
'avatarUrl'=>$userInfo['userInfo']['avatarUrl'],
'province'=>$userInfo['userInfo']['province'],
'city'=>$userInfo['userInfo']['city'],
'expires_in'=>$return['expires_in'],
'dateline'=>time()
);
$is_save=$wei_user_Model->where(array('openid'=>$return['openid']))->data($save)->save();
}else{
$add=array(
'openid'=>$return['openid'],
'unionid'=>$unionid_Data['unionId'],
'session_key'=>$return['session_key'],
'nickname'=>$userInfo['userInfo']['nickName'],
'gender'=>$userInfo['userInfo']['gender'],
'avatarUrl'=>$userInfo['userInfo']['avatarUrl'],
'province'=>$userInfo['userInfo']['province'],
'city'=>$userInfo['userInfo']['city'],
'expires_in'=>$return['expires_in'],
'dateline'=>time()
);
$is_add=$wei_user_Model->data($add)->add();
}
if($is_save!==FALSE || $is_add){
$wei_user_Data=$wei_user_Model->where(array('openid'=>$return['openid']))->find();
$this->setSession($return['session_key']);
$data['session']=session('session');
$data['expires']=time()+$return['expires_in'];
$data['error']=0;
}else{
$data['errmsg']="session更新失败!";
$data['error']=1;
}
return $data;
}
//设置session
private function setSession($session){
if(!empty($session)){
session('session',$session);
}
}
//发送code授权
private function getOAuth($code){
$url=';
$data=array(
'appid'=>'YOURAPPID',
'secret'=>'YOURSECRET',
'js_code'=>$code,
'grant_type'=>'authorization_code'
);
$return=json_decode(https_request($url, $data),true);
return $return;
}
//得到unionid 提交sessionKey、userinfo、
private function getUnionID($sessionKey,$userInfo){
if(!$userInfo['encryptedData']){
return 'encryptedData为空';
exit;
}
if(!$userInfo['iv']){
return 'iv为空';
exit;
}
vendor('wxBizDataCrypt.wxBizDataCrypt');
$appid = 'YOURAPPID';
$encryptedData=$userInfo['encryptedData'];
$iv = $userInfo['iv'];
$pc = new \WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
return $data;
}else{
return $errCode;
}
}
//支付回调
public function payNotify(){
//存储微信的回调
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$array=$this->FromXml($xml);
if($array['return_code']=='SUCCESS'){
//马拉松俱乐部
if($array['attach']=='MarathonClubJoinfee'){
$marathonclub_join_Model=M('marathonclub_join','wei_');
$marathonclub_join_Data=$marathonclub_join_Model->where(array('order_id'=>$array['out_trade_no']))->find();
if(!$marathonclub_join_Data['is_pay']){
$is_save=$marathonclub_join_Model->where(array('order_id'=>$array['out_trade_no']))->data(array('is_pay'=>1))->save();
if($is_save){
$return['return_code']='SUCCESS';
$returnXml=$this->arrayToXml($return);
}else{
$return['return_code']='FAIL';
$returnXml=$this->arrayToXml($return);
}
}else{
$return['return_code']='FAIL';
$returnXml=$this->arrayToXml($return);
}
}
echo $returnXml;
}
}
//将xml转为array
private function FromXml($xml){
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $this->values;
}
}