123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- <?php
- 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\Exception;
- use think\Log;
- class WeChatAdService extends BaseService {
- private $bashUrl = 'https://api.weixin.qq.com/marketing/';
- const ACTION_TYPE_COMPLETE_ORDER = 'COMPLETE_ORDER'; //下单
- const ACTION_TYPE_REGISTER = 'REGISTER'; //关注即注册
- public $error_msg = '';
- /**
- * @var WeChatAdService
- */
- protected static $self = NULL;
- /**
- * @return WeChatAdService
- */
- public static function instance()
- {
- if (self::$self == NULL) {
- self::$self = new self();
- }
- return self::$self;
- }
- /**
- * 上传微信数据源
- * @param $admin_id
- * @param $params ['url', 'open_id', 'money', 'product_name', 'product_id', 'action_type']
- * @return bool
- */
- //public function SendWxAdSource($admin_id,$url,$open_id, $money, $product_name = '', $action_type = 'COMPLETE_ORDER'){
- public function SendWxAdSource($admin_id, $params){
- if($adminConfig = model('AdminConfig')->getAdminInfoAll($admin_id)){
- $wx_ad_state = intval($adminConfig['wx_ad_state'] ?? 0);
- $wx_ad_source_id = $adminConfig['wx_ad_source_id'] ?? '';
- //微信AD数据源开启时&数据源ID存在时,上传数据
- if($wx_ad_state && $wx_ad_source_id){
- $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());
- $source_params = [
- 'admin_id' => $adminConfig['admin_id'],
- 'access_token' => $access_token,
- 'wx_ad_source_id' => $wx_ad_source_id,
- 'url' => $params['url'],
- 'app_id' => $adminConfig['appid'],
- 'open_id' => $params['open_id'],
- 'money' => $params['money'],
- 'product_name' => $params['product_name'],
- 'product_id' => $params['product_id'],
- 'action_type' => $params['action_type'],
- ];
- return $this->sendAdSource($source_params);
- }
- }
- return false;
- }
- /**
- * 渠道创建微信AD数据源ID
- * @param $admin_id
- * @return bool|string
- */
- public function createChannelWxAdSourceId($admin_id){
- if($adminConfig = model('AdminConfig')->getAdminInfoAll($admin_id)){
- $wx_ad_state = intval($adminConfig['wx_ad_state'] ?? 0);
- $wx_ad_source_id = $adminConfig['wx_ad_source_id'] ?? '';
- if( $wx_ad_state && empty($wx_ad_source_id) ){
- $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());
- if($wx_ad_source_id = $this->createAdSourceId($adminConfig['admin_id'],$access_token, $adminConfig['appid'],'CPS下单','CPS下单')){
- $update = model('AdminConfig')->where('admin_id',$adminConfig['admin_id'])->update(['wx_ad_source_id'=>$wx_ad_source_id]);
- if($update === false){
- $this->error_msg = 'Write Db Fail';
- Log::notice("WeChatAd: AdminId:{$adminConfig['admin_id']} AdSourceId:{$wx_ad_source_id} WriteWeChatAdSourceId To Mysql Fail");
- return false;
- }
- model('AdminConfig')->delAdminInfoAllCache($adminConfig['admin_id']);
- return $wx_ad_source_id;
- }
- }
- }
- return false;
- }
- /**
- * 查看数据源报表
- * @param $admin_id
- * @param $access_token
- * @param $source_id
- * @param $start_time
- * @param $end_time
- * @return mixed|\Psr\Http\Message\ResponseInterface|null
- */
- private function searchAdSource($admin_id,$access_token,$source_id,$start_time,$end_time){
- try{
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($admin_id);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- $client = new Http($httpConfig);
- $data = ['start_date' => $start_time, 'end_date' => $end_time];
- $result = $client->get("user_action_set_reports/get?version=v1.0&access_token=$access_token&user_action_set_id=$source_id&time_granularity=HOURLY&aggregation=RESERVATION&date_range=".urlencode(json_encode($data)));
- if($result = json_decode($result->getBody(),true)){
- return $result;
- }
- }catch (\Exception $e){
- $this->error_msg = $e->getMessage();
- Log::error("WeChatAd: AdminId:{$admin_id} CreateAdSourceId Fail,Error:".$e->getMessage());
- return null;
- }
- return null;
- }
- /**
- * 上传微信AD数据源信息
- * @param $params ['admin_id' ,'access_token' , 'wx_ad_source_id' ,'url' ,'app_id' ,'open_id' ,'money' ,'product_name' ,'product_id' ,'action_type' ]
- * @return bool
- */
- //private function sendAdSource($admin_id,$access_token,$wx_source_id,$url,$app_id,$open_id, $money, $product_name = '', $action_type)
- private function sendAdSource($params)
- {
- try{
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($params['admin_id']);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- $client = new Http($httpConfig);
- $data['actions'][0] = [
- 'user_action_set_id' => $params['wx_ad_source_id'],
- 'action_type' => $params['action_type'],
- 'action_time' => time(),
- 'url' => $params['url'],
- 'user_id' => [
- 'wechat_app_id' => $params['app_id'],
- 'wechat_openid' => $params['open_id'],
- ],
- 'action_param' => [
- "product_name" => $params['product_name'],
- "product_id" => $params['product_id'],
- "value" => intval($params['money'] * 100),
- "source" => "Biz",
- "wechat_app_id" => $params['app_id'],
- 'claim_type' => 0
- ]
- ];
- $result = $client->request('POST',
- "user_actions/add?version=v1.0&access_token=".$params['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'])){
- $this->error_msg = $result['errmsg'];
- Log::notice("WeChatAd: AdminId:{$params['admin_id']} SendWeChatSource Fail Data:".json_encode($data)." Error:".$result['errmsg']);
- return false;
- }else{
- Log::info("WeChatAd: AdminId:{$params['admin_id']} SendWeChatSource Success Data:".json_encode($data));
- return true;
- }
- }
- }catch (\Exception $e){
- $this->error_msg = $e->getMessage();
- Log::error("WeChatAd: AdminId:{$params['admin_id']} source_id:{$params['wx_ad_source_id']} SendWeChatSource Fail,Error:".$e->getMessage());
- return false;
- }
- return false;
- }
- /**
- * 创建微信AD数据源
- * @param $admin_id
- * @param $accessToken
- * @param $name
- * @param $des
- * @param string $type
- * @return bool
- */
- private function createAdSourceId($admin_id,$accessToken,$app_id,$name,$des,$type = 'WECHAT', $platform_id=null){
- try{
- //判断是否已经获取
- $key = 'ASAD:'.$app_id;
- 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($admin_id);
- if ($proxy) {
- $httpConfig = array_merge($httpConfig, ['proxy' => $proxy]);
- }
- }
- $client = new Http($httpConfig);
- $data = ['type' => $type, 'name' => $name, 'description' => $des,'wechat_app_id'=>$app_id];
- $result = $client->request('POST',
- "user_action_sets/add?version=v1.0&access_token=$accessToken",
- [
- '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("WeChatAd: AdminId:{$admin_id} CreateAdSourceId Exists source_id:{$wx_ad_source_id} Data:".json_encode($result));
- return $wx_ad_source_id;
- }else{
- //失败时处理
- $this->error_msg = $result['errmsg'];
- Log::notice("WeChatAd: AdminId:{$admin_id} CreateAdSourceId Fail,Error:".$result['errmsg']);
- return false;
- }
- }else{
- //成功
- Log::info("WeChatAd: AdminId:{$admin_id} CreateAdSourceId Success Data:".json_encode($result));
- return $result['data']['user_action_set_id'] ?? false;
- }
- }
- }catch (\Exception $e){
- $this->error_msg = $e->getMessage();
- Log::error("WeChatAd: AdminId:{$admin_id} CreateAdSourceId Fail,Error:".$e->getMessage());
- return false;
- }
- }
- /**
- * 指定平台 执行微信的 AD
- * @param $app_id
- * @param $platform_id
- */
- public function createWxAdSourceId($app_id, $platform_id, $refresh_token)
- {
- $access_token = current((new WeChatObject(null))->getOfficialAccountByPlatform($platform_id, $app_id, $refresh_token)->access_token->getRefreshedToken());
- if(
- $wx_ad_source_id = $this->createAdSourceId(null,$access_token, $app_id,'CPS下单','CPS下单', 'WECHAT', $platform_id)
- ){
- return $wx_ad_source_id;
- } else {
- Log::notice("AbWeChatAd: appid:{$app_id} CreateAdSourceId Fail,Error:");
- }
- return false;
- }
- /**
- * 调用接口
- * @param $httpConfig
- * @param $access_token
- * @param $data
- * @return bool
- */
- public function send($httpConfig,$access_token, $data, $api_url = 'user_actions/add')
- {
- try{
- $httpConfig['base_uri'] = $this->bashUrl;
- $client = new Http($httpConfig);
- $result = $client->request('POST',
- $api_url. "?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'])){
- $this->error_msg = $result['errmsg'];
- Log::error("AbWeChatAd: SendWeChatSource Fail Data:".json_encode($data)." Error:".$result['errmsg']);
- return false;
- }else{
- Log::info("AbWeChatAd: SendWeChatSource Success Data:".json_encode($data));
- return true;
- }
- }
- }catch (\Exception $e){
- $this->error_msg = $e->getMessage();
- Log::error("AbWeChatAd: SendWeChatSource Fail,Error:".$e->getMessage());
- return false;
- }
- return false;
- }
- }
|