123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287 |
- <?php
- /**
- * Created by: PhpStorm
- * User: lytian
- * Date: 2020/4/2
- * Time: 13:42
- */
- namespace app\main\service;
- use app\common\library\Redis;
- use app\common\library\WeChatObject;
- use EasyWeChat\Factory;
- use GuzzleHttp\Client as Http;
- use GuzzleHttp\Exception\GuzzleException;
- use Symfony\Component\Cache\Simple\RedisCache;
- use think\Config;
- use think\Log;
- class GdtMpApiService extends BaseService
- {
- /**
- * 接口地址
- * @var string
- */
- private $bashUrl = 'https://api.weixin.qq.com/marketing/';
- /**
- * 定义属性
- * @var GdtMpApiService
- */
- protected static $self = null;
- /**
- * 返回实例
- * @return GdtMpApiService
- */
- public static function instance()
- {
- if (self::$self == null) {
- self::$self = new self();
- }
- return self::$self;
- }
- /**
- * 获取行为源ID,不存在创建
- * @param $adminConfig
- * @param $platform_id
- * @return bool|int|string
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function getUserActionSetId($adminConfig, $platform_id = null)
- {
- try {
- //判断是否已经获取
- $key = 'ASAD:WEB:' . $adminConfig['appid'];
- if (($id = Redis::instance()->get($key)) !== false) {
- return $id;
- }
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- if (!is_null($platform_id)) {
- $proxy = OpenPlatformService::instance()->getProxyconfigById($platform_id);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- } else {
- $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($adminConfig['admin_id']);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- }
- $client = new Http($httpConfig);
- $weChatConfig = Config::get('wechat');
- $weChatConfig['http']['base_uri'] = 'https://api.weixin.qq.com/';
- $weChatConfig['app_id'] = $adminConfig['platform_appid'];
- $weChatConfig['secret'] = $adminConfig['platform_secret'];
- $weChatConfig['token'] = $adminConfig['platform_token'];
- $weChatConfig['aes_key'] = $adminConfig['platform_aes_key'];
- $openPlatform = Factory::openPlatform($weChatConfig);
- $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
- $officialAccount = $openPlatform->officialAccount($adminConfig['appid'], $adminConfig['refresh_token']);
- $access_token = current($officialAccount->access_token->getToken());
- $data = [
- 'type' => "WEB",
- 'name' => "GDT回传CPS下单",
- 'description' => "GDT回传CPS下单",
- 'wechat_app_id' => $adminConfig['appid']
- ];
- $result = $client->request('POST',
- "user_action_sets/add?version=v1.0&access_token=$access_token",
- [
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'charset' => 'utf-8'
- ],
- 'body' => json_encode($data)
- ]
- );
- if ($result = json_decode($result->getBody(), true)) {
- if (intval($result['errcode'])) {
- //失败
- if (intval($result['errcode']) == 900351000) {
- //已存在时,截取ID,并返回成功
- $errMsg = explode(':', $result['errmsg']);
- $wx_ad_source_id = intval(end($errMsg)) ?? false;
- Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Exists source_id:{$wx_ad_source_id} Data:" . json_encode($result));
- //写入redis
- Redis::instance()->set($key, $wx_ad_source_id, 86400 * 7);
- return $wx_ad_source_id;
- } else {
- //失败时处理
- Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Fail,Error:" . $result['errmsg']);
- return false;
- }
- } else {
- //成功
- Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Success Data:" . json_encode($result));
- //写入redis
- $wx_ad_source_id = $result['data']['user_action_set_id'];
- Redis::instance()->set($key, $wx_ad_source_id, 86400 * 7);
- return $wx_ad_source_id ?: false;
- }
- }
- return false;
- } catch (\Exception $e) {
- Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} CreateAdSourceId Fail,Error:" . $e->getMessage());
- return false;
- }
- }
- /**
- * 调用接口进行回传
- * @param $adminConfig
- * @param $data
- * @return bool
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function apiReport($adminConfig, $data)
- {
- try {
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($adminConfig['admin_id']);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- $weChatConfig = Config::get('wechat');
- $weChatConfig['http']['base_uri'] = 'https://api.weixin.qq.com/';
- $weChatConfig['app_id'] = $adminConfig['platform_appid'];
- $weChatConfig['secret'] = $adminConfig['platform_secret'];
- $weChatConfig['token'] = $adminConfig['platform_token'];
- $weChatConfig['aes_key'] = $adminConfig['platform_aes_key'];
- $openPlatform = Factory::openPlatform($weChatConfig);
- $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
- $officialAccount = $openPlatform->officialAccount($adminConfig['appid'], $adminConfig['refresh_token']);
- $access_token = current($officialAccount->access_token->getToken());
- $client = new Http($httpConfig);
- $result = $client->request('POST',
- "user_actions/add?version=v1.0&access_token=$access_token",
- [
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'charset' => 'utf-8'
- ],
- 'body' => json_encode($data)
- ]
- );
- Log::info("WeChatMpApiHeader:".json_encode($result->getHeaders()));
- if ($result = json_decode($result->getBody(), true)) {
- if (intval($result['errcode'])) {
- Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Fail Data:" . json_encode($data) . " Error:" . json_encode($result,
- JSON_UNESCAPED_UNICODE));
- return false;
- } else {
- Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Success Data:" . json_encode($data));
- return true;
- }
- }
- } catch (\Exception $e) {
- Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} SendWeChatSource Fail,Error:" . $e->getMessage());
- return false;
- }
- return false;
- }
- /**
- * 关注回传
- * @param $adminConfig
- * @param $params
- * @return bool
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function follow($adminConfig, $params)
- {
- try {
- $wx_source_id = $this->getUserActionSetId($adminConfig);
- if ($wx_source_id) {
- $data['actions'][0] = [
- 'user_action_set_id' => $wx_source_id,
- 'action_type' => "FOLLOW",
- 'action_time' => time(),
- 'url' => $params['url'],
- 'user_id' => [
- 'wechat_app_id' => $params['appid'],
- 'wechat_openid' => $params['openid'],
- ],
- 'action_param' => [
- "wechat_app_id" => $params['appid'],
- ]
- ];
- $res = $this->apiReport($adminConfig, $data);
- if ($res) {
- Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Success");
- } else {
- Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Fail");
- }
- return $res;
- }
- return false;
- } catch (\Exception $e) {
- Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:FOLLOW SendWeChatSource Fail,Error:" . $e->getMessage());
- return false;
- }
- }
- /**
- * 订单完成回传
- * @param $adminConfig
- * @param $params
- * @return bool
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function completeOrder($adminConfig, $params)
- {
- try {
- $wx_source_id = $this->getUserActionSetId($adminConfig);
- if ($wx_source_id) {
- $data['user_action_set_id'] = $wx_source_id;
- $data['actions'][0] = [
- 'action_type' => $params['action_type'],
- 'action_time' => time(),
- 'url' => $params['url'],
- 'user_id' => [
- 'wechat_app_id' => $params['appid'],
- 'wechat_openid' => $params['openid'],
- ],
- 'action_param' => [
- "product_name" => $params['product_name'],
- "product_id" => $params['product_id'],
- "value" => intval($params['money'] * 100),
- "source" => "Biz",
- "wechat_app_id" => $params['appid'],
- 'claim_type' => 0
- ]
- ];
- $res = $this->apiReport($adminConfig, $data);
- if ($res) {
- Log::info("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Success");
- } else {
- Log::notice("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Fail");
- }
- return $res;
- }
- return false;
- } catch (\Exception $e) {
- Log::error("GDTWeChatAd: AdminId:{$adminConfig['admin_id']} Action:ORDER SendWeChatSource Fail,Error:" . $e->getMessage());
- return false;
- }
- }
- }
|