I have been working on WeChat and encountered many pitfalls. I wrote it down today so that everyone can avoid detours. It is my first time to write text, which is a bit crude. If there is anything you don’t understand, you can contact me at QQ1034100429, or send a private message.
getaccesstoken Get access_token
//Initiate payment
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)
sendtpl sends template messages<?php<br />
/**<br />
* Created by PhpStorm.<br />
* User: Administrator<br />
* Date: 2016/4/11<br />
* Time: 22:43<br />
*/<br />
namespace Org;<br />
class Weixin<br />
{<br />
Private $appid; //Appid of WeChat official account<br />
Private $appsecret; //appsecret of WeChat public account<br />
Private $mchid; //The merchant account of the WeChat public account<br />
Private $wechatkey; //Payment key for WeChat official account<br />
private$token;<br />
Public function __construct()<br />
{<br />
$this->appid = C('WEIXIN_APPID');<br>
$this->appsecret = C("WEIXIN_APP_SECRET");<br>
$this->mchid = C("WEIXIN_MCHID");<br>
$this->wechatkey = C("WEIXIN_KEY");<br>
$this->token = C('WEIXIN_APP_TOKEN');<br>
<br>
}<br>
Public function chushi()<br>
{<br>
echo $this->getaccesstoken();<br>
}<br>
Public function checkSignature()<br>
{<br>
$signature = $_GET['signature'];<br>
$timestamp = $_GET['timestamp'];<br>
$nonce = $_GET['nonce'];<br>
$token = $this->token;<br>
$arrtemp = array($token, $timestamp, $nonce);<br>
sort($arrtemp, SORT_STRING);<br>
$arrtemp = implode($arrtemp);<br>
$arrtemp = sha1($arrtemp);<br>
If ($arrtemp == $signature) {<br>
return true;<br>
else {<br>
Return false; <br>
}<br>
}<br>
Public function valid()<br>
{<br>
$echoStr = $_GET['echostr'];<br>
If ($this->checkSignature()) {<br>
echo $echoStr;<br>
exit;<br>
}<br>
}<br>
////According to the returned information, make corresponding processing<br>
// public function responseMsg()<br>
// {<br>
// $postStr = file_get_contents('php://input');<br>
// if (!empty($postStr)){<br>
// /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,<br>
// the best way is to check the validity of xml by yourself */<br>
// libxml_disable_entity_loader(true);<br>
// $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);<br>// $fromUsername = $postObj->FromUserName;<br>
// $toUsername = $postObj->ToUserName;<br>
// $keyword = trim($postObj->Content);<br>
// $msgType = $postObj->MsgType;<br>
// $Event=$postObj->Event;<br>
// $time = time();<br>
// $textTpl = "<xml><br>
// <ToUserName><![CDATA[%s]]></ToUserName><br>
// <FromUserName><![CDATA[%s]]></FromUserName><br>
// <CreateTime>%s</CreateTime><br>
// <MsgType><![CDATA[%s]]></MsgType><br>
// <Content><![CDATA[%s]]></Content><br>
// <FuncFlag>0</FuncFlag><br>
// </xml>";<br>
// if(!empty( $keyword ))<br>
// {<br>
// $msgType = "text";<br>
// $contentStr = "Welcome to wechat world!";<br>
// $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br>
// echo $resultStr;<br>
// }else{<br>
// echo "Input something...";<br>
// }<br>
//<br>
// }else {<br>
// echo "";<br>
// exit;<br>
// }<br>
// }<br>
public function getaccesstoken()<br>
{<br>
$access_token = S('access_token');<br>
if(!empty($access_token)){<br>
<br>
return $access_token;<br>
}else{<br>
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;;<br>
$ret = $this->curlget($url);<br> $ret = json_decode($ret,true);<br>
S('access_token',$ret['access_token'],7100);<br>
<br>
return $ret['access_token'];<br>
}<br>
}<br>
//根据openid拉取用户信息<br>
public function userinfo($openid){<br>
$access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($url),true);<br>
return $userinfo;<br>
}<br>
function p($arr){<br>
echo "<meta charset='utf8'><pre class="brush:php;toolbar:false">";<br>
print_r($arr);<br>
}<br>
function curlget($url)<br>
{<br>
$ch = curl_init();<br>
curl_setopt($ch, CURLOPT_URL, $url);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($ch, CURLOPT_HEADER, 0);<br>
$output = curl_exec($ch);<br>
curl_close($ch);<br>
return $output;<br>
}<br>
public function jingmo($url,$code,$state){<br>
if($code){<br>
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";<br>
$arrtemp = json_decode($this->curlget($url),true);<br>
$ret = $this->getuserinfo($arrtemp['openid'],$arrtemp['access_token']);<br>
return $ret;<br>
}else{<br>
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";<br>
header("Location: $url");<br>
}<br>
}<br>
public function getuserinfo($openid,$user_access_token){<br>
$userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$user_access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($userurl),true);<br>
return $userinfo;<br>
}<br>
public function getjsapi_ticket(){<br>
$js_ticket = S("js_ticket");<br>
if(!empty($js_ticket)){<br>
return $js_ticket;<br>
}else{<br> $access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";<br>
$res = json_decode($this->curlget($url),true);<br>
S("js_ticket",$res['ticket'],7100);<br>
return $res['ticket'];<br>
}<br>
}<br>
public function getjssign(){<br>
echo "<meta charset='utf8'>";<br>
$js_ticket = $this->getjsapi_ticket();<br>
$time = time();<br>
$arr = array(<br>
'noncestr'=>md5($time),<br>
'jsapi_ticket'=>$js_ticket,<br>
'timestamp'=>$time,<br>
'url'=>'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],<br>
<br>
);<br>
$this->p($arr);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
echo $i;<br>
}<br>
// echo $string;<br>
$signature =strtolower($string);<br>
$signature = sha1($string);<br>
$jsconfig = array(<br>
'debug'=>true,<br>
'appId'=>$this->appid,<br>
'timestamp'=>$time,<br>
'nonceStr'=>md5($time),<br>
'signature'=>$signature,<br>
' jsApiList'=>"['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ']",<br>
);<br>
$json = json_encode($jsconfig);<br>
return $json;<br>
}<br>
//生成大写签名<br>
function createsign($arr,$biaozhi){<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br> $string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$signtemp = "$string&key=" . $this->wechatkey;<br>
$sign = strtoupper(MD5($signtemp));<br>
$arr[$biaozhi] = $sign;<br>
//$json = json_encode($arr);<br>
return $arr;<br>
}<br>
//支付<br>
<br>
//发起支付<br>
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)<br>
{<br>
$time = time();<br>
$arr = array(<br>
'appid' => $this->appid,<br>
'mch_id' => $this->mchid,<br>
'nonce_str' => md5($time),<br>
'body' => "kjhk",<br>
'out_trade_no' => $out_trade_no,<br>
'total_fee' => $total_fee,<br>
'spbill_create_ip' => "127.0.0.1",<br>
'notify_url' => $notify_url,<br>
'trade_type' => "JSAPI",<br>
'openid' => $openid,<br>
);<br>
$biaozhi ='sign';<br>
$arr = $this->createsign($arr,$biaozhi);<br>
$xml = "<xml>";<br>
foreach ($arr as $key=>$val) {<br>
$xml.="<".$key.">".$val."</".$key.">";<br>
}<br>
$xml.="</xml>";<br>
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";<br>
$resxml = $this->postCurlTransfer($url,$xml);<br>
$res = simplexml_load_string($resxml);<br>
$cutime = time();<br>
$jsapiarr=array(<br>
'appId'=>$this->appid,<br>
'timeStamp'=>"$cutime",<br>
'nonceStr'=>md5($cutime),<br>
'package'=>"prepay_id=".$res->prepay_id,<br>
'signType'=>"MD5",<br>
);<br> $biaozhi = 'paySign';<br>
$jsapi = $this->createsign($jsapiarr,$biaozhi);<br>
// $jsapijson = json_encode($jsapi);<br>
return $jsapi;<br>
}<br>
public function getpaysign(){<br>
$time = time();<br>
$arr = array(<br>
'appid'=>$this->appid,<br>
'mch_id'=>$this->mchid,<br>
'nonce_str'=>md5($time),<br>
'body'=>"sdf",<br>
'out_trade_no'=>"2016".$time,<br>
'total_fee'=>1,<br>
'spbill_create_ip'=>"127.0.0.1",<br>
'notify_url'=>"http://www.baidu.com",<br>
'trade_type'=>"JSAPI",<br>
);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$string.="&key=".$this->wechatkey;<br>
$sign = strtoupper(md5($string));<br>
$arr['sign'] = $sign;<br>
return $arr;<br>
}<br>
function Post($curlPost,$url){<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_HEADER, false);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>
curl_setopt($curl, CURLOPT_NOBODY, true);<br>
curl_setopt($curl, CURLOPT_POST, true);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);<br>
$return_str = curl_exec($curl);<br>
curl_close($curl);<br>
return $return_str;<br>
}<br>
private function postCurlTransfer($url, $data)<br>
{<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($curl, CURLOPT_POST, 1);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);<br> $str = curl_exec($curl);<br>
curl_close($curl);<br>
<br>
Return $ Str; <br>
}<br>
//Send template message<br>
Public function sendtpl($openid, $url, $template_id, $content, $topcolor="#FF0000")<br>
{<br>
$arr = array(<br>
'touser' => $openid,<br>
‘template_id’ => $template_id,<br>
'url' => $url,<br>
'topcolor' => $topcolor,<br>
'data' => $content,<br>
);<br>
$arrjson = json_encode($arr);<br>
$accesstoken = $this->getAccessToken();<br>
$sendurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accesstoken;<br>
return $this->postCurlTransfer($sendurl, $arrjson);<br>
}<br>
}
The above is a simple package of WeChat payment
If you initiate payment, please first correspond to the information of the WeChat official account.
Including WeChat payment directory
I am here
http://domain name//index.php/Home/Index/
It seems to be this
The process of obtaining access_token<?php<br />
/**<br />
* Created by PhpStorm.<br />
* User: sks<br />
* Date: 16/7/8<br />
* Time: 下午3:54<br />
*/<br />
namespace HomeController;<br />
use CommonControllerHomebaseController;<br />
Class WeixinController extends HomebaseController{<br />
Public function zhanshi(){<br />
$weixin = new OrgWeixin;<br />
$code = $_GET['code'];<br />
$state = $_GET['state'];<br />
$url="";<br />
$userinfo = $weixin->jingmo($url, $code, $state);<br>
Session('userinfo',$userinfo);<br>
if($code) {<br>
header("Location: $state");<br>
}else{<br>
}<br>
}<br>
}
Public function
function.phpfunction getuserinfo(){ //Get user information<br>
Import("weixin");<br>
$weixin = new OrgWeixin;<br>
$info = session('userinfo');<br>
If($info){<br>
Return $ info; <br>
die;<br>
}else {<br>
$state = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];<br>
$code =
$url = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/Weixin/zhanshi');<br>
$url = urlencode($url);<br>
$weixin->jingmo($url, $code, $state);<br>
}<br>
}<br>Test payment
/**
* Created by PhpStorm.
*User: sks
* Date: 16/7/8
* Time: 3:29 pm
*/
namespace HomeController;
use CommonControllerHomebaseController;
use ThinkPage;
Class IndexController extends HomebaseController{
//Test payment
Public function zhifu()
{
$userinfo = getuserinfo(); //Get WeChat user information and call the public function
$openid = $userinfo['openid'];
$time = time();
$title = "I want to pay";
$out_trade_no = date('Y',time()).$time.rand(1000,2000);
$total_fee = 1;
$notify_url = "http://domain name/index.php/Home/Index/paynotify";//Callback URL
$weixin = new OrgWeixin;
$result = $weixin->sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url);
$this->assign('result',$result);
$this->display();
}
//Here is the payment result notification
Public function paynotify(){
$weixin = new OrgWeixin;
$xml = file_get_contents("php://input");
$p = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$arr = $this->object_array($p);
$out_trade_no = $arr['out_trade_no'];
$transaction_id= $arr['transaction_id'];
$openid = $arr['openid'];
$sign = $arr['sign'];
//Processing payment results
unset($arr['sign']);
$biaozhi = "sign";
$ret = $weixin->createsign($arr, $biaozhi);
If($ret['sign'] === $sign) {
$aa = "Success";
else {
$aa = "Failure";
}
$file = './logweixin.txt';//The file name of the file to be written (can be any file name), if the file does not exist, it will be created
$content = $out_trade_no."***".$transaction_id."First written content n";
If($f = file_put_contents($file, $content,FILE_APPEND)){//This function supports version (PHP 5)
echo "Writing successful.
";
}
//The process of processing payment results here
echo "success";
}
Public function getaccesstoken(){
$weixin = new OrgWeixin;
echo $weixin->getaccesstoken();
}
}