Wechat.php 2.0 KB
<?php
/**
 * @remark :
 * @name   :Wechat.php
 * @author :lyh
 * @method :post
 * @time   :2023/8/23 18:18
 */

namespace App\Helper;

use \GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

/**
 * @remark :微信相关
 * @name   :Wechat
 * @author :lyh
 * @method :post
 * @time   :2023/8/23 18:19
 */
class Wechat
{
    public $alias = 'global6.0';
    public $appid = 'wx8253a38fd7ae78f0';
    public $appSecret = '20981cca3d00c074a8886f115d19548d';

    /**
     * @remark :生成access_token
     * @name   :getAccessToken
     * @author :lyh
     * @method :post
     * @time   :2023/8/23 18:28
     */
    public function getAccessToken()
    {
        $cacheKey = 'access_token';
        if (Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->appSecret;
        $client = new Client();
        $response = $client->get($url);
        $data = json_decode($response->getBody(), true);
        $accessToken = $data['access_token'];
        // 将accessToken缓存起来,避免多次请求
        Cache::put($cacheKey, $accessToken, $data['expires_in'] / 60);
        return $accessToken;
    }
    /**
     * @remark :生成二维码
     * @name   :setQrcode
     * @author :lyh
     * @method :post
     * @time   :2023/8/23 18:19
     */
    public function setQrcode($type,$accessToken){
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $accessToken;
        $client = new Client();
        $response = $client->post($url, [
            'json' => [
                'expire_seconds' => 3600,
                'action_name' => 'QR_STR_SCENE',
                'action_info' => [
                    'scene' => [
                        'scene_str' => $type.uniqid().$this->alias,
                    ],
                ],
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }

}