企微短剧业务系统

MiniProgramService.php 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Service;
  3. use App\RedisModel;
  4. class MiniProgramService
  5. {
  6. const ACCESS_TOKEN_RDS = 'Playlet::MiniProgramToken_';
  7. /**
  8. * 生成小程序SchemeUrl
  9. * */
  10. public static function createSchemeUrl($appid, $appSecret, $queryParam)
  11. {
  12. # 获取accessToken
  13. $accessToken = MiniProgramService::getAccessToken($appid, $appSecret);
  14. if(empty($accessToken)) {
  15. return false;
  16. }
  17. $postData = [
  18. 'jump_wxa' => [
  19. 'path' => '',
  20. 'query' => empty($queryParam) ? '' : http_build_query($queryParam),
  21. ],
  22. 'expire_type' => 1,
  23. 'expire_interval' => 30,
  24. ];
  25. $requestUri = config('miniProgram.get_url_scheme');
  26. $requestUri .= $accessToken;
  27. $response = HttpService::httpPost($requestUri, json_encode($postData));
  28. $responseData = json_decode($response, true);
  29. return $responseData;
  30. }
  31. /**
  32. * 生成小程序LinkUrl
  33. * */
  34. public static function createLinkUrl($appid, $appSecret)
  35. {
  36. # 获取accessToken
  37. $accessToken = MiniProgramService::getAccessToken($appid, $appSecret);
  38. if(empty($accessToken)) {
  39. return false;
  40. }
  41. $postData = [
  42. 'path' => '',
  43. 'query' => '',
  44. 'expire_type' => 1,
  45. 'expire_interval' => 30,
  46. ];
  47. $requestUri = config('miniProgram.get_url_link');
  48. $requestUri .= $accessToken;
  49. $response = HttpService::httpPost($requestUri, json_encode($postData));
  50. $responseData = json_decode($response, true);
  51. return $responseData;
  52. }
  53. /**
  54. * 获取小程序accessToken
  55. * */
  56. public static function getAccessToken($appid, $appSecret)
  57. {
  58. $rdsKey = MiniProgramService::ACCESS_TOKEN_RDS . $appid;
  59. $accessToken = RedisModel::get($rdsKey);
  60. if(empty($accessToken)) {
  61. $responseData = MiniProgramService::refreshToken($appid, $appSecret);
  62. if(isset($responseData['errcode']) && $responseData['errcode']) {
  63. # 发送报警信息,记录日志
  64. return false;
  65. }
  66. $accessToken = $responseData['access_token'] ?? false;
  67. $expiresIn = $responseData['expires_in'] ?? -1;
  68. RedisModel::set($rdsKey, $accessToken);
  69. RedisModel::expire($rdsKey, $expiresIn);
  70. }
  71. return $accessToken;
  72. }
  73. /**
  74. * 刷新accessToken
  75. * */
  76. public static function refreshToken($appid, $appSecret)
  77. {
  78. $requestUri = config('miniProgram.get_token');
  79. $requestUri .= 'appid='.$appid.'&secret='.$appSecret;
  80. $response = HttpService::httpGet($requestUri);
  81. $responseData = json_decode($response, true);
  82. return $responseData;
  83. }
  84. }