微信入口、生成菜單,公眾號授權獲取用戶信息(unionid)


本篇主要存儲一次原來自己使用的微信公眾號開發的一些小功能

比較常用的為配置微信入口、生成菜單、已經授權登錄獲取用戶信息一些小功能。

不過,最好還是多看微信開發文檔。文檔地址:跳轉微信開發文檔

不多說什么了,直接上代碼:

<?php
namespace app\index\controller;
/**
 *微信接入類
 */
use think\Controller;

define("TOKEN", "TOKEN");          #微信公眾號 TOKEN

class Wx  extends Controller
{
    var $appid     = 'APPID';      #微信公眾號appid
    var $appsecret = 'APPSECRET';  #微信公眾號appsecret

    #微信入口驗證
    public function valid()
    {
        $echoStr = isset($_GET["echostr"])?$_GET["echostr"]:null;

        if($this->checkSignature()){
            echo $echoStr;
            //exit;
        }
        // else{
        //     $this->responseMsg();
        // }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    #獲取 基礎 Access_token  
    public function get_access_token()
    {
#accestoken有7200秒時效,獲取后請盡量找地方存儲,不要每次調用每次獲取
#下面是我存儲的accesstoken與失效時間,各位看官大大可以自由存儲
$accesstoken = getConfigValue('accesstoken'); $tokentime = getConfigValue('tokentime'); #如果token 的時間已經小於當前時間, 從新獲取 if($tokentime < time()) { #獲取配置參數 $appId = $this->appid; $appSecret = $this->appsecret; //獲取access_token字符串 $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret; // 如果是企業號用以下URL獲取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $res = $this->https_request($tokenUrl); //提取access_token字符串 解析json字符串 $data = json_decode($res, true); #修改對應存儲 model('config')->where('code','accesstoken')->update(['value'=>$data['access_token']]); model('config')->where('code','tokentime')->update(['value'=>time()+7000]); $tokens = $data['access_token']; }else{ $tokens = $accesstoken; } // return $data['access_token']; return $tokens; } #生成菜單 public function makeMenu() { $accessToken = $this->get_access_token(); // $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$accessToken; $data = ' { "button":[ { "type": "view", "name": "單級菜單", "url": "對應路徑" }, { "name":"多級菜單", "sub_button":[ { "type":"view", "name":"一級菜單", "url":"最多三個" }, { "type":"view", "name":"二級菜單", "url":"最多五個" } ] } ] }'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { echo curl_error($ch); } curl_close($ch); echo $tmpInfo; } #授權第一步 獲取code public function getReturn() { $appid = $this->appid; #回調地址 $redirect_uri = '回調路徑'; #如果拼接字符串 $data = []; $data[0] = $_GET['state']; if(!empty($_GET['recode'])) { $data[1] = $_GET['recode']; } $state = implode(",",$data); #請求授權 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$redirect_uri."response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect"; header("Location:$url"); die; } #授權登錄 並獲取授權用戶信息 public function getUserCode() { $appid = $this->appid; $secret = $this->appsecret; $code = $_GET["code"]; #獲取授權用戶對應的openid $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code'; $json_obj = json_decode(file_get_contents($get_token_url,true),true); #獲取授權用戶信息 $openid = $json_obj['openid']; // $access_token = $json_obj['access_token']; // $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$json_obj['access_token'].'&openid='.$openid.'&lang=zh_CN'; #帶有unionid 的授權用戶信息 -- 帶有unionid 必須用基礎access_token 來獲取 $accessToken = $this->get_access_token(); $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accessToken.'&openid='.$openid.'&lang=zh_CN'; #獲得用戶的信息 $user_obj = json_decode(file_get_contents($get_user_info_url,true),true); $res = explode(',', $_GET['state']); #對應用戶的state[0] 來指定跳轉的路徑 $loginUrl = "重定向路徑"; #根據openid 來查找對應的用戶信息 #進行其他操作 #進行重定向 $this->redirect($loginUrl); } # request 請求 private function https_request($url, $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } }

 

在剛開始微信開發的時候這個類庫幫我不少。

有需要的小伙伴可以借鑒。

如有疑問可以留言

大家共同進步哈。

2020年04月21日


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM