[TOC] ## 获取小程序商品二维码 ### 必须post请求 ``` <script> $.post("/app/index.php?i=1&c=entry&m=ewei_shopv2&do=mobile&r=getcode&id={$_GPC['id']}",{},function(result){ // console.log(1111,result) $("#eweima").attr('src',"/app/index.php?i=1&c=entry&m=ewei_shopv2&do=mobile&r=getcode&id={$_GPC['id']}"); }); </script> ``` ``` $id = intval($_GPC['id']); $ret = $this->getCodeUnlimit(array('scene' => 'id=' . $id, 'page' => empty($id) ? 'pages/goods/index/index' : 'pages/goods/detail/index')); header('content-type: image/png'); exit($ret); ``` ``` public function getCodeUnlimit($params = array()) { if (empty($params) || !(is_array($params))) { return error(-1, '参数错误(params)'); } if (empty($params['scene']) || empty($params['page'])) { return error(-1, '参数错误(scenepage)'); } $accessToken = $this->getAccessToken(); if (is_error($accessToken)) { return error(-1, $accessToken['message']); } load()->func('communication'); $request = ihttp_post('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accessToken, json_encode($params)); $content = json_decode($request['content'], true); if (!(empty($content['errcode']))) { return error(-1, '(errcode: ' . $content['errcode'] . ') ' . $content['errmsg']); } return $request['content']; } ``` ``` public function getAccessToken() { global $_W; $appset = m('common')->getSysset('app'); $cacheKey = 'eweishop:wxapp:accesstoken:' . $_W['uniacid']; $accessToken = m('cache')->get($cacheKey, $_W['uniacid']); if (!(empty($accessToken)) && !(empty($accessToken['token'])) && (TIMESTAMP < $accessToken['expire'])) { return $accessToken['token']; } if (empty($appset['appid']) || empty($appset['secret'])) { return error(-1, '未填写小程序的 appid 或 appsecret!'); } load()->func('communication'); $content = ihttp_get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appset['appid'] . '&secret=' . $appset['secret']); if (is_error($content)) { return error(-1, '获取微信公众号授权失败, 请稍后重试!错误详情: ' . $content['message']); } $result = @json_decode($content['content'], true); if (empty($result) || !(is_array($result)) || empty($result['access_token']) || empty($result['expires_in'])) { $errorinfo = substr($content['meta'], strpos($content['meta'], '{')); $errorinfo = @json_decode($errorinfo, true); return error(-1, '获取微信公众号授权失败, 请稍后重试! 公众平台返回原始数据为: 错误代码-' . $errorinfo['errcode'] . ',错误信息-' . $errorinfo['errmsg']); } $record['token'] = $result['access_token']; $record['expire'] = (TIMESTAMP + $result['expires_in']) - 200; m('cache')->set($cacheKey, $record, $_W['uniacid']); return $result['access_token']; } ```