GdtMpApiService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. /**
  3. * Created by: PhpStorm
  4. * User: lytian
  5. * Date: 2020/4/2
  6. * Time: 13:42
  7. */
  8. namespace app\main\service;
  9. use app\common\library\Redis;
  10. use app\common\library\WeChatObject;
  11. use EasyWeChat\Factory;
  12. use GuzzleHttp\Client as Http;
  13. use GuzzleHttp\Exception\GuzzleException;
  14. use Symfony\Component\Cache\Simple\RedisCache;
  15. use think\Config;
  16. use think\Log;
  17. class GdtMpApiService extends BaseService
  18. {
  19. /**
  20. * 接口地址
  21. * @var string
  22. */
  23. private $bashUrl = 'https://api.weixin.qq.com/marketing/';
  24. /**
  25. * 定义属性
  26. * @var GdtMpApiService
  27. */
  28. protected static $self = null;
  29. /**
  30. * 返回实例
  31. * @return GdtMpApiService
  32. */
  33. public static function instance()
  34. {
  35. if (self::$self == null) {
  36. self::$self = new self();
  37. }
  38. return self::$self;
  39. }
  40. /**
  41. * 获取行为源ID,不存在创建
  42. * @param $adminConfig
  43. * @param $platform_id
  44. * @return bool|int|string
  45. * @throws \GuzzleHttp\Exception\GuzzleException
  46. * @throws \Psr\SimpleCache\InvalidArgumentException
  47. */
  48. public function getUserActionSetId($adminConfig, $platform_id = null)
  49. {
  50. try {
  51. //判断是否已经获取
  52. $key = 'ASAD:WEB:' . $adminConfig['appid'];
  53. if (($id = Redis::instance()->get($key)) !== false) {
  54. return $id;
  55. }
  56. $httpConfig = [
  57. 'base_uri' => $this->bashUrl,
  58. 'connect_timeout' => 10,
  59. 'timeout' => 30,
  60. 'http_errors' => true, //抛出异常 true是 false否
  61. 'verify' => false, //不验证ssl证书
  62. ];
  63. if (!is_null($platform_id)) {
  64. $proxy = OpenPlatformService::instance()->getProxyconfigById($platform_id);
  65. if ($proxy) {
  66. $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
  67. }
  68. } else {
  69. $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($adminConfig['admin_id']);
  70. if ($proxy) {
  71. $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
  72. }
  73. }
  74. $client = new Http($httpConfig);
  75. $weChatConfig = Config::get('wechat');
  76. $weChatConfig['http']['base_uri'] = 'https://api.weixin.qq.com/';
  77. $weChatConfig['app_id'] = $adminConfig['platform_appid'];
  78. $weChatConfig['secret'] = $adminConfig['platform_secret'];
  79. $weChatConfig['token'] = $adminConfig['platform_token'];
  80. $weChatConfig['aes_key'] = $adminConfig['platform_aes_key'];
  81. $openPlatform = Factory::openPlatform($weChatConfig);
  82. $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
  83. $officialAccount = $openPlatform->officialAccount($adminConfig['appid'], $adminConfig['refresh_token']);
  84. $access_token = current($officialAccount->access_token->getToken());
  85. $data = [
  86. 'type' => "WEB",
  87. 'name' => "GDT回传CPS下单",
  88. 'description' => "GDT回传CPS下单",
  89. 'wechat_app_id' => $adminConfig['appid']
  90. ];
  91. $result = $client->request('POST',
  92. "user_action_sets/add?version=v1.0&access_token=$access_token",
  93. [
  94. 'headers' => [
  95. 'Content-Type' => 'application/json',
  96. 'charset' => 'utf-8'
  97. ],
  98. 'body' => json_encode($data)
  99. ]
  100. );
  101. if ($result = json_decode($result->getBody(), true)) {
  102. if (intval($result['errcode'])) {
  103. //失败
  104. if (intval($result['errcode']) == 900351000) {
  105. //已存在时,截取ID,并返回成功
  106. $errMsg = explode(':', $result['errmsg']);
  107. $wx_ad_source_id = intval(end($errMsg)) ?? false;
  108. Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Exists source_id:{$wx_ad_source_id} Data:" . json_encode($result));
  109. //写入redis
  110. Redis::instance()->set($key, $wx_ad_source_id, 86400 * 7);
  111. return $wx_ad_source_id;
  112. } else {
  113. //失败时处理
  114. Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Fail,Error:" . $result['errmsg']);
  115. return false;
  116. }
  117. } else {
  118. //成功
  119. Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Success Data:" . json_encode($result));
  120. //写入redis
  121. $wx_ad_source_id = $result['data']['user_action_set_id'];
  122. Redis::instance()->set($key, $wx_ad_source_id, 86400 * 7);
  123. return $wx_ad_source_id ?: false;
  124. }
  125. }
  126. return false;
  127. } catch (\Exception $e) {
  128. Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Fail,Error:" . $e->getMessage());
  129. return false;
  130. }
  131. }
  132. /**
  133. * 调用接口进行回传
  134. * @param $adminConfig
  135. * @param $data
  136. * @return bool
  137. * @throws \GuzzleHttp\Exception\GuzzleException
  138. * @throws \Psr\SimpleCache\InvalidArgumentException
  139. */
  140. public function apiReport($adminConfig, $data)
  141. {
  142. try {
  143. $httpConfig = [
  144. 'base_uri' => $this->bashUrl,
  145. 'connect_timeout' => 10,
  146. 'timeout' => 30,
  147. 'http_errors' => true, //抛出异常 true是 false否
  148. 'verify' => false, //不验证ssl证书
  149. ];
  150. $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($adminConfig['admin_id']);
  151. if ($proxy) {
  152. $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
  153. }
  154. $weChatConfig = Config::get('wechat');
  155. $weChatConfig['http']['base_uri'] = 'https://api.weixin.qq.com/';
  156. $weChatConfig['app_id'] = $adminConfig['platform_appid'];
  157. $weChatConfig['secret'] = $adminConfig['platform_secret'];
  158. $weChatConfig['token'] = $adminConfig['platform_token'];
  159. $weChatConfig['aes_key'] = $adminConfig['platform_aes_key'];
  160. $openPlatform = Factory::openPlatform($weChatConfig);
  161. $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
  162. $officialAccount = $openPlatform->officialAccount($adminConfig['appid'], $adminConfig['refresh_token']);
  163. $access_token = current($officialAccount->access_token->getToken());
  164. $client = new Http($httpConfig);
  165. $result = $client->request('POST',
  166. "user_actions/add?version=v1.0&access_token=$access_token",
  167. [
  168. 'headers' => [
  169. 'Content-Type' => 'application/json',
  170. 'charset' => 'utf-8'
  171. ],
  172. 'body' => json_encode($data)
  173. ]
  174. );
  175. Log::info("WeChatMpApiHeader:".json_encode($result->getHeaders()));
  176. if ($result = json_decode($result->getBody(), true)) {
  177. if (intval($result['errcode'])) {
  178. Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Fail Data:" . json_encode($data) . " Error:" . json_encode($result,
  179. JSON_UNESCAPED_UNICODE));
  180. return false;
  181. } else {
  182. Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Success Data:" . json_encode($data));
  183. return true;
  184. }
  185. }
  186. } catch (\Exception $e) {
  187. Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Fail,Error:" . $e->getMessage());
  188. return false;
  189. }
  190. return false;
  191. }
  192. /**
  193. * 关注回传
  194. * @param $adminConfig
  195. * @param $params
  196. * @return bool
  197. * @throws \GuzzleHttp\Exception\GuzzleException
  198. * @throws \Psr\SimpleCache\InvalidArgumentException
  199. */
  200. public function follow($adminConfig, $params)
  201. {
  202. try {
  203. $wx_source_id = $this->getUserActionSetId($adminConfig);
  204. if ($wx_source_id) {
  205. $data['actions'][0] = [
  206. 'user_action_set_id' => $wx_source_id,
  207. 'action_type' => "FOLLOW",
  208. 'action_time' => time(),
  209. 'url' => $params['url'],
  210. 'user_id' => [
  211. 'wechat_app_id' => $params['appid'],
  212. 'wechat_openid' => $params['openid'],
  213. ],
  214. 'action_param' => [
  215. "wechat_app_id" => $params['appid'],
  216. ]
  217. ];
  218. $res = $this->apiReport($adminConfig, $data);
  219. if ($res) {
  220. Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Success");
  221. } else {
  222. Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Fail");
  223. }
  224. return $res;
  225. }
  226. return false;
  227. } catch (\Exception $e) {
  228. Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Fail,Error:" . $e->getMessage());
  229. return false;
  230. }
  231. }
  232. /**
  233. * 订单完成回传
  234. * @param $adminConfig
  235. * @param $params
  236. * @return bool
  237. * @throws \GuzzleHttp\Exception\GuzzleException
  238. * @throws \Psr\SimpleCache\InvalidArgumentException
  239. */
  240. public function completeOrder($adminConfig, $params)
  241. {
  242. try {
  243. $wx_source_id = $this->getUserActionSetId($adminConfig);
  244. if ($wx_source_id) {
  245. $data['user_action_set_id'] = $wx_source_id;
  246. $data['actions'][0] = [
  247. 'action_type' => $params['action_type'],
  248. 'action_time' => time(),
  249. 'url' => $params['url'],
  250. 'user_id' => [
  251. 'wechat_app_id' => $params['appid'],
  252. 'wechat_openid' => $params['openid'],
  253. ],
  254. 'action_param' => [
  255. "product_name" => $params['product_name'],
  256. "product_id" => $params['product_id'],
  257. "value" => intval($params['money'] * 100),
  258. "source" => "Biz",
  259. "wechat_app_id" => $params['appid'],
  260. 'claim_type' => 0
  261. ]
  262. ];
  263. $res = $this->apiReport($adminConfig, $data);
  264. if ($res) {
  265. Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Success");
  266. } else {
  267. Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Fail");
  268. }
  269. return $res;
  270. }
  271. return false;
  272. } catch (\Exception $e) {
  273. Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Fail,Error:" . $e->getMessage());
  274. return false;
  275. }
  276. }
  277. }