123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace App\Service;
- use App\RedisModel;
- class MiniProgramService
- {
- const ACCESS_TOKEN_RDS = 'Playlet::MiniProgramToken_';
- /**
- * 生成小程序SchemeUrl
- * */
- public static function createSchemeUrl($appid, $appSecret, $queryParam)
- {
- # 获取accessToken
- $accessToken = MiniProgramService::getAccessToken($appid, $appSecret);
- if(empty($accessToken)) {
- return false;
- }
- $postData = [
- 'jump_wxa' => [
- 'path' => '',
- 'query' => empty($queryParam) ? '' : http_build_query($queryParam),
- ],
- 'expire_type' => 1,
- 'expire_interval' => 30,
- ];
- $requestUri = config('miniProgram.get_url_scheme');
- $requestUri .= $accessToken;
- $response = HttpService::httpPost($requestUri, json_encode($postData));
- $responseData = json_decode($response, true);
- return $responseData;
- }
- /**
- * 生成小程序LinkUrl
- * */
- public static function createLinkUrl($appid, $appSecret)
- {
- # 获取accessToken
- $accessToken = MiniProgramService::getAccessToken($appid, $appSecret);
- if(empty($accessToken)) {
- return false;
- }
- $postData = [
- 'path' => '',
- 'query' => '',
- 'expire_type' => 1,
- 'expire_interval' => 30,
- ];
- $requestUri = config('miniProgram.get_url_link');
- $requestUri .= $accessToken;
- $response = HttpService::httpPost($requestUri, json_encode($postData));
- $responseData = json_decode($response, true);
- return $responseData;
- }
- /**
- * 获取小程序accessToken
- * */
- public static function getAccessToken($appid, $appSecret)
- {
- $rdsKey = MiniProgramService::ACCESS_TOKEN_RDS . $appid;
- $accessToken = RedisModel::get($rdsKey);
- if(empty($accessToken)) {
- $responseData = MiniProgramService::refreshToken($appid, $appSecret);
- if(isset($responseData['errcode']) && $responseData['errcode']) {
- # 发送报警信息,记录日志
- return false;
- }
- $accessToken = $responseData['access_token'] ?? false;
- $expiresIn = $responseData['expires_in'] ?? -1;
- RedisModel::set($rdsKey, $accessToken);
- RedisModel::expire($rdsKey, $expiresIn);
- }
- return $accessToken;
- }
- /**
- * 刷新accessToken
- * */
- public static function refreshToken($appid, $appSecret)
- {
- $requestUri = config('miniProgram.get_token');
- $requestUri .= 'appid='.$appid.'&secret='.$appSecret;
- $response = HttpService::httpGet($requestUri);
- $responseData = json_decode($response, true);
- return $responseData;
- }
- }
|