PHP 对接 饿了么开放平台 接单

<?PHP
# 一开始使用的是API方式对接,所以我这里是API的方式+SDK的结合  (除了获取token之外都是使用SDK方式,所以看到的朋友还是直接使用纯SDK方式对接最好),因为我这里使用API的方式获取存储 token 所以我在饿了么的SDK包中有需要使用的方法中 把原来调token的方式注释了,用我自己的!
# 兄弟们不要学我,如果有SDK最好还是全用SDK的好! 我后面也会改全用SDK
# 需要注意引入路劲 其他的大多数再SDK都给你写好了  饿了么的SDK到开放平台下载,有意思的是,他给的推送响应参数示例和给出的响应结构体有个别少数存在参数单词错误,不对应。(例:响应结构体中给 shop_name,在响应示例中给的可能是 shopName)。 需要自己仔细看报错信息(如果有的话,至少我在修改店铺信息的时候遇到了)。
# 目前我下载的这版本SDK中饿了么已将返回的json字符串做了转数组的操作。
# 当然我这里还有部分需要优化的 我这里就先简单粗暴
class ELMController extends commonController { const SANDBox_KEY = '你的 SANDBox_KEY'; const SANDBox_SECRET = '你的 SANDBox_SECRET'; # 正式饿了么开发参数 const KEY = ''; const SECRET = ''; # 饿了么 沙箱 + 正式 获取TOKEN 地址 【因为我是用API的方式去获取token 所以我这里需要保留】 const ELM_SANDBox_TOKEN_URL = 'https://open-api-sandBox.shop.ele.me/token'; const ELM_TOKEN_URL = 'https://open-api.shop.ele.me/token'; # 回调地址 const JT_TEST_URL = '你的测试回调地址'; const ZP_URL = '你的正式回调地址'; /** * 获取授权地址 */ public function getoauthUrlAction(){ $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $Rurl = (($webSite['debug']) ? self::JT_TEST_URL : self::ZP_URL).'?md=service&cl=ELM&at=ELMReturn'; $config = new ElemeOpenApi\Config\Config($key,$secret,$webSite['debug']); $UserService = new ElemeOpenApi\OAuth\OAuthClient($config); $UUIDStr = $this->UUIDstr(); $r = $UserService->get_auth_url($UUIDStr,'all',$Rurl); file_put_contents('logs/OauthUrl.log', date('Y-m-d H:i:s') . ' reception:' . $r . PHP_EOL, FILE_APPEND); echo '<pre>'; var_dump($r);die; } /** * 获取饿了么推送订单 */ public function ELMOrdersAction() { $cancelOrderData = file_get_contents("PHP://input"); file_put_contents('logs/Porders.log', date('Y-m-d H:i:s') . ' reception:' . $cancelOrderData . ' &end' . PHP_EOL, FILE_APPEND); $orderDatas = json_decode($cancelOrderData, true); $orderInfo = json_decode($orderDatas['message'], true); $Order = $this->getordersAction($orderInfo['orderId']); # 订单详情 # 店铺详情 $Store = $this->getStoresByStoreIDAction($orderInfo['shopId']); file_put_contents('logs/synthesize_store.log', date('Y-m-d H:i:s') . ' storeInfo:' . json_encode($Store) .' &' . PHP_EOL, FILE_APPEND); file_put_contents('logs/synthesize_order.log', date('Y-m-d H:i:s') . ' orderInfo:' . json_encode($Order) .' &' . PHP_EOL, FILE_APPEND); echo '<pre>'; var_dump($Order); var_dump($Store); # 以下是第一次配置推送URL的时候 需要给饿了么返的信息,如果没有,或者写错 都可能造成回调地址配置不成功的问题。 $r = ['message'=>'ok']; echo json_encode($r); } /** * 回调 很多地方需要用到
   * 获取 code */ public function ELMReturnAction() { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $Rurl = (($webSite['debug']) ? self::JT_TEST_URL : self::ZP_URL).'?md=service&cl=ELM&at=ELMReturn'; $Tokencurl = (($webSite['debug']) ? self::ELM_SANDBox_TOKEN_URL : self::ELM_TOKEN_URL); $TokenParameter['code'] = $_GET['code']; $TokenParameter['grant_type'] = 'authorization_code'; $TokenParameter['redirect_uri'] = $Rurl; $TokenParameter['client_id'] = $key; if(!empty($TokenParameter['code'])){ $tr = $this->GetAccesstoken($Tokencurl, $TokenParameter); file_put_contents('logs/getToken.log', date('Y-m-d H:i:s') .$tr. PHP_EOL, FILE_APPEND); $TokenData = json_decode($tr, true); $TokenData['t'] = time(); # 令牌有效时间,单位秒,在令牌有效期内可以重复使用。有效期限制(access_token:沙箱环境为1天、正式环境为30天,refresh_token:沙箱环境为15天、正式环境为35天) file_put_contents('logs/TokenStr.txt', json_encode($TokenData)); echo '<pre>'; var_dump($TokenData); } } /** * 刷新token * curl -i -XPOST -H "Content-Type: application/x-www-form-urlencoded" * -H "Authorization: Basic OU9LV2JtVXJLcjoyZGRiZTc2NTkzOWZhZjI5ZDEwNTU3MDg3MzVjOGViNw==" * -d "grant_type=refresh_token&refresh_token=21a5b98083e13676c5fc3948df4f0852" * https://open-api-sandBox.shop.ele.me/token */ public function refreshTokenAction($refresh_token) { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $Tokencurl = (($webSite['debug']) ? self::ELM_SANDBox_TOKEN_URL : self::ELM_TOKEN_URL); $TokenParameter['grant_type'] = 'refresh_token'; $TokenParameter['refresh_token'] = $refresh_token; $tr = $this->GetAccesstoken($Tokencurl, $TokenParameter); $TokenData = json_decode($tr, true); $TokenData['t'] = time(); file_put_contents('logs/refreshToken.log', date('Y-m-d H:i:s') . ' reception:' . $tr . PHP_EOL, FILE_APPEND); file_put_contents('logs/TokenStr.txt', json_encode($TokenData)); return $TokenData; } /** * 获取Token * @param $url * @param $post_data * @return bool|false|string * curl -i -XPOST -H "Content-Type: application/x-www-form-urlencoded" * -H "Authorization: Basic OU9LV2JtVXJLcjoyZGRiZTc2NTkzOWZhZjI5ZDEwNTU3MDg3MzVjOGViNw==" * -d "grant_type=authorization_code&code=f5d9280fce5cedc761f1f19ef484e7e0&redirect_uri=[redirect_uri]&client_id=9OKWbmUrKr" * https://open-api-sandBox.shop.ele.me/token */ function GetAccesstoken($url, $post_data) { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $Basic = base64_encode($key .":". $secret); $header_data[] = "Content-type:application/x-www-form-urlencoded"; $header_data[] = "Authorization:Basic ". $Basic; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); $sResult = curl_exec($ch); if($sError=curl_error($ch)){ die($sError); } curl_close($ch); return $sResult; } /** * 获取饿了么订单 根据id * @param $K 应用的app key * @param $orderID 订单ID */ public function getordersAction($orderID){ $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $str = file_get_contents('logs/TokenStr.txt'); $str = json_decode($str,true); $token = $str['access_token']; $ntime = time(); $otime = $str['t']; $expires_in = $str['expires_in']; $otime = $otime + ($expires_in - 60); # 我这边所有使用到token的地方 过期时间都会减去一分钟 判断提前过期,防止存在时差 if($ntime >= $otime){ $TokenData = $this->refreshTokenAction($str['refresh_token']); $token = $TokenData['access_token']; } $config = new ElemeOpenApi\Config\Config($key,$secret,$webSite['debug']); $UserService = new \ElemeOpenApi\Api\OrderService($token,$config); $r = $UserService->get_order($orderID); file_put_contents('logs/order_ID_log', date('Y-m-d H:i:s') . ' reception:' . json_encode($r) . PHP_EOL, FILE_APPEND); return $r; // echo '<pre>'; // var_dump($r);die; } /** * 获取门店ID 通过token * Q:我想知道哪个token对应哪个门店,我该如何获取店铺ID?(门店授权如何知道这是哪家门店?) * A:可以调取接口eleme.user.getUser 获取店铺ID。 */ public function getStoresAction() { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $str = file_get_contents('logs/TokenStr.txt'); $str = json_decode($str,true); $token = $str['access_token']; $ntime = time(); $otime = $str['t']; $expires_in = $str['expires_in']; $otime = $otime + ($expires_in - 60); if($ntime >= $otime){ $TokenData = $this->refreshTokenAction($str['refresh_token']); $token = $TokenData['access_token']; } $config = new ElemeOpenApi\Config\Config($key,$secret,$webSite['debug']); $UserService = new ElemeOpenApi\Api\UserService($token,$config); $r = $UserService->get_user(); file_put_contents('logs/order_token_log.log', date('Y-m-d H:i:s') .json_encode($r). PHP_EOL, FILE_APPEND); echo '<pre>'; var_dump($r); } /** * 获取门店信息 通过店铺ID */ public function getStoresByStoreIDAction($storeID) { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $str = file_get_contents('logs/TokenStr.txt'); $str = json_decode($str,true); $token = $str['access_token']; $ntime = time(); $otime = $str['t']; $expires_in = $str['expires_in']; $otime = $otime + ($expires_in - 60); if($ntime >= $otime){ $TokenData = $this->refreshTokenAction($str['refresh_token']); $token = $TokenData['access_token']; } $config = new ElemeOpenApi\Config\Config($key,$secret,$webSite['debug']); $ShopService = new \ElemeOpenApi\Api\ShopService($token,$config); $r = $ShopService->get_shop($storeID); file_put_contents('logs/getStoresByStoreID.log', date('Y-m-d H:i:s') .json_encode($r). PHP_EOL, FILE_APPEND); return $r; // echo '<pre>'; // var_dump($r); } /** * 修改店铺 */ public function updateStoreAction() { $Config = Config::getInstance(); $webSite = $Config->getWebSiteConfig(); $secret = (($webSite['debug']) ? self::SANDBox_SECRET : self::SECRET); $key = (($webSite['debug']) ? self::SANDBox_KEY : self::KEY); $str = file_get_contents('logs/TokenStr.txt'); $str = json_decode($str,true); $token = $str['access_token']; $ntime = time(); $otime = $str['t']; $expires_in = $str['expires_in']; $otime = $otime + ($expires_in - 60); if($ntime >= $otime){ $TokenData = $this->refreshTokenAction($str['refresh_token']); $token = $TokenData['access_token']; } $shopID = 305179207; $properties = array(); $properties["addresstext"] = "上海市长宁区龙溪路虹桥路1923号"; $properties["geo"] = "121.223,31.233"; $properties["agentFee"] = 3.0; $properties["closeDescription"] = "正常营业"; $properties["deliverDescription"] = "超过5公里,100元起送"; // $properties["deliverGeoJson"] = '{"type":"FeatureCollection","features":[{"geometry":{"type":"polygon","coordinates":[[[121.381303,31.243521],[121.380938,31.242778],[121.381679,31.243297],[121.381303,31.243521]]]},"type":"Feature","properties":{"area_agent_fee":20,"delivery_price":10,"manual_weight":0,"system_weight":0,"weight_type\":1}}]}'; $properties["description"] = "便宜好吃的小食"; $properties["name"] = "烤鸭大王"; $properties["isBookable"] = 1; $properties["openTime"] = "10:00-13:00,18:00-21:00"; $properties["phone"] = "13666666666"; // $properties["logoImageHash"] = "13666666666"; $properties["promotionInfo"] = "本周全场半价"; $properties["invoice"] = 1; $properties["invoiceMinAmount"] = 100.0; $properties["noAgentFeetotal"] = 20.0; $properties["isOpen"] = 1; $properties["packingFee"] = 2.0; $properties["openId"] = "10046"; $config = new ElemeOpenApi\Config\Config($key,$secret,$webSite['debug']); $ShopService = new \ElemeOpenApi\Api\ShopService($token,$config); $r = $ShopService->update_shop($shopID, $properties); file_put_contents('logs/updateStore.log', date('Y-m-d H:i:s') .json_encode($r). PHP_EOL, FILE_APPEND); echo '<pre>'; var_dump($r); } /** * POST 请求 API * @param $url * @param $post_data * @return bool|string */ function http_post($url, $post_data) { $header_data[] = "application/json;charset=utf-8"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); $sResult = curl_exec($ch); $info = curl_getinfo($ch); if($sError=curl_error($ch)){ die($sError); } curl_close($ch); print_r($info); return $sResult; } /** * @return string 随机字符串 */ private function UUIDstr(){ return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } }

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...