Laravel封装微信小程序登录以及服务端获取accesstoken

2024-06-03 02:59:16   2025-12-28 07:17:38   PHP   193 views  

  wechat  

App/Http/Api/WeChatController(注意config('services.socialite.wechat_mini.appid')和 config('services.socialite.wechat_mini.secret')要在config文件以及.env文件内配置好)

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class WeChatController extends Controller
{

    /**
     * @var string
     */
    private $wechat_miniapp_url;
    /**
     * @var string
     */
    private $wechat_miniapp_getaccesstoken_url;

    /**
     *基础url
     */
    public function __construct()
    {
        //授权登录
        $this->wechat_miniapp_url = "https://api.weixin.qq.com/sns/jscode2session";
        //获取AccessToken
        $this->wechat_miniapp_getaccesstoken_url = "https://api.weixin.qq.com/cgi-bin/token";
    }

    /**
     * 小程序code登录获取openid以及session_key
     * @param Request $request
     * @return mixed
     */
    public function jscode2session(Request $request)
    {
        $data = [
          'appid' => config('services.socialite.wechat_mini.appid'),
          'secret' => config('services.socialite.wechat_mini.secret'),
          'js_code' => $request->code,
          'grant_type' => 'authorization_code'
        ];
        // 使用 http_build_query() 函数将查询参数数组转换为 URL 编码的字符串
        $queryString = http_build_query($data);

        // 将查询字符串附加到基础 URL 上
        $fullUrl = $this->wechat_miniapp_url . '?' . $queryString;
        $request = json_decode(Http::get($fullUrl));
        return $request;

    }

    /**
     * 小程序获取access_token
     * @return \Illuminate\Cache\CacheManager|\Illuminate\Contracts\Foundation\Application|mixed|null
     * @throws \Exception
     */
    public function getAccessToken()
    {
        // 检查缓存中是否已有有效的token
        $cachedToken = cache('wechat_miniapp_access_token');

        // 检查缓存的token是否存在且未超过3600秒
        if ($cachedToken && cache('wechat_miniapp_access_token_time') <= now()) {
            return $cachedToken;
        }

        // 配置数据
        $data = [
            'grant_type' => 'client_credential',
            'appid' => config('services.socialite.wechat_mini.appid'),
            'secret' => config('services.socialite.wechat_mini.secret'),
        ];

        // 使用 http_build_query() 函数将查询参数数组转换为 URL 编码的字符串
        $queryString = http_build_query($data);

        // 将查询字符串附加到基础 URL 上
        $fullUrl = $this->wechat_miniapp_getaccesstoken_url . '?' . $queryString;

        // 发送 HTTP GET 请求
        $response = json_decode(Http::get($fullUrl), true);

        // 存储新的token及当前时间
        if (isset($response['access_token'])) {
            cache(['wechat_miniapp_access_token' => $response['access_token']]);
            cache(['wechat_miniapp_access_token_time' => now()->addSeconds($response['expires_in']/2)]);

            return $response['access_token'];
        }

        return null; // 如果没有获取到token,则返回null
    }

}