ByteDance.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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, $status)
  121. {
  122. $data = [
  123. 'access_token' => $this->accessToken,
  124. 'open_id' => $openid,
  125. 'order_type' => 0, // 0:普通小程序订单(非 POI 订单),
  126. 'order_status' => 1,
  127. 'app_name' => 'douyin',
  128. 'update_time' => (int)Carbon::now()->getPreciseTimestamp(3),
  129. 'order_detail' => json_encode([
  130. 'order_id' => $orderId,
  131. 'create_time' => (int)Carbon::now()->getPreciseTimestamp(3),
  132. 'status' => $status, // 已支付 待支付
  133. 'amount' => 1,
  134. 'total_price' => $goods['price'] * 100,
  135. 'detail_url' => 'pages/my/consume',
  136. 'item_list' => [
  137. [
  138. 'item_code' => (string)$goods['id'], // 商品ID,
  139. 'img' => 'https://zhengda.oss-cn-chengdu.aliyuncs.com/zhangsiye/images/26474488be1b83e2fcb0b9475508a9bb.png',
  140. 'title' => $goods['title'],
  141. 'price' => $goods['price'] * 100,
  142. ]
  143. ]
  144. ],JSON_UNESCAPED_UNICODE),
  145. ];
  146. return $this->post($this->API::ORDER_PUSH, $data);
  147. }
  148. /**
  149. * @param string $code
  150. * @return array|mixed
  151. * @throws \Exception
  152. */
  153. public function login($code = ''): array
  154. {
  155. return $this->post($this->API::LOGIN, [
  156. 'appid' => $this->appId,
  157. 'secret' => $this->secret,
  158. 'code' => $code,
  159. ]);
  160. }
  161. /**
  162. * @return array|mixed
  163. * @throws \Exception
  164. */
  165. public function generateQrcode()
  166. {
  167. $userId = \user()->id;
  168. return $this->post($this->API::CREATE_QRCODE, [
  169. 'appname' => 'douyin',
  170. 'access_token' => $this->accessToken,
  171. 'path' =>urlencode('pages/index/index?'."user_id=$userId"),
  172. 'width' => 600,
  173. ]);
  174. }
  175. /**
  176. * 接口请求
  177. *
  178. * @param string $uri
  179. * @param array $data
  180. * @return array|mixed
  181. * @throws \Exception
  182. */
  183. protected function post($uri = '', $data = []) : array
  184. {
  185. try {
  186. $client = new Client();
  187. $res = $client->post($uri, [
  188. 'verify' => false,
  189. 'headers' => ['Content-Type' => 'application/json'],
  190. 'body' => json_encode($data)
  191. ]);
  192. $stringBody = (string)$res->getBody();
  193. $res = json_decode($stringBody, true);
  194. // 生成二维码接口是直接放回 buffer的
  195. if(empty($res) && $uri == $this->API::CREATE_QRCODE){
  196. return [$stringBody];
  197. }
  198. if(isset($res['err_no']) && !empty($res['err_no'])){
  199. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_no']},错误信息:{$res['err_tips']}");
  200. }
  201. if(isset($res['err_code']) && !empty($res['err_code'])){
  202. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_msg']},错误信息:{$res['err_msg']}");
  203. }
  204. return $res['data']?? [];
  205. } catch (GuzzleException $e) {
  206. \Log::error($e->getMessage());
  207. throw new \Exception($e->getMessage());
  208. }
  209. }
  210. protected function setAccessFileDir(): void
  211. {
  212. $this->accessTokenDir = storage_path('app/bytedance');
  213. }
  214. protected function setAccessFilePath(): void
  215. {
  216. $this->accessTokenFile = storage_path('app/bytedance/bytedance_access_token.json');
  217. }
  218. protected function setNoticeUrl(): void
  219. {
  220. $this->noticeUrl = env('APP_URL').'/api/pay/bytedance/notify';
  221. }
  222. }