1.微信公众平台开通微信支付,审核通过。
2.微信商户平台配置支付授权目录
3.微信交易单号获取类
<?php
/*
* 生活服务_微信付款
*/
namespace Apis\Controller;
use Common\Controller\AppframeController;
class WxpayController extends AppframeController {
protected $mchid;
protected $appid;
protected $key;
public function _initialize() {
parent::_initialize();
$this->mchid = '1430532102'; // 微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$this->appid = 'wx20d62ad060e66486'; //公众号APPID 通过微信支付商户资料审核后邮件发送
$this->key = '8934e7d15453e97507ef7mao521125ab'; //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
}
public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp) {
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->key,
);
$unified = array(
'appid' => $config['appid'],
'attach' => '支付', //商家数据包,原样返回
'body' => $orderName,
'mch_id' => $config['mch_id'],
'nonce_str' => $this->createNonceStr(),
'notify_url' => $notifyUrl,
'openid' => $openid, //rade_type=JSAPI,此参数必传
'out_trade_no' => $outTradeNo,
'spbill_create_ip' => '127.0.0.1',
'total_fee' => intval($totalFee * 100), //单位 转为分
'trade_type' => 'JSAPI',
);
$unified['sign'] = $this->getSign($unified, $config['key']);
$responseXml = $this->curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($unified));
$unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($unifiedOrder === false) {
die('parse xml error');
}
if ($unifiedOrder->return_code != 'SUCCESS') {
die($unifiedOrder->return_msg);
}
if ($unifiedOrder->result_code != 'SUCCESS') {
die($unifiedOrder->err_code);
/*
NOAUTH 商户无此接口权限
NOTENOUGH 余额不足
ORDERPAID 商户订单已支付
ORDERCLOSED 订单已关闭
SYSTEMERROR 系统错误
APPID_NOT_EXIST APPID不存在
MCHID_NOT_EXIST MCHID不存在
APPID_MCHID_NOT_MATCH appid和mch_id不匹配
LACK_PARAMS 缺少参数
OUT_TRADE_NO_USED 商户订单号重复
SIGNERROR 签名错误
XML_FORMAT_ERROR XML格式错误
REQUIRE_POST_METHOD 请使用post方法
POST_DATA_EMPTY post数据为空
NOT_UTF8 编码格式错误
*/
}
//$unifiedOrder->trade_type 交易类型 调用接口提交的交易类型,取值如下:JSAPI,NATIVE,APP
//$unifiedOrder->prepay_id 预支付交易会话标识 微信生成的预支付回话标识,用于后续接口调用中使用,该值有效期为2小时
//$unifiedOrder->code_url 二维码链接 trade_type为NATIVE是有返回,可将该参数值生成二维码展示出来进行扫码支付
$arr = array(
"appId" => $config['appid'],
"timeStamp" => $timestamp,
"nonceStr" => $this->createNonceStr(),
"package" => "prepay_id=" . $unifiedOrder->prepay_id,
"signType" => 'MD5',
);
$arr['paySign'] = $this->getSign($arr, $config['key']);
return $arr;
}
public function notify() {
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->key,
);
$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);
}
$arr = (array) $postObj;
unset($arr['sign']);
if ($this->getSign($arr, $config['key']) == $postObj->sign) {
// $mch_id = $postObj->mch_id; //微信支付分配的商户号
// $appid = $postObj->appid; //微信分配的公众账号ID
// $openid = $postObj->openid; //用户在商户appid下的唯一标识
// $transaction_id = $postObj->transaction_id;//微信支付订单号
// $out_trade_no = $postObj->out_trade_no;//商户订单号
// $total_fee = $postObj->total_fee; //订单总金额,单位为分
// $is_subscribe = $postObj->is_subscribe; //用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
// $attach = $postObj->attach;//商家数据包,原样返回
// $time_end = $postObj->time_end;//支付完成时间
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
return $postObj;
}
}
/**
* curl get
*
* @param string $url
* @param array $options
* @return mixed
*/
public static function curlGet($url = '', $options = array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function curlPost($url = '', $postData = '', $options = array()) {
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function createNonceStr($length = 16) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
public static function arrayToXml($arr) {
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
$xml .= "</xml>";
return $xml;
}
/**
* 例如:
* appid: wxd930ea5d5a258f4f
* mch_id: 10000100
* device_info: 1000
* Body: test
* nonce_str: ibuaiVcKdpRxkhJA
* 第一步:对参数按照 key=value 的格式,并按照参数名 ASCII 字典序排序如下:
* stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_i
* d=10000100&nonce_str=ibuaiVcKdpRxkhJA";
* 第二步:拼接支付密钥:
* stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d"
* sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A9CF3B7"
*/
public static function getSign($params, $key) {
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false) {
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
//方法调用
$res = $wx->createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp);
3.回调函数
<?php
header('Content-Type: text/html; charset=utf-8');
$mysql_server_name='localhost'; //改成自己的mysql数据库服务器
$mysql_username='root'; //改成自己的mysql数据库用户名
$mysql_password='Pa1mtrends'; //改成自己的mysql数据库密码
$mysql_database='cloud'; //
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password) or die("error connecting") ; //连接数据库
mysql_query("set names 'utf8'"); //数据库输出编码 应该与你的数据库编码保持一致.南昌网站建设公司百恒网络PHP工程师建议用UTF-8 国际标准编码.
mysql_select_db($mysql_database); //打开数据库
$mchid = '143053xxxx'; // 微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = 'wx20d62ad06xxxxx'; //公众号APPID 通过微信支付商户资料审核后邮件发送
$key = '8934e7d15453e97507ef7mao5xxxxxx'; //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$config = array(
'mch_id' => $mchid,
'appid' => $appid,
'key' => $key,
);
$postStr = file_get_contents("php://input");
if (!$postStr) {
$postStr = "maozi";
}
$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);
}
$arr = (array) $postObj;
unset($arr['sign']);
if (getSign($arr, $config['key']) == $postObj->sign) {
$mch_id = $postObj->mch_id; //微信支付分配的商户号
$appid = $postObj->appid; //微信分配的公众账号ID
$openid = $postObj->openid; //用户在商户appid下的唯一标识
$transaction_id = $postObj->transaction_id;//微信支付订单号
$out_trade_no = $postObj->out_trade_no;//商户订单号
$total_fee = $postObj->total_fee; //订单总金额,单位为分
$total_fee = floatval($total_fee/100);
$time_end = $postObj->time_end;//支付完成时间
$time_end = strtotime(substr($time_end,0,4)."-".substr($time_end, 4,2)."-".substr($time_end,6,2)." ".substr($time_end,8,2).":". substr($time_end, 10, 2).":".substr($time_end, 12, 2));
//用户id
$res = mysql_query("select * from cmf_market_order where sn='{$out_trade_no}'",$conn);
$oinfo = mysql_fetch_assoc($res);
$uid = $oinfo['uid'];
//查询订单是否存在
$has_sql = "select * from cmf_market_order_wx where wx_sn='{$transaction_id}'";
$has = mysql_query($has_sql,$conn);
$has = mysql_fetch_assoc($has);
if ($has) {
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
exit;
}
//插入微信订单信息
$sql = "insert into cmf_market_order_wx (mch_id,appid,openid,uid,sn,wx_sn,total,time) values ('{$mch_id}','{$appid}','{$openid}','{$uid}','{$out_trade_no}','{$transaction_id}','{$total_fee}','{$time_end}')";
$result = mysql_query($sql,$conn);
if ($result) {//更新订单状态
$up_sql = "update cmf_market_order set haspay=1,status=1,paytime='{$time_end}' where sn='{$out_trade_no}'";
$result_update = mysql_query($up_sql,$conn);
}
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
return $postObj;
}
function getSign($params, $key) {
ksort($params, SORT_STRING);
$unSignParaString = formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
function formatQueryParaMap($paraMap, $urlEncode = false) {
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
?>
4.支付页面,直接调用支付接口
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>微信安全支付</title>
<script type="text/javascript">
//调用微信JS api 支付
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
"appId": "{$info['appId']}",
"timeStamp": "{$info['timeStamp']}",
"nonceStr": "{$info['nonceStr']}",
"package": "{$info['package']}",
"signType": "MD5",
"paySign": "{$info['paySign']}"
},
function(res){
if (res.err_msg == 'get_brand_wcpay_request:ok') {
alert("支付成功");
window.location.href = 'http://www.baidu.com';
} else {
alert("错误");
}
}
);
}
function callpay()
{
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
jsApiCall();
}
}
</script>
</head>
<body>
</br></br></br></br>
<div align="center">
<button style="width:210px; height:30px; background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" >贡献一下11111111</button>
</div>
</body>
</html>