第一步:获取access_token
获取
/*
* 获取基础access_token
*/
public static function getAccess_token(){
$obj = new self();
$accesstoken = \Yii::$app->redis->get('wechatAccessToken');
if ($accesstoken) {
return $accesstoken;
} else {
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$obj->appid.'&secret='.$obj->appsecret;
$response = Curl::curlGet($url);
$data = json_decode($response,true);
\Yii::$app->redis->set('wechatAccessToken', $data['access_token']);
\Yii::$app->redis->expire('wechatAccessToken', 7000);
return $data['access_token'];
}
}
第二步获取ticket ,存入redis中
/*
* 获取jsapi_ticket
*/
public static function getJsapi_ticket(){
$jsapi_ticket = \Yii::$app->redis->get('jsapi_ticket');
if ($jsapi_ticket) {
return $jsapi_ticket;
} else {
$access_token = self::getAccess_token();
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
$response = Curl::curlGet($url);
$data = json_decode($response,true);
\Yii::$app->redis->set('jsapi_ticket', $data['ticket']);
\Yii::$app->redis->expire('jsapi_ticket', 7000);
return $data['ticket'];
}
}
第三步:获取需要返回的签名
/*
* 对jsapi_ticket签名
*/
public static function getSignatureByTicket($data){
ksort($data);
$str = '';
foreach ($data as $k => $val){
$str .= $k.'='.$val.'&';
}
$str = trim($str,'&');
$signature = sha1($str);
return $signature;
}
第四步 返回需要组装的数组
$data['noncestr'] = Common::getRandStr(8);
$data['jsapi_ticket'] = WeChat::getJsapi_ticket();
$data['timestamp'] = time();
$data['url'] = \Yii::$app->request->hostInfo.\Yii::$app->request->getUrl();
$JsJdk['signature'] = WeChat::getSignatureByTicket($data);
$JsJdk['timestamp'] = $data['timestamp'];
$JsJdk['noncestr'] = $data['noncestr'];
$JsJdk['appId'] = \Yii::$app->params['wechat']['AppID'];
第五步获取 需要分享的参数
$share_config = array("title"=>'优惠券分享',"link"=>$data['url'],"imgUrl"=>'http://'.$_SERVER['HTTP_HOST'].'/application/images/fenxiang1.png',"desc"=>'分享代金券');