JssdkClient.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace EasyWeChat\OfficialAccount\Card;
  11. use EasyWeChat\BasicService\Jssdk\Client as Jssdk;
  12. use EasyWeChat\Kernel\Support\Arr;
  13. use function EasyWeChat\Kernel\Support\str_random;
  14. /**
  15. * Class Jssdk.
  16. *
  17. * @author overtrue <i@overtrue.me>
  18. */
  19. class JssdkClient extends Jssdk
  20. {
  21. /**
  22. * @param bool $refresh
  23. * @param string $type
  24. *
  25. * @return array
  26. *
  27. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  28. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  29. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  30. * @throws \Psr\SimpleCache\InvalidArgumentException
  31. */
  32. public function getTicket(bool $refresh = false, string $type = 'wx_card'): array
  33. {
  34. return parent::getTicket($refresh, $type);
  35. }
  36. /**
  37. * 微信卡券:JSAPI 卡券发放.
  38. *
  39. * @param array $cards
  40. *
  41. * @return string
  42. */
  43. public function assign(array $cards)
  44. {
  45. return json_encode(array_map(function ($card) {
  46. return $this->attachExtension($card['card_id'], $card);
  47. }, $cards));
  48. }
  49. /**
  50. * 生成 js添加到卡包 需要的 card_list 项.
  51. *
  52. * @param string $cardId
  53. * @param array $extension
  54. *
  55. * @return array
  56. *
  57. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  58. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  59. * @throws \Psr\SimpleCache\InvalidArgumentException
  60. */
  61. public function attachExtension($cardId, array $extension = [])
  62. {
  63. $timestamp = time();
  64. $nonce = str_random(6);
  65. $ticket = $this->getTicket()['ticket'];
  66. $ext = array_merge(['timestamp' => $timestamp, 'nonce_str' => $nonce], Arr::only(
  67. $extension,
  68. ['code', 'openid', 'outer_id', 'balance', 'fixed_begintimestamp', 'outer_str']
  69. ));
  70. $ext['signature'] = $this->dictionaryOrderSignature($ticket, $timestamp, $cardId, $ext['code'] ?? '', $ext['openid'] ?? '', $nonce);
  71. return [
  72. 'cardId' => $cardId,
  73. 'cardExt' => json_encode($ext),
  74. ];
  75. }
  76. }