轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
轻源码 门户 终极进阶 查看主题

微信小程序获得userinfo、session、openid和unionid的前端及php代码

发布者: luxiangtian | 发布时间: 2018-7-11 21:38| 查看数: 6265| 评论数: 0|帖子模式

来自原文地址

目录结构:

es6-promise文件自行到官网下载

  1. index.js文件引入es6-promise并在onLoad中写下函数:
  1. var Promise = require('../../es6-promise.min.js');//引入ES6
  2. onLoad: function () {
  3. var that = this;
  4. //第一步:更新用户信息
  5. var getUserInfo = function(){
  6. return new Promise(function(resolve,reject){
  7. app.getUserInfo();
  8. resolve();
  9. });
  10. };
  11. getUserInfo().then(function(){
  12. //第二步:其它操作
  13. });
  14. },

并在app.js文件写入下面代码

  1. //app.js
  2. var Promise = require('es6-promise.min.js');//引入ES6
  3. App({
  4. onError:function(res){
  5. console.log(res);
  6. },
  7. //获取session
  8. getSession:function(){
  9. var info=wx.getStorageSync('session');
  10. return info.session;
  11. },
  12. //获取用户信息
  13. getUserInfo:function(){
  14. var timestamp=getTimestamp();//获取当前时间戳
  15. //检查微信登录态是否过期
  16. var checkSession = function(){
  17. return new Promise(function(resolve,reject){
  18. wx.checkSession({
  19. fail: function(){
  20. console.log('SESSION登录态过期!');
  21. reject();
  22. },
  23. success:function(){
  24. resolve();
  25. }
  26. });
  27. });
  28. };
  29. //检查SESSION缓存是否过期
  30. var checkStorage = function () {
  31. return new Promise(function(resolve,reject){
  32. wx.getStorage({
  33. key: 'session',
  34. success: function(res) {
  35. if(res.data.expires){
  36. if(timestamp>res.data.expires){//超时
  37. resolve();
  38. }else{
  39. reject();
  40. }
  41. }else{
  42. resolve();
  43. }
  44. },
  45. fail:function(){
  46. resolve();
  47. }
  48. });
  49. });
  50. };
  51. //刷新用户信息
  52. var updateUserInfo=function(){
  53. return new Promise(function(resolve,reject){
  54. wx.showToast({
  55. title: '加载中',
  56. icon: 'loading',
  57. duration: 10000,
  58. mask:true
  59. });
  60. resolve();
  61. });
  62. }
  63. //用户授权登录
  64. var login= function(){
  65. return new Promise(function(resolve,reject){
  66. wx.login({
  67. success: function(loginRes) {
  68. resolve(loginRes);
  69. },
  70. fail:function(res){
  71. reject(res);
  72. }
  73. });
  74. });
  75. }
  76. //获取用户信息
  77. var getUserInfo = function (loginRes) {
  78. return new Promise(function(resolve,reject){
  79. var that=this;
  80. wx.getUserInfo({
  81. success: function (userinfoRes) {
  82. var data={
  83. loginRes:loginRes,
  84. userinfoRes:userinfoRes
  85. }
  86. resolve(data);
  87. },
  88. fail:function(res){
  89. reject(res);
  90. }
  91. });
  92. });
  93. };
  94. //用户信息入库
  95. var request = function (data) {
  96. return new Promise(function(resolve,reject){
  97. var userInfoStr=JSON.stringify(data.userinfoRes);
  98. wx.request({
  99. url: ',
  100. data: {
  101. code: data.loginRes.code,
  102. userInfo:userInfoStr
  103. },
  104. header: {
  105. 'content-type': 'application/x-www-form-urlencoded'
  106. },
  107. method:'POST',
  108. success: function(res) {
  109. //缓存session及userInfo
  110. if(res.data.error==0){
  111. var return_obj={
  112. res:res.data,
  113. userinfoRes:data.userinfoRes
  114. };
  115. resolve(return_obj);
  116. }else{
  117. reject(res);
  118. }
  119. },
  120. fail:function(res){
  121. reject(res);
  122. }
  123. });
  124. });
  125. };
  126. //异步写入缓存
  127. var setStorage = function (data) {
  128. return new Promise(function(resolve,reject){
  129. wx.setStorage({
  130. key:"session",
  131. data:{
  132. session:data.res.session,
  133. userInfo:data.userinfoRes.userInfo,
  134. expires:data.res.expires //超时时间戳
  135. },
  136. success:function(){
  137. resolve();
  138. },
  139. fail:function(res){
  140. reject(res);
  141. }
  142. })
  143. })
  144. };
  145. checkSession().then(function(value){
  146. console.log('SESSION登录态未过期!');
  147. checkStorage().then(function(value) {
  148. console.log('SESSION缓存已过期');
  149. updateUserInfo().then(function(){
  150. login().then(function(value){
  151. console.log('授权登录成功');
  152. getUserInfo(value).then(function(value){
  153. console.log('获取用户信息成功');
  154. request(value).then(function(value) {
  155. console.log('用户信息入库成功');
  156. setStorage(value).then(function(value) {
  157. console.log('写入缓存成功');
  158. wx.hideToast();
  159. },function(value) {
  160. wx.showModal({
  161. title: '写入缓存失败',
  162. showCancel:false,
  163. content: value
  164. })
  165. }).catch(console.log(console));
  166. }, function(value) {
  167. wx.showModal({
  168. title: '用户信息入库失败',
  169. showCancel:false,
  170. content: value
  171. })
  172. });
  173. }, function(value) {
  174. wx.showModal({
  175. title: '获取用户信息失败!',
  176. showCancel:false,
  177. content: value
  178. })
  179. });
  180. }, function(value){
  181. wx.showModal({
  182. title: '授权登录失败!',
  183. showCancel:false,
  184. content: value
  185. })
  186. });
  187. });
  188. },function(){
  189. console.log('SESSION缓存未过期');
  190. });
  191. },function(){
  192. console.log('SESSION登录态已过期!');
  193. updateUserInfo().then(function(){
  194. login().then(function(value){
  195. console.log('授权登录成功');
  196. getUserInfo(value).then(function(value){
  197. console.log('获取用户信息成功');
  198. request(value).then(function(value) {
  199. console.log('用户信息入库成功');
  200. setStorage(value).then(function(value) {
  201. console.log('写入缓存成功');
  202. wx.hideToast();
  203. },function(value) {
  204. wx.showModal({
  205. title: '写入缓存失败',
  206. showCancel:false,
  207. content: value
  208. })
  209. }).catch(console.log(console));
  210. }, function(value) {
  211. wx.showModal({
  212. title: '用户信息入库失败',
  213. showCancel:false,
  214. content: value
  215. })
  216. });
  217. }, function(value) {
  218. wx.showModal({
  219. title: '获取用户信息失败!',
  220. showCancel:false,
  221. content: value
  222. })
  223. });
  224. }, function(value){
  225. wx.showModal({
  226. title: '授权登录失败!',
  227. showCancel:false,
  228. content: value
  229. })
  230. });
  231. });
  232. });
  233. }
  234. });
  235. function getTimestamp(){
  236. var tmp = Date.parse( new Date() ).toString();
  237. tmp = tmp.substr(0,10);
  238. return tmp;
  239. }

后端PHP代码:(thinkphp框架)

  1. <?php
  2. /*
  3. * 小程序公共类
  4. */
  5. namespace Weixin\Controller;
  6. use Think\Controller\RestController;
  7. class CommonController extends RestController{
  8. //发送模板消息
  9. public function sendmessage(){
  10. $data=$_POST=json_decode(file_get_contents('php://input'), TRUE);
  11. $access_token=$this->getAccessToken();
  12. $request_url='.$access_token;
  13. $request_data=array(
  14. 'touser'=>$data['touser'],//接收者(用户)的 openid
  15. 'template_id'=>$data['template_id'],//所需下发的模板消息的id
  16. 'page'=>$data['page'],//点击模板卡片后的跳转页面
  17. 'form_id'=>$data['form_id'],//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
  18. 'data'=>$data['data'],//"keyword1": {"value": "339208499", "color": "#173177"}
  19. 'emphasis_keyword'=>$data['emphasis_keyword']//模板需要放大的关键词,不填则默认无放大
  20. );
  21. $return=json_decode(https_request($request_url,$request_data,'json'),true);
  22. $this->response($return,'json');
  23. }
  24. public function getSession(){
  25. $code=$_POST['code'];
  26. if(!$code){
  27. $data['errmsg']='code为空';
  28. $data['error']=1;
  29. $this->response($data,'json');
  30. exit;
  31. }
  32. if(!$_POST['userInfo']){
  33. $data['errmsg']='userInfo为空';
  34. $data['error']=1;
  35. $this->response($data,'json');
  36. exit;
  37. }
  38. $userInfo=json_decode($_POST['userInfo'],true);
  39. $return=$this->updateSession($code,$userInfo);
  40. $this->response($return,'json');
  41. }
  42. //获取AccessToken
  43. private function getAccessToken(){
  44. $common_config_Model=M('common_config','wei_');
  45. $common_config_Data=$common_config_Model->where(array('appid'=>'YOURAPPID'))->find();
  46. if($common_config_Data['access_token']&&time()<$common_config_Data['access_token_update_time']+$common_config_Data['access_token_expires_in']){
  47. $return=array('access_token'=>$common_config_Data['access_token'],'expires_in'=>$common_config_Data['access_token_expires_in']);
  48. }else{
  49. $url='.$common_config_Data['appid'].'&secret='.$common_config_Data['secret'];
  50. $return=json_decode(https_request($url),true);
  51. if($return['access_token']){
  52. $save=array(
  53. 'access_token'=>$return['access_token'],
  54. 'access_token_expires_in'=>$return['expires_in'],
  55. 'access_token_update_time'=>time()
  56. );
  57. $common_config_Model->where(array('appid'=>'YOURAPPID'))->data($save)->save();
  58. }
  59. }
  60. return $return['access_token'];
  61. }
  62. //刷新session
  63. private function updateSession($code,$userInfo){
  64. $return=$this->getOAuth($code);
  65. if(!$return['session_key']){
  66. $data['errmsg']='getOAuth函数报错:'.json_encode($return);
  67. $data['error']=1;
  68. return $data;
  69. exit;
  70. }
  71. $unionid_Data=json_decode($this->getUnionID($return['session_key'],$userInfo),true);
  72. if(!$unionid_Data['unionId']){
  73. $data['errmsg']='getUnionID函数报错:'.json_encode($unionid_Data);
  74. $data['error']=1;
  75. return $data;
  76. exit;
  77. }
  78. $wei_user_Model=M('user','wei_');
  79. $exist=$wei_user_Model->where(array('openid'=>$return['openid']))->find();
  80. if($exist){
  81. $save=array(
  82. 'unionid'=>$unionid_Data['unionId'],
  83. 'session_key'=>$return['session_key'],
  84. 'nickname'=>$userInfo['userInfo']['nickName'],
  85. 'gender'=>$userInfo['userInfo']['gender'],
  86. 'avatarUrl'=>$userInfo['userInfo']['avatarUrl'],
  87. 'province'=>$userInfo['userInfo']['province'],
  88. 'city'=>$userInfo['userInfo']['city'],
  89. 'expires_in'=>$return['expires_in'],
  90. 'dateline'=>time()
  91. );
  92. $is_save=$wei_user_Model->where(array('openid'=>$return['openid']))->data($save)->save();
  93. }else{
  94. $add=array(
  95. 'openid'=>$return['openid'],
  96. 'unionid'=>$unionid_Data['unionId'],
  97. 'session_key'=>$return['session_key'],
  98. 'nickname'=>$userInfo['userInfo']['nickName'],
  99. 'gender'=>$userInfo['userInfo']['gender'],
  100. 'avatarUrl'=>$userInfo['userInfo']['avatarUrl'],
  101. 'province'=>$userInfo['userInfo']['province'],
  102. 'city'=>$userInfo['userInfo']['city'],
  103. 'expires_in'=>$return['expires_in'],
  104. 'dateline'=>time()
  105. );
  106. $is_add=$wei_user_Model->data($add)->add();
  107. }
  108. if($is_save!==FALSE || $is_add){
  109. $wei_user_Data=$wei_user_Model->where(array('openid'=>$return['openid']))->find();
  110. $this->setSession($return['session_key']);
  111. $data['session']=session('session');
  112. $data['expires']=time()+$return['expires_in'];
  113. $data['error']=0;
  114. }else{
  115. $data['errmsg']="session更新失败!";
  116. $data['error']=1;
  117. }
  118. return $data;
  119. }
  120. //设置session
  121. private function setSession($session){
  122. if(!empty($session)){
  123. session('session',$session);
  124. }
  125. }
  126. //发送code授权
  127. private function getOAuth($code){
  128. $url=';
  129. $data=array(
  130. 'appid'=>'YOURAPPID',
  131. 'secret'=>'YOURSECRET',
  132. 'js_code'=>$code,
  133. 'grant_type'=>'authorization_code'
  134. );
  135. $return=json_decode(https_request($url, $data),true);
  136. return $return;
  137. }
  138. //得到unionid 提交sessionKey、userinfo、
  139. private function getUnionID($sessionKey,$userInfo){
  140. if(!$userInfo['encryptedData']){
  141. return 'encryptedData为空';
  142. exit;
  143. }
  144. if(!$userInfo['iv']){
  145. return 'iv为空';
  146. exit;
  147. }
  148. vendor('wxBizDataCrypt.wxBizDataCrypt');
  149. $appid = 'YOURAPPID';
  150. $encryptedData=$userInfo['encryptedData'];
  151. $iv = $userInfo['iv'];
  152. $pc = new \WXBizDataCrypt($appid, $sessionKey);
  153. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  154. if ($errCode == 0) {
  155. return $data;
  156. }else{
  157. return $errCode;
  158. }
  159. }
  160. //支付回调
  161. public function payNotify(){
  162. //存储微信的回调
  163. $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
  164. $array=$this->FromXml($xml);
  165. if($array['return_code']=='SUCCESS'){
  166. //马拉松俱乐部
  167. if($array['attach']=='MarathonClubJoinfee'){
  168. $marathonclub_join_Model=M('marathonclub_join','wei_');
  169. $marathonclub_join_Data=$marathonclub_join_Model->where(array('order_id'=>$array['out_trade_no']))->find();
  170. if(!$marathonclub_join_Data['is_pay']){
  171. $is_save=$marathonclub_join_Model->where(array('order_id'=>$array['out_trade_no']))->data(array('is_pay'=>1))->save();
  172. if($is_save){
  173. $return['return_code']='SUCCESS';
  174. $returnXml=$this->arrayToXml($return);
  175. }else{
  176. $return['return_code']='FAIL';
  177. $returnXml=$this->arrayToXml($return);
  178. }
  179. }else{
  180. $return['return_code']='FAIL';
  181. $returnXml=$this->arrayToXml($return);
  182. }
  183. }
  184. echo $returnXml;
  185. }
  186. }
  187. //将xml转为array
  188. private function FromXml($xml){
  189. //将XML转为array
  190. //禁止引用外部xml实体
  191. libxml_disable_entity_loader(true);
  192. $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  193. return $this->values;
  194. }
  195. }

最新评论

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

客服QQ点击咨询

微信公众号

APP客户端

Copyright © 2016-2019 http://www.qingyuanma.com/ 鲁ICP备17014494号

快速回复 返回顶部 返回列表