赞
踩
h5端进入小程序 private function get_wxapp_temp_url() { $url = ''; $wxappConfig = WxappService::wxappConfig(null); $config = [ 'appid' => $wxappConfig['wx_appid'] ?? '这个appid', 'secret' => $wxappConfig['wx_appsecret'] ?? '这个是秘钥', ]; $wxapp = new Wxapp($config); $res = $wxapp->getTempUrl('pages/shop/shopHome/shopHome', 'ru_id=888'); // 访问店铺小程序页面路径 $res = json_decode($res, true); if ($res) { $url = isset($res['openlink']) ? $res['openlink'] : ''; } return $url; } /** * 唤起小程序临时访问链接 */ public function getTempUrl($path = '', $query = '') { if (!$this->checkAuth()) { return false; } $jump_wxa = [ 'path' => $path, 'query' => $query ]; $expire_time = time() + 60 * 60; $data = ['jump_wxa' => $jump_wxa, 'expire_time' => $expire_time]; $result = $this->curlPost(self::API_URL_PREFIX . self::GEN_SCHEME . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } 以下的详情文件方法 <?php namespace App\Modules\Wxapp\Libraries; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; class Wxapp { /** * 微信小程序类 * 官方文档:https://mp.weixin.qq.com/debug/wxadoc/dev/index.html?t=20161107 */ const API_URL_PREFIX = 'https://api.weixin.qq.com'; const AUTH_ORIZATION = '/sns/jscode2session?'; // 获取登录凭证(code) protected $wx_mini_appid; // 小程序ID protected $wx_mini_secret; // 小程序app_secret密钥 const GET_ACCESS_TOKEN = '/cgi-bin/token?'; // 获取access_token const GET_USER_INFO = '/cgi-bin/user/info?'; // 获取unionid const GET_WXA_CODE = '/wxa/getwxacode?'; // 获取小程序码 接口A const GET_WXA_CODE_UNLIMIT = '/wxa/getwxacodeunlimit?'; // 获取小程序码 接口B const GET_WXA_QRCODE = '/cgi-bin/wxaapp/createwxaqrcode?'; // 获取小程序码 接口C // 模板消息 小程序模板消息接口将于2020年1月10日下线 开发者可使用订阅消息功能 const GET_WXA_KEYWORD_LIST = '/cgi-bin/wxopen/template/library/get?'; // 获取模板库某个模板标题下关键词库 const GET_WXA_TEMPLATE_ADD = '/cgi-bin/wxopen/template/add?'; // 组合模板并添加至帐号下的个人模板库 const GET_WXA_TEMPLATE_DEL = '/cgi-bin/wxopen/template/del?'; // 删除帐号下的某个模板 const GET_WXA_TEMPLATE_LIST = '/cgi-bin/wxopen/template/list?'; // 获取帐号下已存在的模板列表 const GET_WXA_TEMPLATE_SEND_URL = '/cgi-bin/message/wxopen/template/send?'; //发送模板消息 接口地址 // 订阅消息 const SUBSCRIBE_MESSAGE_ADD_TEMPLATE = '/wxaapi/newtmpl/addtemplate?'; // 组合模板并添加至帐号下的个人模板库 const SUBSCRIBE_MESSAGE_DELETE_TEMPLATE = '/wxaapi/newtmpl/deltemplate?'; // 删除帐号下的个人模板 const SUBSCRIBE_MESSAGE_GET_CATEGORY = '/wxaapi/newtmpl/getcategory?'; // 获取小程序账号的类目 const SUBSCRIBE_MESSAGE_GET_PUB_TEMPLATE_KEYWORDS = '/wxaapi/newtmpl/getpubtemplatekeywords?'; // 获取模板标题下的关键词列表 const SUBSCRIBE_MESSAGE_GET_PUB_TEMPLATE_TITLE = '/wxaapi/newtmpl/getpubtemplatetitles?'; // 获取帐号所属类目下的公共模板标题 const SUBSCRIBE_MESSAGE_GET_TEMPLATE_LIST = '/wxaapi/newtmpl/gettemplate?'; // 获取当前帐号下的个人模板列表 const SUBSCRIBE_MESSAGE_SEND = '/cgi-bin/message/subscribe/send?'; // 发送订阅消息 // 直播API const MEDIA_UPLOAD_URL = '/cgi-bin/media/upload?'; // 上传临时素材 // 直播间 const BROADCAST_ROOM_CREATE = '/wxaapi/broadcast/room/create?';// 创建直播间 const GET_LIVE_INFO = '/wxa/business/getliveinfo?'; // 获取直播房间列表 const BROADCAST_ROOM_ADD_GOODS = '/wxaapi/broadcast/room/addgoods?'; //直播间导入已入库的商品 // 直播商品 const BROADCAST_GOODS_ADD = '/wxaapi/broadcast/goods/add?';// 商品添加并提审 const BROADCAST_GOODS_RESETAUDIT = '/wxaapi/broadcast/goods/resetaudit?';// 撤回审核 const BROADCAST_GOODS_AUDIT = '/wxaapi/broadcast/goods/audit?';// 重新提交审核 const BROADCAST_GOODS_DELETE = '/wxaapi/broadcast/goods/delete?';// 删除商品 const BROADCAST_GOODS_UPDATE = '/wxaapi/broadcast/goods/update?';// 更新商品 const GET_GOODS_WAREHOUSE = '/wxa/business/getgoodswarehouse?';// 获取商品状态 const GET_GOODS_LIST = '/wxaapi/broadcast/goods/getapproved?';// 获取商品列表 // 临时链接 const GEN_SCHEME = '/wxa/generatescheme?'; // 临时链接 protected $access_token; public $debug = false; public $errCode = 0; public $errMsg = "no access"; protected $_retry = false; public function __construct(array $options) { $this->wx_mini_appid = isset($options['appid']) ? $options['appid'] : ''; $this->wx_mini_secret = isset($options['secret']) ? $options['secret'] : ''; } /** * code 换取 session_key * 调用接口获取登录凭证(code) * @param $code * @return bool|mixed */ public function getOauthOrization($code) { $params = [ 'appid' => $this->wx_mini_appid, 'secret' => $this->wx_mini_secret, 'js_code' => $code, 'grant_type' => 'authorization_code' ]; $result = $this->curlGet(self::API_URL_PREFIX . self::AUTH_ORIZATION . http_build_query($params, '', '&')); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * code 换取 unionid * 调用接口获取登录凭证(code) * @param $token * @param $openid * @return bool|mixed */ public function getUnionid($token, $openid) { $params = [ 'withCredentials' => true, 'access_token' => $token, 'openid' => $openid, 'lang' => 'zh_CN' ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_USER_INFO, self::json_encode($params)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * 换取 access_token 缓存 * @return bool|mixed */ protected function checkAuth() { $cache_id = md5('wxapp_access_token' . $this->wx_mini_secret); if (($access_token = $this->getCache($cache_id)) && !empty($access_token)) { return $this->access_token = $access_token; } $result = $this->curlGet(self::API_URL_PREFIX . self::GET_ACCESS_TOKEN . "grant_type=client_credential&appid=" . $this->wx_mini_appid . "&secret=" . $this->wx_mini_secret); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } $this->access_token = $json['access_token']; $expire = $json['expires_in'] ? intval($json['expires_in']) - 300 : 7200; $this->setCache($cache_id, $this->access_token, $expire); return $this->access_token; } return false; } /** * 删除 access_token 缓存 */ public function resetAuth() { $this->access_token = null; $cache_id = md5('wxapp_access_token' . $this->wx_mini_secret); $this->removeCache($cache_id); return true; } /** * 接口失败重试 * @param string $method SDK方法名称 * @param array $arguments SDK方法参数 * @return bool|mixed */ protected function checkRetry($method, $arguments = []) { // access_token 超时过期重试 if (!$this->_retry && in_array($this->errCode, ['40014', '40001', '41001', '42001'])) { ($this->_retry = true) && $this->resetAuth(); $this->errCode = 40001; $this->errMsg = 'no access'; return call_user_func_array([$this, $method], $arguments); } return false; } /** * 唤起小程序临时访问链接 */ public function getTempUrl($path = '', $query = '') { if (!$this->checkAuth()) { return false; } $jump_wxa = [ 'path' => $path, 'query' => $query ]; $expire_time = time() + 60 * 60; $data = ['jump_wxa' => $jump_wxa, 'expire_time' => $expire_time]; $result = $this->curlPost(self::API_URL_PREFIX . self::GEN_SCHEME . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } /** * 获取小程序码 接口A * 适用于需要的码数量较少的业务场景 * @param string $path 小程序路径 * @param string $width * @param bool $auto_color * @param string $line_color * @return bool|mixed 返回的图片 Buffer */ public function getWaCode($path = '', $width = '430', $auto_color = false, $line_color = '') { if (!$this->checkAuth()) { return false; } $data = [ 'path' => $path, 'width' => $width, 'auto_color' => $auto_color, 'line_color' => $line_color ]; if ($auto_color === false) { unset($data['line_color']); } $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_CODE . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } /** * 获取小程序码 接口B * 适用于需要的码数量极多,或仅临时使用的业务场景 * @param string $scene 值 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符 例如:自定义推荐参数 scene=uid * @param string $path 小程序路径 * @param string $width 二维码的宽度 * @param bool $auto_color 自动配置线条颜色 * @param string $line_color * @param bool $is_hyaline 是否需要透明底色 * @return bool|mixed 返回的图片 Buffer */ public function getWaCodeUnlimit($scene = '', $path = '', $width = '', $auto_color = false, $line_color = '', $is_hyaline = true) { if (!$this->checkAuth()) { return false; } $data = [ 'scene' => $scene, 'page' => $path, 'width' => $width, 'auto_color' => $auto_color, 'line_color' => $line_color, 'is_hyaline' => $is_hyaline ]; if ($auto_color === false) { unset($data['line_color']); } $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_CODE_UNLIMIT . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } /*生成小程序店铺二维码*/ public function getWaCodeNew($path = '', $width = '430', $auto_color = false, $line_color = '') { if (!$this->checkAuth()) { return false; } $data = [ 'path' => $path, 'width' => $width, 'auto_color' => $auto_color, 'line_color' => $line_color ]; if ($auto_color === false) { unset($data['line_color']); } $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="; $result = $this->curlPost($url . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } /** * 获取小程序码 接口C * 适用于需要的码数量较少的业务场景 * 通过该接口生成的小程序二维码,永久有效,数量限制见文末说明,请谨慎使用。 * @param string $path * @param string $width * @return bool|mixed */ public function getWxaCode($path = '', $width = '430') { if (!$this->checkAuth()) { return false; } $data = [ 'path' => $path, 'width' => $width ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_QRCODE . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $result; } return false; } /** * 获取模板库某个模板标题下关键词库KeywordList * 成功返回消息模板标题下关键词库 * @param string $tpl_id 模板库中模板的编号 * @return boolean|string */ public function getWxTemplateKeywordList($tpl_id = '') { if (!$this->checkAuth()) { return false; } $tpl_id = [ 'id' => $tpl_id, ]; //获取模板库某个模板标题下关键词库 $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_KEYWORD_LIST . 'access_token=' . $this->access_token, self::json_encode($tpl_id)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * 模板消息 添加消息模板 * 成功返回消息模板的调用id * @param string $tpl_id 模板的编号 * @param string $keyword_id 关键词库id * @return boolean|string */ public function wxaddTemplateMessage($tpl_id = '', $keyword_id = '') { if (!$this->checkAuth()) { return false; } $tpl_id = [ 'id' => $tpl_id, 'keyword_id_list' => $keyword_id ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_TEMPLATE_ADD . 'access_token=' . $this->access_token, self::json_encode($tpl_id)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json['template_id']; } return false; } /** * 删除模板消息 * @param string $template_id 模板消息ID * @return boolean|array */ public function wxDelTemplate($template_id = '') { if (!$this->checkAuth()) { return false; } $data = [ 'template_id' => $template_id ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_TEMPLATE_DEL . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * 获取帐号下已存在的模板列表 * @param int $offset 用于分页,表示从offset开始。从 0 开始计数。 * @param int $count 用于分页,表示拉取count条记录。最大为 20。最后一页的list长度可能小于请求的count。 * @return boolean|array */ public function wxTemplateList($offset = 0, $count = 20) { if (!$this->checkAuth()) { return false; } $data = [ 'offset' => $offset, 'count' => $count ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_TEMPLATE_LIST . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * 发送模板消息 * @param array $data 消息结构 *{ *"touser": "OPENID", * "template_id": "TEMPLATE_ID", *"page": "index", *"form_id": "FORMID", *"data": { * "keyword1": { * "value": "339208499", * "color": "#173177" * }, * "keyword2": { * "value": "2015年01月05日 12:30", * "color": "#173177" * }, *"keyword3": { * "value": "粤海喜来登酒店", * "color": "#173177" *} , *"keyword4": { * "value": "广州市天河区天河路208号", * "color": "#173177" *} *}, *"emphasis_keyword": "keyword1.DATA" *} * @return boolean|array */ public function sendTemplateMessage($data = []) { if (!$this->checkAuth()) { return false; } $result = $this->curlPost(self::API_URL_PREFIX . self::GET_WXA_TEMPLATE_SEND_URL . 'access_token=' . $this->access_token, self::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 订阅消息 组合模板并添加至帐号下的个人模板库 * @param string $tid 模板标题 id,可通过接口获取,也可登录小程序后台查看获取 * @param array $kidList 开发者自行组合好的模板关键词列表,关键词顺序可以自由搭配(例如 [3,5,4] 或 [4,5,3]),最多支持5个,最少2个关键词组合 * @param string $sceneDesc 服务场景描述,15个字以内 * @return boolean|string */ public function subscribeMessageAddTemplate($tid = '', $kidList = [], $sceneDesc = '') { if (!$this->checkAuth()) { return false; } $data = [ 'tid' => $tid, 'kidList' => $kidList ]; if (!empty($sceneDesc)) { $data['sceneDesc'] = $sceneDesc; } // 此处官方文档 使用 json 请求失败,改成 http_build_query $result = $this->curlPost(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_ADD_TEMPLATE . 'access_token=' . $this->access_token, http_build_query($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['priTmplId']; } return false; } /** * 订阅消息 删除帐号下的个人模板 * @param string $priTmplId 要删除的模板id * @return boolean|string */ public function subscribeMessageDeleteTemplate($priTmplId = '') { if (!$this->checkAuth()) { return false; } $params = [ 'priTmplId' => $priTmplId, ]; // 此处官方文档 使用 json 请求失败,改成 http_build_query $result = $this->curlPost(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_DELETE_TEMPLATE . 'access_token=' . $this->access_token, http_build_query($params)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 订阅消息 获取小程序账号的类目 * @return boolean|array */ public function subscribeMessageGetCategory() { if (!$this->checkAuth()) { return false; } $result = $this->curlGet(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_GET_CATEGORY . 'access_token=' . $this->access_token); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['data']; } return false; } /** * 订阅消息 获取模板标题下的关键词列表 * @param string $tid 模板标题 id,可通过接口获取 * @return boolean|string */ public function subscribeMessageGetPubTemplateKeywords($tid = '') { if (!$this->checkAuth()) { return false; } $params = [ 'tid' => $tid ]; $result = $this->curlGet(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_GET_PUB_TEMPLATE_KEYWORDS . 'access_token=' . $this->access_token . '&' . http_build_query($params, '', '&')); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['data']; } return false; } /** * 订阅消息 获取帐号所属类目下的公共模板标题 * @param string $ids 类目 id,多个用逗号隔开 * @param int $start 用于分页,表示从 start 开始。从 0 开始计数。 * @param int $limit 用于分页,表示拉取 limit 条记录。最大为 30 * @return boolean|string */ public function subscribeMessageGetPubTemplateTitle($ids = '', $start = 0, $limit = 30) { if (!$this->checkAuth()) { return false; } $params = [ 'ids' => $ids, 'start' => $start, 'limit' => $limit > 30 ? 30 : $limit ]; $result = $this->curlGet(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_GET_PUB_TEMPLATE_TITLE . 'access_token=' . $this->access_token . '&' . http_build_query($params, '', '&')); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['data']; } return false; } /** * 订阅消息 获取当前帐号下的个人模板列表 * @return boolean|string */ public function subscribeMessageGetTemplateList() { if (!$this->checkAuth()) { return false; } $result = $this->curlGet(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_GET_TEMPLATE_LIST . 'access_token=' . $this->access_token); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['data']; } return false; } /** * 订阅消息 发送订阅消息 * @link https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html * @param string $touser 接收者(用户)的 openid * @param string $template_id 所需下发的订阅模板id * @param array $data 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } * @param string $page 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 * @param string $miniprogram_state 跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 * @param string $lang 进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN * @return boolean|string */ public function subscribeMessageSend($touser = '', $template_id = '', $data = [], $page = '', $miniprogram_state = '', $lang = '') { if (!$this->checkAuth()) { return false; } $params = [ 'touser' => $touser, 'template_id' => $template_id, 'data' => $data ]; if (!empty($page)) { $params['page'] = $page; } if (!empty($miniprogram_state)) { $params['miniprogram_state'] = $miniprogram_state; } if (!empty($lang)) { $params['lang'] = $lang; } $result = $this->curlPost(self::API_URL_PREFIX . self::SUBSCRIBE_MESSAGE_SEND . 'access_token=' . $this->access_token, self::json_encode($params)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 创建直播间 * @param array $data * @return bool|mixed */ public function liveRoomCreate($data = []) { if (empty($data)) { return false; } if (!$this->checkAuth()) { return false; } $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_ROOM_CREATE . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json['roomId']; } return false; } /** * 获取直播房间列表 * @param int $start 起始拉取房间,start = 0 表示从第 1 个房间开始拉取 * @param int $limit 每次拉取的个数上限,不要设置过大,建议 100 以内 * @return bool|mixed */ public function liveRoom($start = 0, $limit = 10) { if (!$this->checkAuth()) { return false; } $data = [ 'start' => $start, 'limit' => $limit ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_LIVE_INFO . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 获取直播间回放 * * 接口说明:调用接口获取已结束直播间的回放源视频(一般在直播结束后10分钟内生成,源视频无评论等内容) * * @param int $room_id 直播间id * @param int $start 起始拉取视频,0表示从第一个视频片段开始拉取 * @param int $limit 每次拉取的数量,建议100以内 * @return bool|mixed */ public function liveRoomReplay($room_id = 0, $start = 0, $limit = 10) { if (empty($room_id)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'action' => 'get_replay', 'room_id' => $room_id, 'start' => $start, 'limit' => $limit ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_LIVE_INFO . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 直播间导入已入库的商品 * * @param int $room_id * @param array $goods_ids * @return bool */ public function liveRoomAddGoods($room_id = 0, $goods_ids = []) { if (empty($room_id) || empty($goods_ids)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'ids' => $goods_ids, 'roomId' => $room_id ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_ROOM_ADD_GOODS . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 上传临时素材,有效期为3天(仅小程序接口可用) * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义 * 注意:临时素材的media_id是可复用的! * @param array $data {"media":'@Path\filename.jpg'} * @param string $type 类型:图片:image 语音:voice 视频:video 缩略图:thumb * @return boolean|array */ public function uploadMedia($data = [], $type = '') { if (empty($data)) { return false; } // 小程序 access_token if (!$this->checkAuth()) { return false; } $result = $this->curlFilePost(self::API_URL_PREFIX . self::MEDIA_UPLOAD_URL . 'access_token=' . $this->access_token . '&type=' . $type, $data); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 商品添加并提审 * * 调用此接口上传并提审需要直播的商品信息,审核通过后商品录入【小程序直播】商品库 * 注意:开发者必须保存【商品ID】与【审核单ID】,如果丢失,则无法调用其他相关接口 * * @param array $goodsInfo * @return bool|mixed */ public function liveGoodsAdd($goodsInfo = []) { if (empty($goodsInfo)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'goodsInfo' => $goodsInfo ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_GOODS_ADD . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 撤回审核 * * 用此接口,可撤回直播商品的提审申请,消耗的提审次数不返还 * @param string $auditId * @param int $goodsId * @return bool|mixed */ public function liveGoodsReset($auditId = '', $goodsId = 0) { if (empty($auditId) || empty($goodsId)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'auditId' => $auditId, 'goodsId' => $goodsId ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_GOODS_RESETAUDIT . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 重新提交审核 * * 调用此接口可以对已撤回提审的商品再次发起提审申请 * * @param int $goodsId * @return bool|mixed */ public function liveGoodsAudit($goodsId = 0) { if (empty($goodsId)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'goodsId' => $goodsId ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_GOODS_AUDIT . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 删除商品 * * 调用此接口,可删除【小程序直播】商品库中的商品,删除后直播间上架的该商品也将被同步删除,不可恢复; * @param int $goodsId * @return bool|mixed */ public function liveGoodsDelete($goodsId = 0) { if (empty($goodsId)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'goodsId' => $goodsId ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_GOODS_DELETE . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 更新商品 * * 调用此接口可以更新商品信息,审核通过的商品仅允许更新价格类型与价格,审核中的商品不允许更新,未审核的商品允许更新所有字段, 只传入需要更新的字段。 * @param int $goodsId * @param array $goodsInfo 需要更新哪个字段就传入哪个字段,goodsId 必传 * @return bool|mixed */ public function liveGoodsUpdate($goodsId = 0, $goodsInfo = []) { if (empty($goodsId) || empty($goodsInfo)) { return false; } if (!$this->checkAuth()) { return false; } $goodsInfo['goodsId'] = $goodsId; $data = [ 'goodsInfo' => $goodsInfo ]; $result = $this->curlPost(self::API_URL_PREFIX . self::BROADCAST_GOODS_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return true; } return false; } /** * 获取商品状态 * * 调用此接口可获取商品的信息与审核状态 * @param array $goods_ids * @return bool|mixed */ public function getGoodsWarehouse($goods_ids = []) { if (empty($goods_ids)) { return false; } if (!$this->checkAuth()) { return false; } $data = [ 'goods_ids' => $goods_ids ]; $result = $this->curlPost(self::API_URL_PREFIX . self::GET_GOODS_WAREHOUSE . 'access_token=' . $this->access_token, self::json_encode($data), 'json'); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * 获取商品列表 * * 调用此接口可获取商品列表 * @param int $start 分页条数起点 * @param int $limit 分页大小,默认30,不超过100 * @param int $status 商品状态,0:未审核。1:审核中,2:审核通过,3:审核驳回 * @return bool|mixed */ public function getGoodsList($start = 0, $limit = 30, $status = 0) { if (!$this->checkAuth()) { return false; } $params = [ 'offset' => $start, 'limit' => $limit, 'status' => $status ]; $result = $this->curlGet(self::API_URL_PREFIX . self::GET_GOODS_LIST . 'access_token=' . $this->access_token . '&' . http_build_query($params, '', '&')); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; } return false; } /** * GET 请求 * @param $url * @param int $timeout * @param string $header * @return bool|mixed */ protected function curlGet($url, $timeout = 5, $header = "") { $ch = curl_init(); if (stripos($url, "https://") !== false) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } curl_setopt($ch, CURLOPT_HTTP_VERSION, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HTTPHEADER, [$header]);//模拟的header头 $result = curl_exec($ch); $aStatus = curl_getinfo($ch); curl_close($ch); if (intval($aStatus["http_code"]) == 200) { return $result; } else { return false; } } /** * POST 请求 文件上传 * @param string $url * @param array $post_data * @param int $timeout * @return string content */ protected function curlFilePost($url, $post_data = [], $timeout = 60) { $ch = curl_init(); if (stripos($url, "https://") !== false) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } curl_setopt($ch, CURLOPT_HTTP_VERSION, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $result = curl_exec($ch); $aStatus = curl_getinfo($ch); curl_close($ch); if (intval($aStatus["http_code"]) == 200) { return $result; } else { return false; } } /** * POST 请求 * @param $url * @param $post_data * @param string $contentType * @param int $timeout * @return bool|mixed */ protected function curlPost($url = '', $post_data, $contentType = 'form_params', $timeout = 60) { $ch = curl_init(); if (stripos($url, "https://") !== false) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } if (is_string($post_data)) { $strPOST = $post_data; } else { $aPOST = []; foreach ($post_data as $key => $val) { $aPOST[] = $key . "=" . urlencode($val); } $strPOST = join("&", $aPOST); } curl_setopt($ch, CURLOPT_HTTP_VERSION, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $strPOST); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if ($contentType == 'form_params') { $header = [ "Content-type: application/x-www-form-urlencoded", ]; } elseif ($contentType == 'json') { $header = [ "Content-type: application/json", ]; } if (isset($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//模拟的header头 } $result = curl_exec($ch); $aStatus = curl_getinfo($ch); curl_close($ch); if (intval($aStatus["http_code"]) == 200) { return $result; } else { return false; } } /** * 微信api不支持中文转义的json结构 * @param $arr * @return string */ public static function json_encode($arr) { if (count($arr) == 0) { return "[]"; } $parts = []; $is_list = false; //Find out if the given array is a numerical array $keys = array_keys($arr); $max_length = count($arr) - 1; if (($keys [0] === 0) && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1 $is_list = true; for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position if ($i != $keys [$i]) { //A key fails at position check. $is_list = false; //It is an associative array. break; } } } foreach ($arr as $key => $value) { if (is_array($value)) { //Custom handling for arrays if ($is_list) { $parts [] = self::json_encode($value); } /* :RECURSION: */ else { $parts [] = '"' . $key . '":' . self::json_encode($value); } /* :RECURSION: */ } else { $str = ''; if (!$is_list) { $str = '"' . $key . '":'; } //Custom handling for multiple data types if (!is_string($value) && is_numeric($value) && $value < 2000000000) { $str .= $value; } //Numbers elseif ($value === false) { $str .= 'false'; } //The booleans elseif ($value === true) { $str .= 'true'; } else { $str .= '"' . addslashes($value) . '"'; } //All other things // :TODO: Is there any more datatype we should be in the lookout for? (Object?) $parts [] = $str; } } $json = implode(',', $parts); if ($is_list) { return '[' . $json . ']'; } //Return numerical JSON return '{' . $json . '}'; //Return associative JSON } /** * 设置缓存,按需重载 * @param string $name * @param mixed $value * @param int $expired * @return boolean */ protected function setCache($name, $value, $expired) { Cache::put($name, $value, Carbon::now()->addSeconds($expired)); return true; } /** * 获取缓存,按需重载 * @param string $name * @return mixed */ protected function getCache($name) { return Cache::get($name); } /** * 清除缓存,按需重载 * @param string $name * @return boolean */ protected function removeCache($name) { return Cache::forget($name); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。