public function getUserInfo($access_token,$openid)
{
$request_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//初始化一个curl会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = $this->response($result);
return $result;
}
3.获取用户资料接口
public function actionUserinfo() { if(isset($_REQUEST["openid"])){ $openid = $_REQUEST["openid"]; $user = WechatUser::find()->where(['openid'=>$openid])->one(); if ($user) { $result['error'] = 0; $result['msg'] = '获取成功'; $result['user'] = $user; } else { $result['error'] = 1; $result['msg'] = '没有该用户'; } } else { $result['error'] = 1; $result['msg'] = 'openid为空'; } return $result; }
三:微信支付
1.微信支付接口:打包支付数据
复制代码 代码如下:
public function actionPay(){
if(isset($_REQUEST["uid"])&&isset($_REQUEST["oid"])&&isset($_REQUEST["totalFee"])){
//uid、oid、totalFee
$uid = $_REQUEST["uid"];
$oid = $_REQUEST["oid"];
$totalFee = $_REQUEST["totalFee"];
$timestamp = time();
//微信支付参数
$appid = Yii::$app->params['wechat']['appid'];
$mchid = Yii::$app->params['wechat']['mchid'];
$key = Yii::$app->params['wechat']['key'];
$notifyUrl = Yii::$app->params['wechat']['notifyUrl'];
//支付打包
$wx_pay = new WechatPay($mchid, $appid, $key);
$package = $wx_pay->createJsBizPackage($uid, $totalFee, $oid, $notifyUrl, $timestamp);
$result['error'] = 0;
$result['msg'] = '支付打包成功';
$result['package'] = $package;
return $result;
}else{
$result['error'] = 1;
$result['msg'] = '请求参数错误';
}
return $result;
}
2.接收微信发送的异步支付结果通知
复制代码 代码如下:
public function actionNotify(){
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//
if ($postObj === false) {
die('parse xml error');
}
if ($postObj->return_code != 'SUCCESS') {
die($postObj->return_msg);
}
if ($postObj->result_code != 'SUCCESS') {
die($postObj->err_code);
}
//微信支付参数
$appid = Yii::$app->params['wechat']['appid'];
$mchid = Yii::$app->params['wechat']['mchid'];
$key = Yii::$app->params['wechat']['key'];
$wx_pay = new WechatPay($mchid, $appid, $key);
//验证签名
$arr = (array)$postObj;
unset($arr['sign']);
if ($wx_pay->getSign($arr, $key) != $postObj->sign) {
die("签名错误");
}
//支付处理正确-判断是否已处理过支付状态
$orders = Order::find()->where(['uid'=>$postObj->openid, 'oid'=>$postObj->out_trade_no, 'status' => 0])->all();
if(count($orders) > 0){
//更新订单状态
foreach ($orders as $order) {
//更新订单
$order['status'] = 1;
$order->update();
}
return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
} else {
//订单状态已更新,直接返回
return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
}
}
3.微信支付类 WechatPay.php
复制代码 代码如下: