ByteDance.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. namespace App\Helper;
  3. use App\Helper\UniPlatform\BaseAPI;
  4. use App\Helper\UniPlatform\BaseUniPlatform;
  5. use Carbon\Carbon;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. /**
  9. * Class ByteDance
  10. *
  11. * @package App\Helper
  12. * @property-read string $appId
  13. * @property-read string $slat
  14. * @property-read string $secret
  15. * @property-read string $token
  16. * @property-read string $accessTokenFile
  17. * @property-read string $accessToken
  18. * @property-read string $noticeUrl
  19. * @property-read string $validTimestamp
  20. */
  21. class ByteDance extends BaseUniPlatform
  22. {
  23. public function __construct(BaseAPI $api)
  24. {
  25. $this->API = $api;
  26. }
  27. /**
  28. * 获取 access token
  29. * @throws \Exception
  30. */
  31. protected function getAccessToken() : string
  32. {
  33. $res = $this->post($this->API::ACCESS_TOKEN, [
  34. 'grant_type' => 'client_credential',
  35. 'appid' => $this->appId,
  36. 'secret' => $this->secret,
  37. ]);
  38. if (!empty($res['err_no'])) {
  39. throw new \Exception('获取access token 错误');
  40. }
  41. file_put_contents($this->accessTokenFile, json_encode([
  42. 'access_token' => $res['access_token'],
  43. 'expires_at' => $res['expiresAt']
  44. ]));
  45. return $res['access_token'];
  46. }
  47. /**
  48. * @param $outOrderNo
  49. * @param $totalAmount
  50. * @param $openId
  51. * @return array|mixed
  52. * @throws \Exception
  53. */
  54. public function createOrder($outOrderNo, $totalAmount, $openId): array
  55. {
  56. $data = [
  57. 'app_id' => $this->appId,
  58. 'out_order_no' => $outOrderNo,
  59. 'total_amount' => intval($totalAmount * 100),
  60. 'subject' => "订单号:".$outOrderNo,
  61. 'body' => '抖音担保支付',
  62. 'valid_time' => $this->validTimestamp,
  63. 'sign' => $this->secret
  64. //'notify_url' => $notifyUrl, // 可以不设置 使用小程序后台设置的回调
  65. ];
  66. $data = array_filter($data);
  67. $data['sign'] = $this->getSign($data);
  68. return $this->post(
  69. $this->API::CREATE_ORDER,
  70. $data
  71. );
  72. }
  73. /**
  74. * @param array $data
  75. * @return string
  76. */
  77. public function getSign(array $data)
  78. {
  79. $rList = [];
  80. foreach ($data as $k => $v) {
  81. if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
  82. continue;
  83. $value = trim(strval($v));
  84. $len = strlen($value);
  85. if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
  86. $value = substr($value, 1, $len - 1);
  87. $value = trim($value);
  88. if ($value == "" || $value == "null")
  89. continue;
  90. array_push($rList, $value);
  91. }
  92. array_push($rList, $this->slat);
  93. sort($rList, SORT_STRING);
  94. return md5(implode('&', $rList));
  95. }
  96. /**
  97. * @param array $data
  98. * @return string
  99. */
  100. public function getNotifySign(array $data)
  101. {
  102. $filtered = [];
  103. foreach ($data as $key => $value) {
  104. if (in_array($key, ['msg_signature', 'type'])) {
  105. continue;
  106. }
  107. $value = trim(strval($value));
  108. $len = strlen($value);
  109. if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
  110. $value = substr($value, 1, $len - 1);
  111. $filtered[] =
  112. is_string($value)
  113. ? trim($value)
  114. : $value;
  115. }
  116. $filtered[] = trim($this->token);
  117. sort($filtered, SORT_STRING);
  118. return sha1(trim(implode('', $filtered)));
  119. }
  120. public function pushOrder($openid, $orderId, $goods)
  121. {
  122. $data = [
  123. 'access_token' => $this->accessToken,
  124. 'open_id' => $openid,
  125. 'order_type' => 0, // 0:普通小程序订单(非 POI 订单),
  126. 'order_detail' => [
  127. 'order_id' => $orderId,
  128. 'create_time' => (int)Carbon::now()->getPreciseTimestamp(3),
  129. 'status' => '已支付',
  130. 'amount' => 1,
  131. 'total_price' => '',
  132. 'detail_url' => 'pages/my/consume',
  133. 'item_list' => [
  134. 'item_code' => $goods['id'], // 商品ID,
  135. 'img' => $goods['img'],
  136. 'title' => $goods['title'],
  137. 'price' => $goods['price'],
  138. ]
  139. ],
  140. 'update_time' => (int)Carbon::now()->getPreciseTimestamp(3)
  141. ];
  142. return $this->post($this->API::ORDER_PUSH, $data);
  143. }
  144. /**
  145. * @param string $code
  146. * @return array|mixed
  147. * @throws \Exception
  148. */
  149. public function login($code = ''): array
  150. {
  151. return $this->post($this->API::LOGIN, [
  152. 'appid' => $this->appId,
  153. 'secret' => $this->secret,
  154. 'code' => $code,
  155. ]);
  156. }
  157. /**
  158. * 接口请求
  159. *
  160. * @param string $uri
  161. * @param array $data
  162. * @return array|mixed
  163. * @throws \Exception
  164. */
  165. protected function post($uri = '', $data = []) : array
  166. {
  167. try {
  168. $client = new Client();
  169. $res = $client->post($uri, [
  170. 'verify' => false,
  171. 'headers' => ['Content-Type' => 'application/json'],
  172. 'body' => json_encode($data)
  173. ]);
  174. $stringBody = (string)$res->getBody();
  175. $res = json_decode($stringBody, true);
  176. if(!empty($res['err_no'])){
  177. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_no']},错误信息:{$res['err_tips']}");
  178. }
  179. return $res['data'];
  180. } catch (GuzzleException $e) {
  181. \Log::error($e->getMessage());
  182. throw new \Exception($e->getMessage());
  183. }
  184. }
  185. protected function setAccessFileDir(): void
  186. {
  187. $this->accessTokenDir = storage_path('app/bytedance');
  188. }
  189. protected function setAccessFilePath(): void
  190. {
  191. $this->accessTokenFile = storage_path('app/bytedance/bytedance_access_token.json');
  192. }
  193. protected function setNoticeUrl(): void
  194. {
  195. $this->noticeUrl = env('APP_URL').'/api/pay/bytedance/notify';
  196. }
  197. }