php实现微信授权登录

一、 微信授权方法:
public function wxAuth()
{
$this->load->model(‘Wxapi_model’);
o p e n i d = i s s e t ( openid = isset( openid=isset(_COOKIE[‘uid’])? C O O K I E [ ′ u i d ′ ] : ′ ′ ; i f ( _COOKIE['uid']:''; if( COOKIE[uid]:;if(openid){
//已授权
//todo something
}else{
$code = $this->input->get_post(‘code’);
$state = $this->input->get_post(‘state’);

		 if ($code && $state) {
            //获取openid
            $token_json = $this->Wxapi_model->getOpenId($code);
            if (isset($token_json->openid)) {
                $openid = $token_json->openid;
                //设置cookie                    
                setcookie("uid",$openid,60*60*24);
               //todo something
            }
            return true;
        }
        //动态获取url
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";// 动态获取当前地址
        $param = time();
        //微信网页版应用 获取code
        $this->Wxapi_model->getCodeUrl($url, $param,2);
        return true;
    }

}

二、Wxapi_model.php 代码 封装了微信公众号接口常用功能

<?php /** * 微信公众号接口常用功能 * * 配置要使用的微信帐号 initConfig($AppId,$AppSecret) * 微信网页授权中转url,返回时带code getCodeUrl($url,$param) * 微信网页根据code获取用户openid getOpenId($code) * 获取js版本api页面配置信息 getJsSignPage() * 通过接口获取微信用户信息 getUnionInfo($openid) * 微信网页获取用户基础信息 getUserInfo($openid) */ class Wxapi_model extends CI_Model{ //微信配置 测试账号 private $wxappId = '你的appID'; private $wxappSecret = '你的appSecret'; //接口初始化 function __construct() { parent::__construct(); } //更新配置 public function initConfig($AppId,$AppSecret){ $this->wxappId = $AppId; $this->wxappSecret = $AppSecret; } //-----------------------------------------------------------------------// /**************************************************** { "touser":"omaV1w6o7V2LpSvIWSVsqec694Co", "template_id":"6td1AjaST60hzdx8RVOjkn17GYqOvCnhD4y_GsY5v7s", "url":"http://www.lyhand.com/webapp/gmtj/comment_manage/check", "data":{ "pnum": { "value":"12", "color":"#173177" } } } { "errcode":0, "errmsg":"ok", "msgid":461887685 } ****************************************************/ //发送模板消息 公众号使用 public function sendTplMsg($openid,$tpl_id,$tpl_url,$tpl_data){ $access_token = self::getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token; $body = (object)array( "touser"=>$openid, "template_id"=>$tpl_id, "url"=>$tpl_url, "data"=>$tpl_data ); $content = ''.json_encode($body); $json = $this->httpPost($url,$content); $data = $json ? json_decode($json) : null; return $data; } //发送模板消息 小程序中使用 //$form_id 为formId或prepayId public function sendWXAppTplMsg($openid,$tpl_id,$tpl_data,$app_page,$form_id){ $access_token = self::getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token; #$tpl_url = 'https://majiang.app0379.com/tools/wmj/guide/100000?mid=3&from=web'; $body = (object)array( "touser"=>$openid, "template_id"=>$tpl_id, "page"=>$app_page, 'form_id'=>$form_id, #"url"=>$tpl_url, "data"=>$tpl_data ); $content = ''.json_encode($body); $json = $this->httpPost($url,$content); $data = $json ? json_decode($json) : null; return $data; } //-----------------------------------------------------------------------// public function getUserList($next_openid=""){ //ACCESS_TOKEN& $access_token = self::getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid='.$next_openid; $json = $this->httpGet($url); $data = $json ? json_decode($json) : null; return $data; } /**************************************************** { "subscribe": 1, "openid": "OPENID", "nickname": "NICKNAME", "sex": 1, "language": "zh_CN", "city": "CITY", "province": "PROVINCE", "country": "COUNTRY", "headimgurl": "HEADIMGURL", "subscribe_time": 1482133529, "unionid": "UNIONID" "remark": "", "groupid": 0 } ****************************************************/ /** * 通过接口获取微信用户信息 * @param $openid * @return mixed|null */ public function getUnionInfo($openid){ $access_token = self::getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; $json = $this->httpGet($url); $data = $json ? json_decode($json) : null; return $data; } /**************************************************** { "openid":" OPENID", "nickname": NICKNAME, "sex":"1", "province":"PROVINCE" "city":"CITY", "country":"COUNTRY", "headimgurl":"HEADIMGURL", "privilege":[PRIVILEGE1,PRIVILEGE2], "unionid": "UNIONID" } ****************************************************/ /** * 微信网页版应用,获取用户基础信息 * @param $token string * @param $openid string * @return mixed|null */ public function getUserInfo($openid){ $token = self::getAccessToken("web"); $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN'; $json = $this->httpGet($url); $data = $json ? json_decode($json) : null; return $data; } private function make_midas_param($data){ ksort($data); $str = ""; foreach ($data as $k => $v) { if ($v && trim($v) != '') { $str .= "$k=$v&"; } } return $str ? substr($str,0,-1) : ""; } public function getMDSBalance($wx_openId,$wx_session){ $MDSKey = 'ErjAyGBlZXHHrwcVsXwYiMl1hgdUuHe2'; $token = self::getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/midas/getbalance?access_token='.$token; $content = array( 'appid' => $this->wxappId, 'openid' => $wx_openId, 'offer_id' => '1450014921', 'ts' => time(), 'zone_id' => "1", 'pf' => "android", ); $string_a = $this->make_midas_param($content); $string_t = $string_a."&org_loc=/cgi-bin/midas/getbalance&method=POST&secret=".$MDSKey; $content['sig'] = hash_hmac('sha256', $string_t, $MDSKey, false); $content['access_token'] = $token; $string_a = $this->make_midas_param($content); $string_t = $string_a."&org_loc=/cgi-bin/midas/getbalance&method=POST&session_key=".$wx_session; $content['mp_sig'] = hash_hmac('sha256', $string_t, $wx_session, false); $json = $this->httpPost($url,json_encode($content)); if( $this->wx_debug ){ echo " "; } $data = $json ? json_decode($json) : null; if( $this->wx_debug ){ echo " "; } return $data; } /**************************************************** { "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", //need "scope":"SCOPE", "unionid": "UNIONID" } ****************************************************/ /** * 微信网页版应用,内部根据code获取用户openid及access_token * * @param $code string * @return mixed|null */ public function getOpenId($code){ $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'. 'appid='.$this->wxappId.'&secret='.$this->wxappSecret.'&code='.$code. '&grant_type=authorization_code'; $json = $this->httpGet($url); $data = $json ? json_decode($json) : null; if( $data && isset($data->access_token) ){ //获取openid的同时token被刷新 $this->setAccessToken($data->access_token,"web"); }else{ //todo 提示 } return $data; } //微信网页版应用,授权中转url,返回时带code public function getCodeUrl($wxReturnUrl,$param,$base=1){ $STATE = $param ? $param : 'state128long'; if($base==1){ $SCOPE = 'snsapi_base'; //静默授权(默认授权) }else{ $SCOPE = 'snsapi_userinfo'; //会出现授权页面 } $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?'. 'appid='.$this->wxappId.'&redirect_uri='.urlEncode($wxReturnUrl). '&response_type=code&scope='.$SCOPE.'&state='.$STATE.'#wechat_redirect'; header("Location:" . $url); return; } //-----------------------------------------------------------------------// /** * 获取微信的js版本api页面配置信息 * @return array */ public function getJsSignPage($url_param="") { $jsapiTicket = self::getJsApiTicket(); // 注意 URL 一定要动态获取,不能 hardcode. $protocol = "http://"; if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443){ $protocol = "https://"; } $url = $url_param?:$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //时间戳及随机串 $timestamp = time(); $nonceStr = self::getNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPage = array( "appId" => $this->wxappId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPage; } /** * 获取微信签名用随机字符串 * @param int $length * @return string */ private function getNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } /** * 获取微信的js版本api签名 * @return string */ public function getJsApiTicket() { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $cache_path = APPPATH."config/wx/".$this->wxappId."-jsapi_ticket.json"; $json = is_file($cache_path) ? file_get_contents($cache_path) : ""; $data = $json ? json_decode($json) : new stdClass(); $time = time(); if( !isset($data->jsapi_ticket) || $data->expire_time < $time ){ $accessToken = self::getAccessToken(); // 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; // 一般帐号使用此URL获取 $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode(self::httpGet($url)); $ticket = isset($res->ticket) ? $res->ticket : ""; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen($cache_path, "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } /** * 获取微信的access_token,有效期2小时 * @return string */ public function getAccessToken($type="api") { // access_token 应该全局存储与更新 $cache_path = APPPATH."config/wx/".$this->wxappId. ($type=="api"?"":"-".$type) ."-access_token.json"; $json = is_file($cache_path) ? file_get_contents($cache_path) : ""; $data = $json ? json_decode($json) : new stdClass(); $time = time(); if( !isset($data->access_token) || $data->expire_time < $time ){ // 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$wxappId."&corpsecret=".$wxappSecret; // 一般帐号使用此URL获取 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential". "&appid=".$this->wxappId."&secret=".$this->wxappSecret; $res = json_decode(self::httpGet($url)); if( $this->wx_debug ){ echo " "; } $access_token = isset($res->access_token) ? $res->access_token : ""; if ($access_token) { $data->expire_time = $time + 3600; $data->access_token = $access_token; $fp = fopen($cache_path, "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data->access_token; if( $this->wx_debug ){ echo " "; } } return $access_token; } public function setAccessToken($access_token,$type="web"){ // access_token 应该全局存储与更新 $cache_path = APPPATH."config/wx/".$this->wxappId. ($type=="api"?"":"-".$type) ."-access_token.json"; $json = is_file($cache_path) ? file_get_contents($cache_path) : ""; $data = $json ? json_decode($json) : new stdClass(); $time = time(); if($access_token){ $data->expire_time = $time + 7000; $data->access_token = $access_token; $fp = fopen($cache_path, "w"); fwrite($fp, json_encode($data)); fclose($fp); } } /** * 简易访问网页,get方式 * @param $url string 要访问的网址 * @return mixed */ private function httpGet($url) { $ch = curl_init(); //设置header curl_setopt($ch, CURLOPT_HEADER, FALSE); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //设置超时 curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置证书 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //设置网址 #curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_URL, $url); //运行 $res = curl_exec($ch); $error = curl_error($ch); curl_close($ch); //结果 if ( empty($error) ) { return $res; } else { #echo "curl出错:$error"; return false; } } /** * 简易访问网页,post方式 * @param $url * @param $content * @return bool|mixed */ private function httpPost($url, $content){ $ch = curl_init(); //设置 curl_setopt($ch, CURLOPT_HEADER,false); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_TIMEOUT,10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POST,true); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS,$content); //运行 $res = curl_exec($ch); $error = curl_error($ch); curl_close($ch); //结果 if ( empty($error) ) { return $res; } else { #echo "curl出错:$error"; return false; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值