JssdkClient.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  23. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  24. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  25. * @throws \Psr\SimpleCache\InvalidArgumentException
  26. */
  27. public function getTicket(bool $refresh = false, string $type = 'wx_card'): array
  28. {
  29. return parent::getTicket($refresh, $type);
  30. }
  31. /**
  32. * 微信卡券:JSAPI 卡券发放.
  33. *
  34. * @return string
  35. */
  36. public function assign(array $cards)
  37. {
  38. return json_encode(array_map(function ($card) {
  39. return $this->attachExtension($card['card_id'], $card);
  40. }, $cards));
  41. }
  42. /**
  43. * 生成 js添加到卡包 需要的 card_list 项.
  44. *
  45. * @param string $cardId
  46. *
  47. * @return array
  48. *
  49. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  50. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  51. * @throws \Psr\SimpleCache\InvalidArgumentException
  52. */
  53. public function attachExtension($cardId, array $extension = [])
  54. {
  55. $timestamp = time();
  56. $nonce = str_random(6);
  57. $ticket = $this->getTicket()['ticket'];
  58. $ext = array_merge(['timestamp' => $timestamp, 'nonce_str' => $nonce], Arr::only(
  59. $extension,
  60. ['code', 'openid', 'outer_id', 'balance', 'fixed_begintimestamp', 'outer_str']
  61. ));
  62. $ext['signature'] = $this->dictionaryOrderSignature($ticket, $timestamp, $cardId, $ext['code'] ?? '', $ext['openid'] ?? '', $nonce);
  63. return [
  64. 'cardId' => $cardId,
  65. 'cardExt' => json_encode($ext),
  66. ];
  67. }
  68. }