laravel微信公众号开发

发布时间:2020-12-25 19:09:30 阅读:1336次

之前用php开发过微信公众号

首先需要登录公众号,启用服务器配置

填写链接

点击开发|接口权限|网页授权

因为用的是laravel框架

设置路由

Route::any('weixin/verify', 'API\WeixinController@index');
Route::any('weixin/oauth', 'API\WeixinController@oauth');
Route::any('weixin/qrcode/{game_id}', 'API\WeixinController@qrcode');
Route::any('weixin/checkunion', 'API\WeixinController@checkunion');

然后创建controller

<?php namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cookie;
use App\User;
use App\Game;
use ZM\ApiResponse\Facades\ApiResponse;
class WeixinController extends Controller
{
    function __construct()
    {
        $appid="wx1***ade58";
        $secret="185***afb";
        $ret = json_decode(Redis::get('accesss_token'),true);
        if(!$ret['access_token']){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $res = json_decode($this->httpGet($url),true);
            $access_token = $res['access_token'];
            $data['expire_time'] = time() + 7200;
            $data['access_token'] = $access_token;
            $ret = Redis::set('accesss_token',json_encode($data),'ex',7200);
        }
    }

    public function index(){
        $echoStr = Request::input("echostr");
        if($this->checkSignature()){
            echo $echoStr;
            $postStr = file_get_contents('php://input');
            if (!empty($postStr)){
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $MsgType = $postObj->MsgType;//消息类型
                $ret = json_decode(Redis::get('accesss_token'),true);
                $access_token = $ret['access_token'];
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$fromUsername&lang=zh_CN";
                $result = $this->httpGet($url);
                error_log(print_r($result,1),3,'/tmp/1.txt');
                return ;
            }
        }
    }

     public function checkSignature()
     {
         $signature = Request::input("signature");
         $timestamp = Request::input("timestamp");
         $nonce = Request::input("nonce");
         $token = "weiXin";
         $tmpArr = array($token, $timestamp, $nonce);
         sort($tmpArr, SORT_STRING);
         $tmpStr = implode($tmpArr);
         $tmpStr = sha1($tmpStr);
         if($tmpStr == $signature){
             return true;
         }else{
             return false;
         }
     }

     function httpGet($url,$fields='') {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//输出内容为字符串
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno'.curl_error($curl);
        }
        curl_close($curl);
        return $res;
     }

     function oauth(){
        //Cookie::queue(Cookie::forget('token'));
        //Cookie::queue(Cookie::forget('mobile'));
        //return;
        $url = Request::input('url');
        $name = Request::input('name');
        $terminal_type = Request::input('terminal_type');
        $code = Request::input('code');
        $state = Request::input('state');
        $game_url = $url."&".$name."&terminal_type=".$terminal_type;
        if (isset($code)){
            $oauth2_accesstoken = $this->oauth2_accesstoken($code);
            $array=$this->jsontoarray($oauth2_accesstoken);
            $access_token = $array["access_token"];
            $open_id = $array["openid"];
            $userinfo = $this->oauth2_getinfo($access_token,$open_id);
            $userinfo = json_decode($userinfo,true);
            $unionid = $userinfo['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if($user){
                error_log(print_r($user->toArray(),1),3,'/tmp/1.txt');
                $token = auth()->login($user);
                if(auth()->check()){
                    error_log(print_r('已登录',1),3,'/tmp/1.txt');
                }else{
                    error_log(print_r('未登录',1),3,'/tmp/1.txt');
                }
                Cookie::queue('token', $token, 86400 * env('JWT_TOKEN_LIFE_DAYS', '30'));//分钟
                Cookie::queue('mobile',$user->name, $minutes = 99999999, $path = null, $domain = null, $secure = false, $httpOnly = false);
                header("location:$game_url");
            }else{
                echo "请先在pc上重新登录";
            }
        }else{
            echo "NO CODE";
        }
     }

    public function qrcode(){
        $game_id = Request::route('game_id');
        $game = Game::where('id', $game_id)->first();    
        $game_name = $game->name;
        $terminal_type = $game->terminal_type;
        $game_url = "http://newgame.test.com/gameBox/index.html?game_id=$game_id&name=$game_name&terminal_type=$terminal_type";
        $game_url = urlencode($game_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1***ade58&redirect_uri=http://newgame.test.com/api/weixin/oauth?url=$game_url&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
        header("location:$url");
    }


    function oauth2_accesstoken($code){
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1***ade58&secret=185***afb&code=$code&grant_type=authorization_code";
        $result = $this->httpGet($url);
        return $result;
    }

    function jsontoarray($json){
        $object=json_decode($json);
        $array=get_object_vars($object);
        return $array;
    }

    function oauth2_getinfo($access_token,$open_id){
        $url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open_id&lang=zh_CN";
        $result = $this->httpGet($url);
        return $result;
    }

    function checkunion(){
        $user = auth()->user();
        if(!$user->unionid){
            return ApiResponse::failure('1001', 'unionid为空');
        }else{
            $res['unionid'] = $user->unionid;
            return ApiResponse::success($res);
        }
    }


}

特别提示,路由方法为any,并且中间件去除csrf

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:laravel微信公众号开发 出自老鄢博客 | 欢迎分享