微信提供了一个回调的接口只要把我们的后台接口传过去微信就会调用我们的回调接口。
传的是xml的所以我们php段不能再用$_POST来接受微信回调传过来的数据。。
应该改成如下

1
$callback = file_get_contents('php://input');

callback就是微信传过来的回调内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<xml><appid><![CDATA[微信开放平台id]]></appid>
<bank_type><![CDATA[OTHERS]]></bank_type>
<cash_fee><![CDATA[金额]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[微信商户id]]></mch_id>
<nonce_str><![CDATA[andorid端生成的随机码]]></nonce_str>
<openid><![CDATA[支付人的微信id]]></openid>
<out_trade_no><![CDATA[微信商户订单号就是我们再android端生成的]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[签名]]></sign>
<time_end><![CDATA[20200131094904]]></time_end>
<total_fee>1</total_fee>
<trade_type><![CDATA[APP]]></trade_type>
<transaction_id><![CDATA[订单号]]></transaction_id>
</xml>

我们需要把他转换成array数组方便读取,代码如下

1
2
3
4
function xmlToArray($xml) {
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}

微信的金额单位不是元是分所以用下面代码转换成元

1
2
3
function priceFormat($price){
return number_format($price/100,2);
}

下面是完整代码

1
2
3
<?php
ini_set('date.timezone','Asia/Shanghai');//设置时间时区
$callback = file_get_contents('php://input');//获取微信传来的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$data = xmlToArray($callback);//xml转换成array
@$openid = $data['openid'];//获取支付用户的id
@$rmb = priceFormat($data['total_fee']);//获取支付金额分转元

if(!isset($openid) !isset($rmb))
return;

$time = strtotime("+1 months",time());
//根据不同的价格设置不同的时间
if($rmb == 12.00){
$time = strtotime("+1 months",time());
}else if($rmb == 18.00){
$time = strtotime("+4 months",time());
}else if($rmb == 28.00){
$time = strtotime("+6 months",time());
}else if($rmb == 48.00){
$time = strtotime("+1 years",time());
}
1
2
3
4
//写插入数据库内容
// openid isvip time

//写入微信用户的openid,会员状态和时间戳到数据库
1
2
3
4
5
6
7
8
function xmlToArray($xml) {
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}

function priceFormat($price){
return number_format($price/100,2);
}