微信授权登录和微信分享

<?php

namespace app\common\controller;
use app\common\controller\WechatAuth;

class PortalBase extends Base
{
protected function _initialize()
{
    parent::_initialize();
    $uid = cookie('uid');
    if(empty($uid)) {
       $this->auth();
      }
   $wechatClass = new WechatAuth();
   $wxConfig = $wechatClass->wxshare();
   $this->assign(['uid'=>$uid,'wxconfig'=>$wxConfig]);
}

private function auth(){
   $wechatClass = new WechatAuth();
   $users=$wechatClass->getAccessToken();
   $uid=db('user')->where(['openid'=>$users['openid']])->value('id');
   if($users){
      $this->baocun_uid($uid,$users);
   }
}

public function baocun_uid($uid,$users){
if(!$uid){

$uid=db('user')->insertGetId(['openid'=>$users['openid'],'nickname'=>$users['nickname'],'sex'=>$users['sex'],'city'=>$users['city'],'headimg'=>$users['headimgurl'],'jifen'=>$login_jifen,'pid'=>$fxuid,'create_time'=>time()]);

}

   cookie('uid',$uid);
}

}

?>

 

 

<?php
namespace app\common\controller;

class WechatAuth {
   private $appid = '';
   private $secret = '';
   private $requestCodeURL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
//微信授权登录
public function getAccessToken()
{
   $domain = request()->domain();
   $code = input('code');
   $url = rtrim($domain,'/').$_SERVER['REQUEST_URI'];
   if($code){
      $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->secret&code=$code&grant_type=authorization_code";
      $oauth2 = json_decode(file_get_contents($oauth2Url),true);
   if (!isset($oauth2["access_token"])){
         return null;
   }
   $access_token = $oauth2["access_token"]; // 获得 access_token(获取用户信息的access_token) 和openid
   $openid = $oauth2['openid'];
   // 获取用户信息(不包含是否关注公众号字段 - subscribe)
   $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
   $userInfo = json_decode(file_get_contents($get_user_info_url),true);
   return $userInfo;
   }else{
      $codeUrl = $this->getRequestCodeURL($url,'oauth');
      header('Location:' . $codeUrl);
}

}
//获取code
public function getRequestCodeURL($redirect_uri, $state = null,$scope = 'snsapi_userinfo'){
   $query = array(
   'appid' => $this->appid,
   'redirect_uri' => $redirect_uri,
   'response_type' => 'code',
   'scope' => $scope,
);
if(!is_null($state) && preg_match('/[a-zA-Z0-9]+/', $state)){
   $query['state'] = $state;
}
$query = http_build_query($query);
   return "{$this->requestCodeURL}?{$query}#wechat_redirect";
}

//获取数据表里存的access_token(和授权登录不同)
public function get_access_token(){
   $accessToken = db('access_token')->where('id',1)->find();
   if($accessToken){
      if($accessToken['stop_time'] > time()) return $accessToken['access_token'];
   else{
   $accessToken =$this->getAccessToken2();
   if(isset($accessToken['access_token'])){
      $data['access_token'] = $accessToken['access_token'];
      $data['stop_time'] = bcadd(7200,time(),0);
      db('access_token')->where('id',1)->update($data);
   }
}
}else{
   $accessToken =$this->getAccessToken2();
   if(isset($accessToken['access_token'])){
      $data['access_token'] = $accessToken['access_token'];
      $data['stop_time'] = bcadd(7200,time(),0);
      db('access_token')->insert($data);
   }
}
   return $accessToken['access_token'];
}
//获取access_token(和授权登录不同)
public function getAccessToken2(){
   $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
   return json_decode(file_get_contents($url),true);
}
//获取access_token存入数据表
public function getAccessToken3(){
   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
   $accessToken = json_decode(file_get_contents($url),true);
   $data['access_token'] = $accessToken['access_token'];
   $data['stop_time'] = bcadd(7200,time(),0);
   db('access_token')->where('id',1)->update($data);
   return $accessToken['access_token'];
}
//获取数据表里存的ticket
public function get_ticket(){
   $ticket = db('access_token')->where('id',1)->find();
   if($ticket){
      if($ticket['stop_time2'] > time()) return $ticket['ticket'];
   else{
      $ticket =$this->getTicket();
      if(isset($ticket['ticket'])){
      $data['ticket'] = $ticket['ticket'];
      $data['stop_time2'] = bcadd(7200,time(),0);
      db('access_token')->where('id',1)->update($data);
   }
}
}else{
   $ticket =$this->getTicket();
   if(isset($ticket['getTicket'])){
      $data['ticket'] = $ticket['ticket'];
      $data['stop_time2'] = bcadd(7200,time(),0);
      db('access_token')->insert($data);
   }
}
   return $ticket['ticket'];
}
//获取ticket
public function getTicket(){
   $accessToken =$this->get_access_token();
   $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' .$accessToken. '&type=jsapi';
   return json_decode(file_get_contents($url),true);
}
//微信分享需要的参数
public function wxshare(){
   $access_token =$this->get_access_token();
   $ticket =$this->get_ticket();
   $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
   $ticketJson = $this->requestGet($ticketUrl);
   $res2 = json_decode($ticketJson,true);
   $currentUrl = request()->url(true);
   $nonceStr = "";
   $time = time();
   $signature = sha1("jsapi_ticket=".$ticket."&noncestr=".$nonceStr."&timestamp=".$time."&url=".$currentUrl);
   $wxConfig = [
      'appId' => $this->appid,
      'timestamp' => $time,
      'nonceStr' => $nonceStr,
      'signature' => $signature,
   ];
   return $wxConfig;
}
public function requestGet($url){
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURLOPT_URL, $url);
   $json = curl_exec($ch);
   curl_close($ch);
   return $json;
}
}

?>

 

前端页面分享js:

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

<script>

//获取文章标题

ftit = '{$setting.keywords}';

//获取网页中内容的图片地址作为分享图

flink = document.images[2].src;

if(flink){

lk = flink;

}else{

//获取网页中内容的图片地址作为分享图

lk = document.images[1].src;

}
href = document.location.href.split("?")[0];
link = href;
desc = '描述';

wx.config({

debug: false,

appId: '{$wxconfig.appId}', // 必填,公众号的唯一标识

timestamp: '{$wxconfig.timestamp}', // 必填,生成签名的时间戳

nonceStr: '{$wxconfig.nonceStr}', // 必填,生成签名的随机串

signature: '{$wxconfig.signature}',// 必填,签名,见附录1

jsApiList : [

'updateTimelineShareData', //分享到朋友圈

'updateAppMessageShareData', //分享给微信朋友

] // 必填,需要使用的JS接口列表

});

wx.ready(function () {

// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容

wx.updateTimelineShareData({

title: ftit, // 名

link: link, // 地址

imgUrl: lk, // 分享的图标

success: function () {

// 用户确认分享后执行的回调函数

},

cancel: function () {

// 用户取消分享后执行的回调函数

}

});

//自定义“分享给朋友”及“分享到QQ”按钮的分享内容

wx.updateAppMessageShareData({

title: ftit, // 名

link: link, // 地址

imgUrl: lk, // 分享的图标

desc: desc, // 分享描述

});

});

</script>

posted @ 2021-03-16 16:22  小小强丶  阅读(428)  评论(0编辑  收藏  举报